MediaQuery
一般情况下,我们会使用如下方式去获取 widget 的宽高:
final size =MediaQuery.of(context).size;
final width =size.width;
final height =size.height;
但是如果不注意,这种写法很容易报错,例如下面的写法就会报错:
import ‘package:flutter/material.dart’;
class GetWidgetWidthAndHeiget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final size =MediaQuery.of(context).size;
final width =size.width;
final height =size.height;
print(‘width is $width; height is $height’);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(‘Width & Height’),
),
body: Container(
width: width / 2,
height: height / 2,
),
),
);
}
}
在代码中,我们是想获取屏幕的宽和高,然后将屏幕宽高的一半分别赋值给 Container
的宽和高,但上述代码并不能成功运行,会报如下错误:
flutter: The following assertion was thrown building GetWidgetWidthAndHeiget(dirty):
flutter: MediaQuery.of() called with a context that does not contain a MediaQuery.
flutter: No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
flutter: This can happen because you