How to pass an initialization param to a capsule from build? #184
-
I've been trying to figure out how to pass parameters in when creating a capsule. Here's my two attempts:
(String, Function(String)) counter(CapsuleHandle use, int initialValue) {
return use.state(initialValue);
} RearchBuilder(builder: (context, use) {
final (count, setCount) = counter(use, 3);
}); This results in a compilation error because
(String, Function(String)) Function(int) counter(CapsuleHandle use) {
return (initialCount) => use.state(initialCount)
} final (count, setCount) = use(counter)(3); This time there's a runtime error What's the right approach here? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 15 replies
-
You can't modify the capsule signature, so you can't pass initialization params to a capsule. You can read params from another capsule or you can modify a capsule (like the example CounterController counterCapsule(CapsuleHandle use) {
final count = use.data(0);
return CounterController(
count: count.value,
increment: () => count.value++,
set: (newValue) => count.value = newValue,
);
}
class CounterController {
CounterController({
required this.count,
required this.increment,
required this.set,
});
final int count;
final void Function() increment;
final void Function(int value) set;
}
main() {
final container = CapsuleContainer();
final counter = container.read(counterCapsule);
counter.set(3);
} |
Beta Was this translation helpful? Give feedback.
-
You cannot pass parameters to a capsule because it would no longer be a capsule (and capsules are typedefs for ValueWrapper<int> startingCountManager(CapsuleHandle use) => use.data(0);
(int, void Function()) countManager(CapsuleHandle use) {
final count = use.data(use(startingCountManager).value);
return (count.value, () => count.value++);
} And just make sure to read/set the |
Beta Was this translation helpful? Give feedback.
You cannot pass parameters to a capsule because it would no longer be a capsule (and capsules are typedefs for
T Function(CapsuleHandle)
). For many situations, the answer is factory capsules. There are also "dynamic capsules," but unless you need incremental computation (you will know if you need it when you need it) then you don't need it. For yours, it looks like you just want another capsule:And just make sure to read/set the
startingCountManager
before