Create a file called my_service.dart. In it make an abstract class that defines the functionality of your service.
abstract class MyService {
Future<int> getSomeValue();
Future<void> doSomething(int value);
}
Create a file called my_service_impl.dart. Extend your MyService class and implement the required methods.
import 'my_service.dart';
class MyServiceImpl extends MyService {
@override
Future<int> getSomeValue() async {
// do something
return someValue;
}
@override
Future<void> doSomething(int value) async {
// do something
}
}
Add the GetIt service locator package to pubspec.yaml.
dependencies:
get_it: ^3.1.0
Create a file called service_locator.dart. Register your service implementation.
import 'package:get_it/get_it.dart';
import 'my_service_impl.dart';
import 'my_service.dart';
GetIt locator = GetIt.instance;
setupServiceLocator() {
locator.registerLazySingleton<MyService>(() => MyServiceImpl());
}
Initialize the service locator before you run the app in main.dart.
void main() {
setupServiceLocator();
runApp(MyApp());
}
Get a reference to your service from anywhere in your code using the service locator.
class MyClass {
MyService _myService = locator<MyService>();
...
}
Then you can use it within that class like this:
_myService.getSomeValue()
_myService.doSomething(someValue)