How to parameterise a container? #174
-
Or put another way, how to pass existing state into the container. Consider the following: int countCapsule(CapsuleHandle _) => 0;
main() {
int startingCount = 3;
final container = CapsuleContainer();
final count = container.read(countCapsule);
}
How could you configure the countCapsule to use the startingCount? Context: I'm using Drift and for tests I want to configure it to use an in memory database whereas for production I want to use a file based database. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 9 replies
-
My solution would be this: extension _ConvenienceExtension on SideEffectRegistrar {
SideEffectRegistrar get use => this;
}
extension SideEffectExtension on SideEffectRegistrar {
CountController myCounter([int? initialValue]) {
final counter = use.data(initialValue ?? 0);
return CountController(
count: counter.value,
increment: () => counter.value++,
reset: () => counter.value = initialValue ?? 0,
);
}
}
class CountController {
CountController({
required this.count,
required this.increment,
required this.reset,
});
final int count;
final void Function() increment;
final void Function() reset;
} final counterController = use.myCounter(3); I use a class instead of a Record for the controller because VSCode doesn't work very well with Records, but the outcome would be the same with a Record. |
Beta Was this translation helpful? Give feedback.
-
I see there's an experimental MockableContainer. I wonder if there's a more general solution though, something along the lines of: typedef Config = (startingCount: int);
CapsuleContainer<Config>(config: (startingCount: 3));
int countCapsule(CapsuleHandler use) {
final config = use.containerConfig<Config>();
return config.startingCount;
};
final count = use(countCapsule); Riverpod also has the concept of overrides which achieves the same but feels a bit off because it requires you to have a "default" implementation which you may never even use. |
Beta Was this translation helpful? Give feedback.
@opsb for your particular case that sparked this question, you could do:
NOTE: I haven't tested the above, but I see no reason it shouldn't work.
The environment variables idea posted previously can also help for s…