MediaQuery.of() called with a context that does not contain a MediaQuery.

今天用Flutter中MediaQuery在获取屏幕的宽高的时候一直报错,报错信息如下:

MediaQuery.of() called with a context that does not contain a MediaQuery.\n'
'No MediaQuery ancestor could be found starting from the context that was passed '
'to MediaQuery.of(). This can happen because you do not have a WidgetsApp or '
'MaterialApp widget (those widgets introduce a MediaQuery), or it can happen '
'if the context you use comes from a widget above those widgets.\n'
'The context used was:

根据字面意思就是无法冲上下文获取到MediaQuery,需要在MaterialApp或者WidgetsApp里面使用才可行。不过自己看了半天也没看出所以然,后来偶然在一篇文章上面看到了解决方案具体如下:在MaterialApp里面创建个statelesswidget,使用这里面的上下文去获取MediaQuery的使用。

class LoadDart extends State {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      title: "LoadActivity",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    // TODO: implement build
    return new Stack(
      children: <Widget>[
        new Center(
          child: new Image.asset(
            "images/load_bg.png",
            fit: BoxFit.fill,
            height: size.height,
          ),
        ),
        new Positioned(
          left: 50,
          right: 50,
          top: size.height / 2,
          child: new Image.asset(
            "images/load_center.png",
          ),
        ),
      ],
    );
  }
}

从这句话我终于理解到在MaterialApp或者WidgetsApp里面使用才可行了。

猜你喜欢

转载自blog.csdn.net/fl2502923/article/details/89209915