get<T extends Object> static method
Gets a dependency of type T
from the closest EasyModule in the widget tree.
This method searches up the widget tree for a EasyModuleInheritedWidget
and
retrieves the requested dependency from its module's injector.
The listen
parameter determines if the widget should rebuild when the module changes.
If true, the widget will rebuild when the module notifies its listeners.
If false, the widget will not rebuild when the module changes (default).
Throws an Exception if the dependency is not found.
Example:
// Without listening to changes
final repository = Module.get<UserRepository>(context);
// With listening to changes - widget will rebuild when module changes
class _MyWidgetState extends State<MyWidget> {
late UserService _userService;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_userService = Module.get<UserService>(context, listen: true);
}
@override
Widget build(BuildContext context) {
return Text(_userService.username);
}
}
Implementation
static T get<T extends Object>(BuildContext context, {bool listen = false}) {
final closestModule = EasyModule.of(context, listen: listen);
if (closestModule == null) {
throw Exception('No $EasyModule found in the widget tree');
}
if (closestModule.injector == null) {
throw Exception('$EasyModule ${closestModule.runtimeType} is not initialized');
}
try {
final response = closestModule.injector!.get<T>();
return response;
} catch (e) {
throw Exception('Type $T not found in module ${closestModule.runtimeType}: $e');
}
}