MultiProvider micro lesson
on Wednesday, 5th of August, 2020
In the FutureProvider lesson, you may have noticed something ugly.
void main() {
runApp(
Provider<Person>(
create: (_) => Person(name: 'Yohan', age: 25),
child: FutureProvider<String>(
create: (context) => Home().fetchAddress,
initialData: "fetching address...",
child: MyApp(),
),
),
);
}There are two providers, one nested inside the over. You can imagine this getting quickly out of hand:
void main() {
runApp(
// You can wrap multiple providers
Provider<Person>(
create: (_) => Person(name: 'Yohan', age: 25),
child: FutureProvider<String>(
create: (context) => Home().fetchAddress,
initialData: "fetching address...",
child: StreamProvider<Connectivity>(
create: (context) => Session.connectivity(),
child: ChangeNotifierProvider<AuthState>(
create: (context) => Session.authState(),
child: MyApp(),
),
),
),
),
);
}This isn't super readable. Provider includes a fix for this: MultiProvider.
MultiProvider let's you pass in a list of providers without nesting anything,
void main() {
runApp(
// You can wrap multiple providers
MultiProvider(
providers: [
Provicer<Person>(create: (_) => Person(name: 'Yohan', age: 25)),
FutureProvider<String>(create: (context) => Home().fetchAddress),
],
child: MyApp(),
),
);
}This widget just makes code more terse and readable. Which is always nice.
- previous: Future Provider
- next: ChangeNotifierProvider