dart_service_locator 1.0.0 dart_service_locator: ^1.0.0 copied to clipboard
A lightweight, flexible dependency injection solution for Flutter applications, supporting both synchronous and asynchronous dependency resolution with minimal boilerplate.
Flutter Service Locator #
A lightweight and easy-to-use dependency injection package for Flutter applications.
Features #
- Simple API for registering and resolving dependencies
- Support for both synchronous and asynchronous dependency resolution
- Singleton and factory instance management
- Built-in disposal mechanism for cleaning up resources
- Minimal boilerplate code required
Installation #
Add this to your package's pubspec.yaml
file:
dependencies:
flutter_service_locator: ^1.0.0
copied to clipboard
Then run:
$ flutter pub get
copied to clipboard
Usage #
Setting up dependencies #
import 'package:flutter_service_locator/service_locator.dart';
void setupDependencies() {
// Register a synchronous dependency
register<Logger>(() => ConsoleLogger());
// Register an asynchronous dependency
registerAsync<Database>(() async {
final db = Database();
await db.initialize();
return db;
});
// Register a dependency that relies on other dependencies
registerAsync<UserRepository>(() async {
final db = await singleton<Database>();
return UserRepository(db);
});
}
copied to clipboard
Using dependencies #
import 'package:flutter_service_locator/service_locator.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder<UserRepository>(
future: singleton<UserRepository>(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final userRepo = snapshot.data!;
// Use userRepo
return Text('User count: ${userRepo.getUserCount()}');
} else {
return CircularProgressIndicator();
}
},
);
}
}
copied to clipboard
Cleaning up #
import 'package:flutter_service_locator/service_locator.dart';
void cleanUp() async {
await clearLocator();
}
copied to clipboard
API Reference #
register<T>(T Function() creator)
: Register a synchronous dependencyregisterAsync<T>(Future<T> Function() creator)
: Register an asynchronous dependencysingleton<T>()
: Get or create a singleton instance of a dependencycreate<T>()
: Create a new instance of a dependencyremove<T>()
: Remove a singleton instance of a dependencyisRegistered<T>()
: Check if a dependency is registeredclearLocator()
: Clear all registered dependencies
Examples #
For more advanced usage and examples, check out the example folder in the package repository.
Additional Information #
For more information on using this package, please refer to the API documentation.
Contributing #
Contributions are welcome! Please feel free to submit a Pull Request.
License #
This project is licensed under the BSD-3-Clause license - see the LICENSE file for details.