Should we use Provider or GetIt to inject dependency of signal service class? #216
-
Description Context: We want to decouple the signal service class from dependent components. Provider:Pros: Cons: GetIt:Pros: Cons: Discussion Points:Which approach aligns better with the overall design philosophy of the signals library? Additional Information: I hope this discussion helps us determine the best way to handle dependency injection for the signal service class. Let's share our thoughts and experiences! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
I would suggest Provider, lite_ref(my package) or something that hooks into the lifecycle of widgets because signals are disposable and GetIt wouldn't know when to dispose them. Therefore, using GetIt for disposables doesn't make much sense unless it's for long-lived signals (eg. Apptheme). Provider/lite_ref also allow easy mocking. In the example below, the class Controller {
late final _count = signal(0);
// we expose it as a readonly
// so it cannot be changed from outside the controller.
ReadonlySignal<int> get count => _count;
void increment() => _count.value++;
void decrement() => _count.value--;
void dispose() {
_count.dispose()
}
}
final countControllerRef = Ref.scoped((ctx) => Controller());
class CounterText extends StatelessWidget {
const CounterText({super.key});
@override
Widget build(BuildContext context) {
final controller = countControllerRef.of(context);
final count = controller.count.watch(context);
return Text('$count');
}
} In my signals package (state_beacon). I created a class Controller extends BeaconController {
late final _count = B.writable(0);
// we expose it as a readable beacon
// so it cannot be changed from outside the controller.
ReadableBeacon<int> get count => _count;
void increment() => _count.value++;
void decrement() => _count.value--;
}
final countControllerRef = Ref.scoped((ctx) => Controller());
class CounterText extends StatelessWidget {
const CounterText({super.key});
@override
Widget build(BuildContext context) {
final count = countControllerRef.select(context, (c) => c.count);
return Text('$count');
}
} |
Beta Was this translation helpful? Give feedback.
-
Created a new guide about it! |
Beta Was this translation helpful? Give feedback.
Created a new guide about it!
https://dartsignals.dev/guides/dependency-injection/