使用不包含MediaQuery的上下文(来自MaterialApp)调用MediaQuery.of()

时间:2019-10-21 08:31:31

标签: flutter

所以...我得到了一个例外,即MediaQuery.of是在不包含MediaQuery的上下文中调用的。

代码:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
    double topPadding = getRelativeTopPadding(context);

    return MaterialApp(
    home: Scaffold(
        body: Stack(
        children: <Widget>[
            Align(
            alignment: Alignment.center,
            child: Container(
                margin: const EdgeInsets.only(right: 15, left: 15),
                child: Column(children: <Widget>[
                new Padding(
                    padding: EdgeInsets.only(top: topPadding),
                ),
                ],),
            ),
            ),
        ],
        ),
    ),
    );
}

double getRelativeTopPadding(BuildContext context) {
    return MediaQuery.of(context).size.width * 0.5;
}
}

例外:

I/flutter ( 6765): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 6765): The following assertion was thrown building MyApp(dirty):
I/flutter ( 6765): MediaQuery.of() called with a context that does not contain a MediaQuery.
I/flutter ( 6765): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
I/flutter ( 6765): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
I/flutter ( 6765): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
I/flutter ( 6765): The context used was:
I/flutter ( 6765):   MyApp(dirty)

我做错了什么?我以为MaterialApp的BuildContext确实包含MediaQuery?

1 个答案:

答案 0 :(得分:1)

请继续补充我的评论,这是您需要做的。

您的材料应用将看起来像这样

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var materialApp = MaterialApp(home: HomePage());
    return materialApp;
  }
}

您的首页应该是这样


class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double topPadding = getRelativeTopPadding(context);
    return Scaffold(
      body: Container(
        child: Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Container(
                padding: EdgeInsets.only(top: topPadding),
                margin: const EdgeInsets.only(right: 15, left: 15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    // new Padding(
                    // padding: EdgeInsets.only(top: topPadding),
                    // ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  double getRelativeTopPadding(BuildContext context) {
    return MediaQuery.of(context).size.width * 0.5;
  }
}