【问题标题】:Cant use MediaQuery.of(context) for Themes in Flutter不能在 Flutter 中将 MediaQuery.of(context) 用于主题
【发布时间】:2020-11-10 03:31:00
【问题描述】:

您好,我正在尝试创建几个TextTheme,并根据这篇文章使用MediaQuery.of(context) 更改字体大小:

Flutter — Effectively scale UI according to different screen sizes

但我收到此错误:

使用不包含 MediaQuery 的上下文调用 MediaQuery.of()。

根据这篇文章我知道了:Flutter Error: MediaQuery.of() called with a context that does not contain a MediaQuery

我应该在我的主页上使用MediaQuery,但是我不能使用MediaQuery 创建主题?

这是我的代码:

  child:
    MaterialApp(
            theme: ThemeData(
                /// TextFields Handlers transparent
                textSelectionHandleColor: Colors.transparent,
                pageTransitionsTheme: const PageTransitionsTheme(
                  builders: <TargetPlatform, PageTransitionsBuilder>{
                    TargetPlatform.android: ZoomPageTransitionsBuilder(),
                  },
                ),
                textTheme: TextTheme(
                  /// Pages Titles
                  headline1: textTheme(
                    fontSize: (MediaQuery.of(context).size.width / 100) * 1.5,
                    fontWeight: FontWeight.w600,
                    color: Globals.allColors['celeste'],
                  ),
                  headline2: textTheme(
                      fontSize: 15,
                      fontWeight: FontWeight.w600,
                      color: Globals.allColors['cetaceanBlue']),
                      ...

错误在:

(MediaQuery.of(context).size.width / 100) * 1.5,

提前致谢!

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    尝试将整个主页包装在构建器小部件中。

    【讨论】:

    • 尝试使用Builder 上方的小部件MaterialApp 时遇到同样的错误,感谢您的回答
    【解决方案2】:

    不,您不能使用从 Mediaquery 检索到的值创建材料主题。您在材料应用程序主题数据中设置“默认”字体大小等。然后在您的主页构建方法中调用 Mediaquery 并根据需要修改该页面的字体大小。

    【讨论】:

    • 很遗憾,根据每个设备分辨率调整字体大小会很有用,使用themes 而不是在整个代码中使用.copyWith 更改它们。感谢您的回答格雷厄姆
    • 很高兴我能帮上忙。
    猜你喜欢
    • 2021-06-08
    • 2021-03-23
    • 2022-01-20
    • 2021-12-02
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2020-04-29
    相关资源
    最近更新 更多