example for builder property in MaterialApp class in flutter?
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.
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
);
}
);