I have four providers, that all provide the Instances of Challenge class, to the same Widget. They are different challenges, but I don't know how to differentiate between the providers, so i wondered, if it's possible to give names to the providers.
Asked
Active
Viewed 285 times
0
-
Related: [Flutter - How does MultiProvider work with providers of the same type?](https://stackoverflow.com/q/56505413/3744182), [how to add multiple ChangeNotifierProvider in same type in Flutter](https://stackoverflow.com/q/61052629/3744182). – dbc Feb 03 '21 at 21:06
2 Answers
2
Actually, you can't, this is the biggest drawback of provider, you can use riverpod instead, it's from the same author, but it has some advantages over a normal provider.
this is what the author of both provider and riverpod sais.
It makes the provider pattern more flexible, which allows supporting commonly requested features like: Being able to have multiple providers of the same type.

Adnan Alshami
- 949
- 1
- 7
- 22
0
No. While you can have multiple providers sharing the same type, a widget will be able to obtain only one of them: the closest ancestor.
Instead, you must explicitly give both providers a different type.
Instead of:
Provider<Challenge>(
create: (_) => 'Something',
child: Provider<Challenge>(
create: (_) => 'SomethingElse',
child: ...,
),
),
Prefer:
MultiProvider(
providers: [
Provider<ChallengeOne>(create: (_) => Something()),
Provider<ChallengeTwo>(create: (_) => SomethingElse()),
Provider<ChallengeThree>(create: (_) => AnotherThing()),
],
child: someWidget,
)

Florian
- 226
- 2
- 11