flutter中MaterialApp类中的构建器属性的示例?

Dan*_*ana 4 flutter

在MaterialApp类中,有一个属性调用构建器.

是否有关于如何使用构建器属性的示例或教程?

Dar*_*ron 14

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)
Run Code Online (Sandbox Code Playgroud)

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(),
        },
      ),
    );
Run Code Online (Sandbox Code Playgroud)

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.


Rém*_*let 7

builderproperty用于让widget包装所有 MaterialApp路由.但仍然可以访问Navigator.它也可以用于覆盖MediaQuery或类似.

例如,你可以做一个

MaterialApp(
 builder: (_, __) {
   return Navigator(
     // TODO: add custom transition
   );
 }
);
Run Code Online (Sandbox Code Playgroud)

哪个Navigator是在所有屏幕上共享登录信息的小部件.并且可能重定向到builder如果MaterialApp未记录的路由.

  • 您能否详细说明如何实现MyAuth?我想要一个可处理登录/注销的小部件,我正在使用build方法并创建一个小部件,但是当我尝试使用MyAuth进行导航时,出现以下错误:请求的导航器操作具有不包含导航器的上下文。 (3认同)