Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

example for builder property in MaterialApp class in flutter?

Tags:

flutter

In MaterialApp class, there is a property call builder.

Are there any example or tutorial on how to use the builder property?

like image 980
Daniel Mana Avatar asked Apr 10 '18 08:04

Daniel Mana


2 Answers

builder can be used to wrap your route-widgets with a parent widget.

For example, if you have a LoadingSpinner widget, then instead of wrapping every single route widget in it. You can simple do:

builder: (context, widget) => LoadingSpinner(child: widget)

And widget would be whatever widget you have in that specific route.

Localization use case

Another useful use case is if you have top level BLoCs (such as a login BLoC) that require a language:

   MaterialApp(
        //... All the config properties
        builder: (context, widget) => Provider<LoginBloc>(
              // This line has access to the Locales
              builder: (_) => LoginBloc(languageCode: Localizations.localeOf(context).languageCode),
              dispose: (_, bloc) => bloc.dispose(),
              child: widget, // `widget` is either ProfilePage or LoginPage`
            ),
        supportedLocales: [
          const Locale('en', 'US'), // US English
          const Locale('en', 'GB'), // GB English
          const Locale('da', 'DK'), // Danish
          // ... other locales the app supports
        ],
        routes: <String, WidgetBuilder>{
          '/profile': (context) => ProfilePage(),
          '/login': (context) => LoginPage(),
        },
      ),
    );

If you were to place the Provider as a parent to MaterialApp, Localizations.localeOf(context) would crash. So here the builder shows it's value.

The above assumes you know what the BLoC pattern is, and what a Provider is.

like image 150
DarkNeuron Avatar answered Sep 17 '22 21:09

DarkNeuron


builder property is used to override properties implicitly set by MaterialApp, such as Navigator, MediaQuery or internationalization.

For example, one could want to override Navigator with a custom made one for custom route transitions:

MaterialApp(
 builder: (_, __) {
   return Navigator(
     // TODO: add custom transition
   );
 }
);
like image 40
Rémi Rousselet Avatar answered Sep 20 '22 21:09

Rémi Rousselet