使用Injectable与GetIt时LocalUserService注册失败但DemoService正常的问题求助
Injectable与GetIt时LocalUserService注册失败但DemoService正常的问题求助
我在Flutter项目中使用Injectable和GetIt时遇到了一个特别奇怪的问题,想请大家帮忙排查下原因。
问题具体场景
我有两个服务类,都用@lazySingleton注解标记为懒汉单例:
// DemoService.dart import 'package:injectable/injectable.dart'; @lazySingleton class DemoService {}
// LocalUserService.dart import 'package:injectable/injectable.dart'; @lazySingleton class LocalUserService {}
但当我用GetIt获取实例时,结果完全不一样:
final DemoService service = getIt(); // ✅ 完全正常,能拿到实例 final LocalUserService service = getIt(); // ❌ 直接抛出错误
错误提示如下:
Bad state: GetIt: Object/factory with type LocalUserService 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?)
我已经自查过的所有点
- 反复确认
LocalUserService类上确实加了@lazySingleton注解,没有遗漏 - 执行过完整的代码生成命令:
flutter pub run build_runner build --delete-conflicting-outputs,全程没有报错 - 打开自动生成的
injection.config.dart,确认LocalUserService已经被包含在配置代码里 main()函数中已经在最开始调用了configureDependencies()- GetIt的初始化完全正确:
final getIt = GetIt.instance;,没有写成GetIt.instance() - 相同的配置逻辑下,
DemoService可以完美获取实例,没有任何问题
我的pubspec.yaml配置
name: time_tally description: "A new Flutter project." publish_to: 'none' version: 1.0.0+1 environment: sdk: ^3.7.2 dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.8 firebase_core: ^3.13.0 cloud_firestore: ^5.6.7 isar_flutter_libs: path: ./local_packages/isar_flutter_libs isar: ^3.1.0+1 path_provider: ^2.1.5 flutter_bloc: ^9.1.1 freezed_annotation: ^2.4.1 json_annotation: ^4.7.0 firebase_auth: ^5.5.3 injectable: ^2.5.0 get_it: ^8.0.3 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^5.0.0 isar_generator: ^3.1.0+1 build_runner: ^2.4.13 freezed: ^2.4.5 json_serializable: ^6.7.1 injectable_generator: ^2.3.0 flutter: uses-material-design: true
实在搞不懂为什么两个类配置完全一致,结果却天差地别,有没有大佬遇到过类似的问题?求指点!
内容来源于stack exchange
相关产品推荐
相关产品推荐

