使用flutter_screenutil遇LateInitializationError问题求助
解决flutter_screenutil的LateInitializationError问题
问题原因
你在ScreenUtilInit的child属性中直接传入MaterialApp,且在MaterialApp的theme里使用了.sp、.h这类flutter_screenutil的扩展方法。但theme会在ScreenUtilInit完成初始化之前被构建,导致内部的_minTextAdapt字段未初始化,从而抛出错误。
解决方案
改用ScreenUtilInit的builder属性替代child,确保ScreenUtil初始化完成后再构建MaterialApp及其中的theme:
修改后的完整代码:
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:spoon_app/screens/splash_screen/mobile.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); runApp(const Spoon()); } class Spoon extends StatelessWidget { const Spoon({super.key}); @override Widget build(BuildContext context) { return ScreenUtilInit( designSize: const Size(375, 812), minTextAdapt: true, splitScreenMode: true, // 使用builder替代child,确保ScreenUtil初始化完成后再构建MaterialApp builder: (context, child) { return MaterialApp( theme: ThemeData( scaffoldBackgroundColor: const Color(0XFFFFFFFF), textTheme: TextTheme( bodySmall: TextStyle( fontSize: 14.sp, fontFamily: "Alex", fontWeight: FontWeight.w400, height: 1.3.h, ), bodyMedium: TextStyle( fontSize: 12.sp, fontFamily: "Alex", fontWeight: FontWeight.w700, ), bodyLarge: const TextStyle( color: Colors.white, fontSize: 18, fontFamily: "Alex", fontWeight: FontWeight.w700, ), headlineMedium: const TextStyle( fontSize: 32, fontWeight: FontWeight.w500, ), headlineLarge: TextStyle( fontFamily: "Alex", fontSize: 32.sp, fontWeight: FontWeight.w500, ) ), ), debugShowCheckedModeBanner: false, title: "SpoonApp", home: MobileWelcomeScreen(), ); }, ); } }
补充说明
builder回调会在ScreenUtil完成所有初始化工作后触发,此时context已包含ScreenUtil的状态,调用.sp、.h等扩展方法时能正常访问到初始化后的_minTextAdapt字段,不会再抛出未初始化错误。
内容的提问来源于stack exchange,提问作者maak akasha
相关产品推荐
相关产品推荐

