【问题标题】:How to set MediaQuery textScaleFactor throughout the application and not for each page如何在整个应用程序中而不是为每个页面设置 MediaQuery textScaleFactor
【发布时间】:2021-11-30 20:27:16
【问题描述】:

主要

final query = MediaQuery.of(context);

return MediaQuery(
  data: query.copyWith(textScaleFactor: 1.4),
  child: MaterialApp(
     title: "Flutter Demo",
     initialRoute: '/loginPage',
  )
);
 ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (13775): The following assertion was thrown building MyApp(dirty, state: _MyAppState#38690):
I/flutter (13775): MediaQuery.of() called with a context that does not contain a MediaQuery.
I/flutter (13775): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
I/flutter (13775): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
I/flutter (13775): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.

使用 MediaQuery 类及其 data 属性,我想为整个应用程序设置 textScaleFactor,但我无法获得MaterialApp...

之前的上下文

所以我不想为每个页面都添加像 parent 这样的类,我怎么能只为整个应用程序添加一次类?

LoginPage(它有效,但我不想要这个)

final query = MediaQuery.of(context);

return MediaQuery(
  data: query.copyWith(textScaleFactor: 1.4),
  child: Scaffold(
     [...]
  );

谢谢,

【问题讨论】:

标签: flutter dart


【解决方案1】:

最简单的方法是用另一个 MaterialApp 包装 MaterialApp 并设置useInheritedMediaQuery:

    return MaterialApp(
      home: LayoutBuilder(
        builder: (context, _) { # builder so we can access MaterialApp context
          final query = MediaQuery.of(context);
          return MediaQuery(
              data: query.copyWith(textScaleFactor: 1.4),
              child: MaterialApp( 
                  useInheritedMediaQuery: true, #inherited MediaQuery will be used
                  ....

另一种方法是使用WidgetsBinding.instance.window.physicalSizehttps://stackoverflow.com/a/60415290/4679965

【讨论】:

  • 它没有显示任何错误,但它显然不像那样工作,它不读取 MediaQuery 数据,以及我的第二个 MaterialApp 的属性,例如 debugShowCheckedModeBanner。跨度>
  • WidgetsBinding.instance.window.physicalSize 的问题还在于它没有用于 MediaQuery 的 copyWith
  • 需要添加useInheritedMediaQuery: true参数,更新答案
  • 哦,好的,好吧,我的 Flutter 没有更新到 2.0 所以... xD 但是还是谢谢!
猜你喜欢
  • 2019-12-11
  • 2016-07-16
  • 2014-11-19
  • 2016-06-18
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
相关资源
最近更新 更多