'Flutter GetIn can't find the method of the services

I'm setting up a project with Flutter. I want to register services with GetIn. But I'm not able to find the methods of the service that I want to use.

This is the class locator in which I register the service, for example MongoDBService.

import 'package:app/services/mongodb.dart';
import 'package:get_it/get_it.dart';

final locator = GetIt.instance;
    
setupLocator() {
    locator.registerSingleton<MongoDBService>(MongoDBService());
}

Then when I want to use the MongoDBService I am not able to find the functions that belong to the service.

void connect() async {
    await mongo.beginConnection();
}
  
final mongo = locator<MongoDBService>;

The error is on beginConnection which is not defined. But currently it is defined in the MongoDBService.

Also I setup the locator by calling the setupLocator function in the main.

void main() {
    setupLocator();
    runApp(const MyApp());
}


Solution 1:[1]

Put final mongo = locator<MongoDBService>; in the connect method.

void connect() async {
    final mongo = locator<MongoDBService>();
    await mongo.beginConnection();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1