I’m using Riverpod provider to manage the state of 4 containers in Flutter that changes the state of the container to a different colour. However, I might need more containers in the future and creating a new provider for each container doesn't sound right. Is there a way to use a single provider for multiple containers while keeping their state independent?
They way I am going about this is creating 4 independent providers for each container, this of course works but I want to add way more containers in the future so the code is getting unnecessarily large.
You can:
StateProvider
. Then it is worth looking at the freezed package, which will keep the object immutable and the correct hashCode/==
.ProviderScope(...)
final containerProvider = Provider((ref) => 1);
Widget build(context, ref) {
return ProviderScope(
overrides: [
containerProvider.overrideWithValue(2),
],
child: Container(...),
),
}
It turns out that each container will be overridden with its own value.
.family
for the provider to provide the custom value