![](/img/trans.png)
[英]MaterialApp and "MediaQuery.of() called with a context that does not contain a MediaQuery"
[英]MediaQuery.of() called with a context (from MaterialApp) that does not contain a MediaQuery
所以......我得到這個異常,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?
只是為了擴展我的評論,這是您需要做的。
您的材料應用程序將如下所示
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.