如何解决flutter中'XXXXX类型的对象未在GetIt内部注册'的问题?

Arp*_*sal 9 android firebase flutter flutter-dependencies

我正在尝试使用 get_it 来创建要使用的单例对象。我不希望使用多个连接到 Firebase 的 API 对象。单例对象是 Api 调用 firebase 的对象。

我使用了以下代码

locator.registerLazySingleton<Api>(() => new Api('teams')) ;
Run Code Online (Sandbox Code Playgroud)

当以下代码有效时

locator.registerLazySingleton<TeamViewModel>(() => new TeamViewModel()) ;
Run Code Online (Sandbox Code Playgroud)

Api类的结构如下:

class Api{
  final Firestore _db = Firestore.instance;
  final String path;
  CollectionReference ref;
  
  Api( this.path ) {
    ref = _db.collection(path);
  }

  Future<QuerySnapshot> getDataCollection() {
     return ref.getDocuments() ;
  }
}`
Run Code Online (Sandbox Code Playgroud)

这就是我使用 API 单例对象的方式:

Api _api = locator<Api>();
Run Code Online (Sandbox Code Playgroud)

虽然以下代码工作正常:

Api _api = Api('team');
Run Code Online (Sandbox Code Playgroud)

我在控制台中收到以下错误:

I/flutter (2313):在构建 MultiProvider 时抛出了以下 _Exception:

I/flutter(2313):异常:Api 类型的对象未在 GetIt 内注册

我想知道这是否甚至可能使用 getit 不是解决此问题的正确方法。

Lok*_*oki 13

不要忘记在应用程序初始化之前在主应用程序文件中调用 setupLocator

  setupLocator();
  runApp(MyApp());
Run Code Online (Sandbox Code Playgroud)

  • 什么是“setupLocator”?我找不到它的参考资料。 (4认同)

fre*_*n29 5

在您的 main 函数上尝试以下代码。

GetIt locator = GetIt.instance;

void main() {

  locator.registerLazySingleton<Api>(() => new Api('teams')) ;

  runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)

或者尝试为您的服务定位器创建一个单独的文件,例如:

service_locator.dart

GetIt sl = GetIt.instance;

final httpLink = HttpLink(...);

final GraphQLClient client = GraphQLClient(
  cache: InMemoryCache(),
  link: httpLink,
);

void setUpServiceLocator() {
  // Services
  sl.registerSingleton<LocationsService>(LocationsService(http.Client()));
  ...

  // Managers
  sl.registerSingleton<LocationsManager>(LocationsManager());
  ...
}
Run Code Online (Sandbox Code Playgroud)

主程序.dart

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  setUpServiceLocator();
  runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)

一些_文件.dart

import 'package:my_awesome_app/service_locator.dart';

...
// call it anywhere you want on your code
sl<LocationsManager>().updateLocationsCommand.execute(query);

// or
sl.get<LocationsManager>().updateLocationsCommand.execute(query);
Run Code Online (Sandbox Code Playgroud)

  • 但问题仍然是一样的。 (2认同)