【问题标题】:How to get screen height in flutter如何在颤动中获得屏幕高度
【发布时间】:2022-01-13 20:13:25
【问题描述】:

嗨,我只是想用 MediaQuery.of(context).size.height 但得到FlutterError (No MediaQuery widget ancestor found. MyApp widgets require a MediaQuery widget ancestor. The specific widget that could not find a MediaQuery ancestor was: MyApp The ownership chain for the affected widget is: "MyApp ← [root]" No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). This can happen because you have not added a WidgetsApp, CupertinoApp, or MaterialApp widget (those widgets introduce a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.)

class BaseLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          height: MediaQuery.of(context).size.height,
          color: Colors.red,
        ),
      ),
    );
  }
}

【问题讨论】:

标签: flutter dart mobile


【解决方案1】:

已编辑

您必须将它放在 MediaQuery 上下文的上下文之上:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BaseLayout()
    );
  }
}

class BaseLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          height: MediaQuery.of(context).size.height,
          color: Colors.red,
        ),
      ),
    );
  }
}

创建一个自己的类,你的错误应该消失了。

原始答案

您的小部件树中有 MaterialApp 吗? MaterialApp 提供了 MediaQuery。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      body:WhateverWidget
    );
  }
}

顺便说一句...解决方案在您的错误代码中;)

This can happen because you have not added a WidgetsApp, CupertinoApp, or MaterialApp widget (those widgets introduce a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.)

【讨论】:

  • 嗨@MCB 我的代码中有 MaterialApp 小部件,但它仍然向我显示错误。更新了我的代码,你可以参考一下
【解决方案2】:

嘿,托尼,我找到了你问题的答案 你需要为它添加安全区域

class BaseLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Container(
            height: MediaQuery.of(context).size.height,
            color: Colors.red,
          ),
        ),
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2010-12-28
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多