如果你適配使用的是 :
flutter_screenutil: ^5.9.3
并且你將 ScreenUtil.init 放在 MyApp 中進(jìn)行初始化,那么恭喜你,遇到了和我一樣的錯誤。
我接手的別人的項目,這個錯誤在debug模式下運(yùn)行沒有問題,當(dāng)打release包后,安卓安裝運(yùn)行發(fā)現(xiàn)頁面空白,布局不顯示,然后調(diào)試,發(fā)現(xiàn)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(官方推薦混合開發(fā)使用第二種方法):
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這個方法一般放在根路由即第一個頁面加載的時候進(jìn)行初始化, 因為這個時候還沒加載 MaterialApp 無法使用 MediaQuery.of(context ) 獲取到屏幕寬高。