问题描述
我一直在尝试获取 Flutter 中整个上下文视图的大小.但是每次我尝试时都会遇到上述错误.这是我的代码:
I have been trying to get the size of the whole context view in Flutter. But every time I try I'm getting the above mentioned error. Here's my code:
import 'package:flutter/material.dart';
void main => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return new MaterialApp(
home: new Scaffold(),
);
}
}
注意:我也尝试过使用 StatefulWidget
.请帮我找出我在这里做错了什么.
Note: I also tried with a StatefulWidget
. Please, help me find what I'm doing wrong here.
推荐答案
您需要一个 MaterialApp
或一个 WidgetsApp
围绕您的小部件.他们提供MediaQuery
.当您调用 .of(context)
时,flutter 将始终查找小部件树以找到小部件.
You need a MaterialApp
or a WidgetsApp
around your widget. They provide the MediaQuery
. When you call .of(context)
flutter will always look up the widget tree to find the widget.
您通常在 main.dart 中有这个:
You usually have this in your main.dart:
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Title',
theme: kThemeData,
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Container(
child: ...,
);
}
}
这篇关于Flutter 错误:使用不包含 MediaQuery 的上下文调用 MediaQuery.of()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!