Flutter GetIt 插件 - 在 GetIt 中未注册类型 xxx

10
我按照示例项目的设置进行了所有操作:
import 'package:get_it/get_it.dart';
import 'package:places/services/authService.dart';

final locator = GetIt.instance;

void setupLocator() {
  locator.registerSingleton<AuthService>(AuthService());
  print("registered");
}

在主文件中调用
void main() {
  setupLocator();
  runApp(MyApp());
}

我有一些检查,其中定位器也正确返回了我的AuthService。

class AuthGuardView extends StatefulWidget {
  AuthGuardView({Key key}) : super(key: key);

  @override
  _AuthGuardViewState createState() => _AuthGuardViewState();
}

class _AuthGuardViewState extends State<AuthGuardView> {
  @override
  Widget build(BuildContext context) {
    return ViewModelProvider<AuthGuardViewModel>.withConsumer(
      viewModel: AuthGuardViewModel(),
      onModelReady: (model) => model.initialise(),
      builder: (context, model, child) => model.isLoggedIn
          ? Container(
              color: Colors.white,
              child: Text("Logged In"),
            )
          : SignUpView(),
    );
  }
}


class AuthGuardViewModel extends ChangeNotifier {
  AuthService _authService = locator<AuthService>();
  bool isLoggedIn = false;

  void initialise() async {
    isLoggedIn = await _authService.isLoggedIn();
    notifyListeners();
  }
}

如果我在SignUpView的ViewModel中做完全相同的事情,会出现以下错误。
flutter: The following assertion was thrown building SignUpView(dirty, state: _SignUpViewState#01129):
flutter: No type AuthService is registered inside GetIt.
flutter:  Did you forget to pass an instance name?
flutter: (Did you accidentally do  GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;did you
flutter: forget to register it?)
flutter: 'package:get_it/get_it_impl.dart':
flutter: Failed assertion: line 248 pos 14: 'instanceFactory != null'

在AuthGuard的ViewModel中,我成功地检索了auth服务。我还注释掉了locator代码(因为我认为它可能是异步调用或类似的东西),但是相同的错误仍然存在。
我正在使用get_it: ^4.0.1,但是当降级到3.x.x时,错误仍然存在。

enter image description here

这里是SignUpViewModel

class SignUpViewModel extends ChangeNotifier {
  SignUpViewModel(){
    if(locator.isRegistered<AuthService>()) {
      AuthService _authService = locator<AuthService>();
    } 
  }
  var textInputFormatter = [
    WhitelistingTextInputFormatter(RegExp(r'\d')),
    PhoneNumberTextInputFormatter()
  ];
  var textEditingController;
  var context;
}

这很有趣。你在哪里创建视图模型? 如果你给我访问你的项目,我可以自己尝试一下。 - Thomas
我已经撤销了更改并切换到了纯提供程序/更改通知体系结构。但是所有的代码都在问题中。我在ViewModel.withconsumer()调用(在ViewModel下)中创建ViewModels :S 我这里有一个项目(除了不使用firebase auth之外,具有相同的设置(尚未注册单例,因此没有错误)https://github.com/lunaticcoding/MilleSandersApp(开发人员分支有您要找的内容) - Marco Papula
如果您提供您的Github账号,我可以为您提供访问正确仓库的权限(但您需要使用旧的提交记录)。 - Marco Papula
句柄是escamoteur。 - Thomas
哦,我的错。你也在 GitLab 上吗?:O - Marco Papula
我想我从未推送过那段代码,但我立即修复了它 :S 抱歉 :S - Marco Papula
5个回答

13

当被注册为 singleton 的类有异步方法时,会出现这种情况。要解决这个问题,您需要在运行 runApp() 之前等待单例完全生成。

void main() async {

/*  WidgetsFlutterBinding.ensureInitialized() is required in Flutter v1.9.4+ 
 *  before using any plugins if the code is executed before runApp. 
 */
  WidgetsFlutterBinding.ensureInitialized();


// Configure injecction
   await setupLocator();

   runApp(MyApp());
}

实际上,只需要一行代码 await setupLocator();。旧的代码 Api _api = locator<Api>(); 保持不变。 - w461
我等待了设置函数,但仍然出现错误。 - lordvidex
您是使用代码生成还是手动注册单例模式?请问我能否看一下您注册和调用单例模式的截图链接? - Loïc Fonkam

4

我添加这个答案,因为我认为它可能会帮助其他人!

我之前也遇到过同样的问题,对我来说,这是由于排序问题造成的。所以请确保先初始化/声明依赖对象,然后再实例化/声明相关对象。


1
使用最新的get_it版本(现在是get_it:^4.0.2)在pubspec.yaml中解决了我的问题。

2
我正在使用相同的get_it版本,但仍然遇到相同的问题。 - ikhsanudinhakim

0
在我的情况下,GetIt在我的导入语句上遇到了困难。为了使其正常工作,您需要使用包导入而不是相对导入。
请按照以下步骤操作:
import 'package:mypackage/features/some_file.dart';

不是:

import '../features/some_file.dart';

-1

我也遇到过这个问题。一开始完全不知所措。后来我想起来,我最近进行了区分大小写的重命名。

我将 Services/Database/Database.dart 改为了 services/database/database.dart,但在一个文件中,我使用了小写版本的导入,而在另一个文件中,仍然是大写版本。统一项目中的大小写是我需要的解决方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接