Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix the problem of 'Object of type XXXXX is not registered inside GetIt' in flutter?

I am trying to use get_it in order to create a singleton object to be used. I do not wish to use multiple objects of API which is connecting to Firebase. The singleton object is that of Api call for firebase.

I have used the following code

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

while following code works

locator.registerLazySingleton<TeamViewModel>(() => new TeamViewModel()) ;

The structure of Api class is as follows:

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() ;
  }
}`

This is how I use the API singleton object:

Api _api = locator<Api>();

while the following code works fine:

Api _api = Api('team');

I get the following error in console:

I/flutter ( 2313): The following _Exception was thrown building MultiProvider:

I/flutter ( 2313): Exception: Object of type Api is not registered inside GetIt

I wish to know if this is even possible of using getit is not the right way to go about this.

like image 260
Arpit Bansal Avatar asked Sep 06 '19 22:09

Arpit Bansal


2 Answers

Try the following code on your main function.

GetIt locator = GetIt.instance;

void main() {

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

  runApp(MyApp());
}

Or try to have a separate file for your service locator like:

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());
  ...
}

main.dart

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  setUpServiceLocator();
  runApp(MyApp());
}

some_file.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);
like image 197
freeman29 Avatar answered Sep 30 '22 22:09

freeman29


don't forget to call setupLocator in your main app file before App init

  setupLocator();
  runApp(MyApp());
like image 37
Loki Avatar answered Oct 01 '22 00:10

Loki