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.
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);
don't forget to call setupLocator in your main app file before App init
setupLocator();
runApp(MyApp());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With