如果你适配使用的是 :
flutter_screenutil: ^5.9.3
并且你将 ScreenUtil.init 放在 MyApp 中进行初始化,那么恭喜你,遇到了和我一样的错误。
我接手的别人的项目,这个错误在debug模式下运行没有问题,当打release包后,安卓安装运行发现页面空白,布局不显示,然后调试,发现ScreenUtil这个插件适配代码无效。
原因就是初始化方式错误,官方提供了两种初始化方法:
第一种,ScreenUtilInit:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
//Set the fit size (Find your UI design, look at the dimensions of the device screen and fill it in,unit in dp)
return ScreenUtilInit(
designSize: const Size(360, 690),
minTextAdapt: true,
splitScreenMode: true,
// Use builder only if you need to use library outside ScreenUtilInit context
builder: (_ , child) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'First Method',
// You can use the library anywhere in the app even in theme
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: Typography.englishLike2018.apply(fontSizeFactor: 1.sp),
),
home: child,
);
},
child: const HomePage(title: 'First Method'),
);
}
}
第二种,ScreenUtil.init(官方推荐混合开发使用第二种方法):
void main() async {
// Add this line
await ScreenUtil.ensureScreenSize();
runApp(MyApp());
}
...
MaterialApp(
...
builder: (ctx, child) {
ScreenUtil.init(ctx);
return Theme(
data: ThemeData(
primarySwatch: Colors.blue,
textTheme: TextTheme(bodyText2: TextStyle(fontSize: 30.sp)),
),
child: HomePage(title: 'FlutterScreenUtil Demo'),
);
},
)
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter_ScreenUtil',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(title: 'FlutterScreenUtil Demo'),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
//Set the fit size (fill in the screen size of the device in the design)
//If the design is based on the size of the 360*690(dp)
ScreenUtil.init(context, designSize: const Size(360, 690));
...
}
}
ScreenUtil.init这个方法一般放在根路由即第一个页面加载的时候进行初始化, 因为这个时候还没加载 MaterialApp 无法使用 MediaQuery.of(context ) 获取到屏幕宽高。