flutter_ScreenUtil 3.0版本和之前的老版本初始化不一样,之前的老版本初始化如下:
ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);新版本采用了
designSize来进行初始化。但是,新版按照官方的来会有问题:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
//设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
ScreenUtil.init(constraints, designSize: Size(750, 1334), allowFontScaling: false);
return MaterialApp(
...
);
},
);
}
}
如果按照上面的来,无法执行,把
ScreenUtil.init(constraints, designSize: Size(750, 1334), allowFontScaling: false);中的
constraints替换成context又会报下面的错误: MediaQuery.of() called with a context that does not contain a MediaQuery.
查看了flutter_ScreenUtil插件源码,发现里面使用了下面这句话:
MediaQueryData mediaQuery = MediaQuery.of(context);网上查找了下,出现这句话的意思是由于祖先控件没有包含MediaQuery,所以使用MediaQuery.of(context)报错,可以使用MaterialApp或者WidgetsApp包装你自己组件。那么将
ScreenUtil.init(context, designSize: Size(750, 1334), allowFontScaling: false);放到“MaterialApp”中即可:
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '国祯E健康',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: ConfigColor.PRIMARY_COLOR,
),
onGenerateRoute: Application.router.generator,
home: MyApp2()
);
}
}
class MyApp2 extends StatelessWidget{
@override
Widget build(BuildContext context) {
//设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
ScreenUtil.init(context, designSize: Size(750, 1334), allowFontScaling: false);
return LaunchPage();
}
}
这是迫不得已的解决办法,本来一个StatelessWidget就能解决,现在却要多加个,如果您有更好的解决办法,欢迎留言。 