[英]Error while using MediaQuery for size of height and width in flutter
I was writing a code for my flutter application.我正在为我的 flutter 应用程序编写代码。 In that I needed to get size of screen of mobile so I used Media Query but error occurred saying "MediaQuery was called with no context" but I was passing the context.
因为我需要获取移动设备屏幕的大小,所以我使用了 Media Query,但发生错误说“MediaQuery was called without context”,但我正在传递上下文。 Here is the code
这是代码
class MainPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return MaterialApp(
title: 'Text',
home: Scaffold(
body: Container(
height: height,
width: width,
),
),
);
}
}
How can I solve this error.我该如何解决这个错误。 Please help.
请帮忙。 Thanks in advance.
提前致谢。
You can't do the MediaQuery.of(context) call in the MaterialApp create Methode, because the app does not know anything about the Media.您不能在 MaterialApp 创建方法中执行 MediaQuery.of(context) 调用,因为该应用程序对媒体一无所知。 The error message is
错误信息是
MediaQuery.of() call with a context that does not contain a MediaQuery
You can use this call after the app is running but not in the start up sequence.您可以在应用程序运行后使用此调用,但不能在启动顺序中使用。
Maybe you create an extra widget underneath the MaterialApp.也许您在 MaterialApp 下创建了一个额外的小部件。 Then it would work.
然后它会工作。
It should be working by the way anyways run flutter clean
from cmd or your console and then try running the app.无论如何,它应该可以正常运行
flutter clean
从 cmd 或您的控制台运行,然后尝试运行该应用程序。
If it is not working then directly give the height and the width of the scaffold
, MediaQuery.of(context).size.height,
and MediaQuery.of(context).size.width,
respectively and some modifications like this:如果不行就直接给出
scaffold
的高度和宽度, MediaQuery.of(context).size.height,
MediaQuery.of(context).size.width,
.size.width,并做如下修改:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('text'),
),
body: Container(
color:Colors.red, //Only to se if the container is being displayed.
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
),
);
}
}
This would definitely work.这肯定会奏效。 if you still face any difficulties then you can ask in the comments.
如果您仍然遇到任何困难,那么您可以在评论中提问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.