Karthik S
Karthik S

Reputation: 23

How can I use a single Riverpod provider for multiple widgets with independent state in Flutter using Riverpod?

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.

Upvotes: 1

Views: 1276

Answers (1)

Ruble
Ruble

Reputation: 4844

You can:

  1. Create as many providers as you need.
  2. Create a model that has as many fields as you have containers and manage it with a single StateProvider. Then it is worth looking at the freezed package, which will keep the object immutable and the correct hashCode/==.
  3. Depending on the situation, you can override the provider through 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.

  1. Use the modifier .family for the provider to provide the custom value

Upvotes: 0

Related Questions