【问题标题】:MediaQuery.of() called with a context that does not contain a MediaQuery even when Wrapped under the MaterialApp Widget使用不包含 MediaQuery 的上下文调用 MediaQuery.of(),即使包装在 MaterialApp 小部件下
【发布时间】:2019-12-18 03:56:19
【问题描述】:

我无法在引用 screenHeight 和 screenWidth 变量的 themeData 方法中的 MaterialApp 小部件中访问 MediaQuery.of()。

我尝试将 HomeScreen 小部件包装在 MaterialApp 小部件本身中,然后是 Scaffold 小部件,但这没有帮助。

class MyApp extends StatelessWidget {
  MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final screenHeight = MediaQuery.of(context).size.height / 100;
    final screenWidth = MediaQuery.of(context).size.width / 100;

    return MaterialApp(
      title: 'MyApp',
      theme: ThemeData(
        primaryColor: Color.fromRGBO(231, 13, 61, 1),
        textTheme: new TextTheme(
          title: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: screenHeight * 1.8,),
          body1: new TextStyle(color: Colors.black, fontSize: screenHeight * 1.8,),

        ),

      ),
      home: HomeScreen(),
    );
  }
}

class _HomeScreen extends State {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppNavBar(),

      body: Container(
        color: Colors.white,
        child: ListView(
          children: <Widget> [
            new Page1Widget(),
            Divider(height: 0, color: Colors.grey,),
            new Page2Widget(),
          ],
        ),
      ),
        bottomNavigationBar: new BottomNavBar(),

    );
  }
}

颤振:══╡小部件库╞══════════════════════════════ ═══════════════════════ 颤振:在构建 MyApp(dirty) 时抛出了以下断言: 颤振:使用不包含 MediaQuery 的上下文调用 MediaQuery.of()。 颤振:从传递给 MediaQuery.of() 的上下文开始,找不到 MediaQuery 祖先。 颤振:这可能是因为您没有 WidgetsApp 或 MaterialApp 小部件(这些小部件引入 Flutter:一个 MediaQuery),或者如果您使用的上下文来自这些小部件上方的小部件,则可能会发生这种情况。 颤振:使用的上下文是: 颤振:MyApp(脏)

【问题讨论】:

    标签: flutter


    【解决方案1】:

    只有MediaQuery 的后代可以访问它。这意味着您不能基于主题构建MaterialApp.theme

    如果需要,可以使用MaterialApp.builder

    MaterialApp(
      builder: (context, child) {
        MediaQuery.of(context);
        return Theme(
          child: child,
        );
      },
      home: ...
    )
    

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2020-02-17
      • 2020-11-22
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      相关资源
      最近更新 更多