如何在Flutter中获得屏幕高度

ergxz8rk  于 2022-11-25  发布在  Flutter
关注(0)|答案(2)|浏览(139)

嗨,我只是想用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,
        ),
      ),
    );
  }
}

dauxcl2d

dauxcl2d1#

已编辑

您必须在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.)
dced5bon

dced5bon2#

我找到了你的问题的答案,你需要为它添加safeArea

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,
          ),
        ),
      ),
    );
  }
}

相关问题