【发布时间】:2020-07-27 02:36:50
【问题描述】:
当我尝试在我的应用程序中使用 MediaQuery 时,我收到以下错误:
“使用不包含 MediaQuery 的上下文调用 MediaQuery.of()”
我做了一些研究,我读到的所有内容都表明,如果我使用 MaterialApp 或 WidgetsApp,我应该可以访问 MediaQuery。
但是,我在使用 MediaQuery 的位置使用 MaterialApp 作为父小部件...所以我不明白为什么我无法在我使用的上下文中访问 MediaQuery...??
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
List<Map<String, String>> elementList;
String elementName;
MyApp() {
this.elementName = "TestName";
this.elementList = List<Map<String, String>>();
this.elementList.add({"element1": "Value1"});
this.elementList.add({"element2": "Value2"});
this.elementList.add({"element3": "Value3"});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Column(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.15,
child: UNavbar(),
),
Container(
height: MediaQuery.of(context).size.height * 0.7,
child: ListView.builder(
itemBuilder: (ctx, index) {
return UNode(elementName, elementList);
}
)
),
Container(
height: MediaQuery.of(context).size.height * 0.15,
alignment: Alignment.bottomCenter,
child: UTextbox(),
),
],
),
);
}
}```
【问题讨论】:
-
你不需要任何
MediaQuery.of- 你需要的是Flexible.flex属性 -
谢谢,这看起来是一种更简洁的对齐方式。但我仍然想知道为什么在这种情况下我无法访问 MediaQuery。
-
因为您使用的
context是MaterialApp的父级,而不是它的子级
标签: flutter