[英]MediaQuery.of() called with a context that does not contain a MediaQuery even when Wrapped under the MaterialApp Widget
I can't access the MediaQuery.of() in the MaterialApp widget within the themeData method referencing the screenHeight & screenWidth variables. 我无法在引用screenHeight和screenWidth变量的themeData方法内的MaterialApp小部件中访问MediaQuery.of()。
I've tried to wrap the HomeScreen widget within a MaterialApp widget itself followed by a Scaffold widget, but this did not help. 我试图将HomeScreen小部件包装在MaterialApp小部件本身中,然后将其包装在Scaffold小部件中,但这没有帮助。
class MyApp extends StatelessWidget {
MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final screenHeight = MediaQuery.of(context).size.height / 100;
final screenWidth = MediaQuery.of(context).size.width / 100;
return MaterialApp(
title: 'MyApp',
theme: ThemeData(
primaryColor: Color.fromRGBO(231, 13, 61, 1),
textTheme: new TextTheme(
title: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: screenHeight * 1.8,),
body1: new TextStyle(color: Colors.black, fontSize: screenHeight * 1.8,),
),
),
home: HomeScreen(),
);
}
}
class _HomeScreen extends State {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppNavBar(),
body: Container(
color: Colors.white,
child: ListView(
children: <Widget> [
new Page1Widget(),
Divider(height: 0, color: Colors.grey,),
new Page2Widget(),
],
),
),
bottomNavigationBar: new BottomNavBar(),
);
}
}
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ flutter: The following assertion was thrown building MyApp(dirty): flutter: MediaQuery.of() called with a context that does not contain a MediaQuery. 颤振:W小工具库引起的异常CA ════════════════════flutter:在构建MyApp(dirty)时引发了以下断言:flutter:在不包含MediaQuery的上下文中调用MediaQuery.of() 。 flutter: No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
颤抖:从传递给MediaQuery.of()的上下文开始,找不到MediaQuery祖先。 flutter: This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce flutter: a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
颤动:之所以会发生这种情况,是因为您没有WidgetsApp或MaterialApp小部件(这些小部件引入了颤动:MediaQuery),或者如果您使用的上下文来自那些小部件上方的小部件,则可能会发生这种情况。 flutter: The context used was: flutter: MyApp(dirty)
flutter:使用的上下文是:flutter:MyApp(dirty)
Only descendants of MediaQuery
can access it. 只有
MediaQuery
后代才能访问它。 Which means you cannot build MaterialApp.theme
based on theme. 这意味着您不能基于主题构建
MaterialApp.theme
。
If you need to, you can use MaterialApp.builder
: 如果需要,可以使用
MaterialApp.builder
:
MaterialApp(
builder: (context, child) {
MediaQuery.of(context);
return Theme(
child: child,
);
},
home: ...
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.