【发布时间】:2020-02-17 07:41:20
【问题描述】:
所以...我得到这个异常,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?
【问题讨论】:
-
确实如此,但这不是您使用的 BuildContext。您正在使用根 BuildContext,它被传递给您的
build函数,该函数返回一个 MaterialApp,它有自己独立的 BuildContext,这是您想要的。将home替换为builder,这是一个具有此签名的函数:(BuildContext context, Widget child)。这将为您提供 MediaQuery 可以工作的 BuildContext。 -
发生这种情况是因为您正在材料应用程序或小部件之外访问 MediaQuery,因此您需要将 Scaffold 提取到 (Material )Widget 并且这将起作用。在下面查看我的答案
标签: flutter