问题描述
我一直试图在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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!