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.

If you really want to be impressed by the creator of Provider, Remi, check out his package called nested, which provides widgets that can take a list of children and nest them. This is what `MultiProvider` is built on top of.


Join thousands of Flutter developers.

Sign up for infrequent updates about Flutter and Dart.

You can get all this content and more in one place. Check out my new book Flutter in Action