flutter - 使用 MediaQuery.of(context) 时未找到 MediaQuery 小部件祖先
问题描述
我收到一条错误消息,提示在使用 MediaQuery.of(context) 时未找到 MediaQuery 小部件祖先。这是我的代码,我在 MaterialApp 中使用MediaQuery.of(context)但它仍然给我错误。有人可以帮忙吗?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Responsive'),
),
body: SingleChildScrollView(
child: Column(
children: [
Container(
color: Colors.red,
height: mediaQuery.size.height,
),
Container(
color: Colors.amber,
height: 200,
),
],
),
),
),
);
}
}
错误
解决方案
您收到此错误是因为您MediaQuery
的MaterialApp
. 使用材料主页作为 Statefull 小部件的独立无状态。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return MaterialApp(
home: Home();
}
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return Scaffold(
appBar: AppBar(
title: Text('Responsive'),
),
body: SingleChildScrollView(
child: Column(
children: [
Container(
color: Colors.red,
height: mediaQuery.size.height,
),
Container(
color: Colors.amber,
height: 200,
),
],
),
),
);
}
}
推荐阅读
- mysql - 带有 Docker 的 Google Cloud SQL 代理抛出连接被拒绝
- javascript - 有没有办法覆盖 Mapbox Geocoder 上的结果事件?
- spring - 为什么我的 return 语句返回 null 结果?
- java - 以下语句在 HashMap 方面有什么区别?
- java - Glassfish 服务器启动时出现异常
- javascript - GraphQL:将数据库列获取到不同的 ObjectType 字段属性
- reactjs - 是否可以更改 Context.Consumer 的显示名称?
- angular - 无法将 html2canvas 中的画布添加到 jspdf addHTML() 方法
- json - 没有无限过滤链的 JQ 对象选择
- c - C中的数组可以存储在非顺序指针中吗?