已注册AuthBloc仍触发GetIt未注册错误的技术求助
GetIt 中 AuthBloc 已注册但无法获取的问题
错误信息
Object/factory with type AuthBloc is not registered inside GetIt. (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance; Did you forget to register it?) 'package:get_it/get_it_impl.dart': get_it_impl.dart:1 Failed assertion: line 372 pos 7: 'instanceFactory != null'
已完成的注册配置
我已经通过injectable生成的代码注册了AuthBloc,相关代码如下:
extension GetItInjectableX on _i1.GetIt { // initializes the registration of main-scope dependencies inside of GetIt Future<_i1.GetIt> init({ String? environment, _i2.EnvironmentFilter? environmentFilter, }) async { final gh = _i2.GetItHelper( this, environment, environmentFilter, ); final firebaseInjectableModule = _$FirebaseInjectableModule(); gh.lazySingleton<_i3.FirebaseAuth>( () => firebaseInjectableModule.firebaseAuth); gh.lazySingleton<_i4.FirebaseFirestore>( () => firebaseInjectableModule.firestore); gh.lazySingleton<_i5.IAuthCredentials>(() => _i6.FirebaseAuthenticator( gh<_i3.FirebaseAuth>(), gh<_i7.GoogleSignIn>(), gh<_i4.FirebaseFirestore>(), )); gh.factory<_i8.LoginFormBloc>( () => _i8.LoginFormBloc(gh<_i5.IAuthCredentials>())); await gh.factoryAsync<_i9.SharedPreferences>( () => firebaseInjectableModule.prefs, preResolve: true, ); gh.factory<_i10.AuthBloc>(() => _i10.AuthBloc(gh<_i5.IAuthCredentials>())); return this; } } class _$FirebaseInjectableModule extends _i11.FirebaseInjectableModule {}
触发错误的调用代码
但在MyAppWidget中调用getIt<AuthBloc>()时仍触发上述错误:
class MyAppWidget extends StatelessWidget { const MyAppWidget({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (context) => getIt<AuthBloc>()..add(const AuthEvent.authCheckRequested()), ), ], child: MaterialApp.router( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, textTheme: const TextTheme( displayLarge: TextStyle(fontSize: 16.0), displaySmall: TextStyle(fontSize: 15.0), displayMedium: TextStyle(fontSize: 15.0), ), ), routerConfig: AppRouter.router, ), ); } }
可能的解决方案
- 确保GetIt初始化完成:必须在调用
getIt<AuthBloc>()前执行await getIt.init()完成依赖注册,比如在main函数中先初始化再启动App:void main() async { WidgetsFlutterBinding.ensureInitialized(); await getIt.init(); runApp(const MyAppWidget()); } - 检查环境匹配:如果使用了injectable的环境标识,确认当前运行环境和注册时的环境一致,否则对应实例不会被注册。
- 验证GetIt实例一致性:确保
getIt是全局单例的GetIt.instance,避免错误写法GetIt sl = GetIt.instance();(多了括号会创建新实例)。 - 重新生成injectable代码:清理缓存后重新生成,执行
flutter pub run build_runner clean,再运行flutter pub run build_runner build。 - 检查类型匹配:确认
getIt<AuthBloc>()中的AuthBloc和注册代码里的_i10.AuthBloc是同一个类,避免导入错误的同名类。
内容的提问来源于stack exchange,提问作者Gbenga B Ayannuga
相关产品推荐
相关产品推荐

