Flutter-MaterialApp

MaterialApp简介

一个拥有完整application功能的widget,作为根widget管理子widget页面,包括页面pop/push栈管理,主题管理等。

使用

  Widget build(BuildContext context) {
        return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WidgetA(),
      routes: {
        "/testPage": (BuildContext context) {
          return TestPage();
        },
      },
    );
  }

MaterialApp路由表

The [MaterialApp] configures the top-level [Navigator] to search for routes
in the following order:

    1. For the / route, the [home] property, if non-null, is used.
    1. Otherwise, the [routes] table is used, if it has an entry for the route.
    1. Otherwise, [onGenerateRoute] is called, if provided. It should return a
      non-null value for any valid route not handled by [home] and [routes].
    1. Finally if all else fails [onUnknownRoute] is called.

番外

  • MaterialApp作为根root,管理一个路由表,路由表中,包含一个MaterialApp 页面MaterialAppA,和一普通页面WidgetA,普通页面WidgetB,同事MaterialApp管理的页面为一个WidgetA的对象;MaterialAppA 路由表为空。
  • root->WidgetA->WidgetB,可以通过Navigator.of(context).pushNamed("/WidgetB");正常跳转
  • root->MaterialAppA->WidgetA->WidgetB,此时,写在WidgetA中的Navigator.of(context).pushNamed("/WidgetB");不能正常调起WidgetB页面,因为此时用的是MaterialAppA的路由表,并不包含WidgetB页面路由。

猜想
Flutter侧有多个 MaterialApp 构成的page,可以设置为不同的 initialRoute 通过多个不同的MaterialApp,来实现原生到Flutter侧页面push。

MaterialApp 管理不同模块路由

将业务拆分成不同模块,模块间没有关联,通过不同的MaterialApp来管理
优点:模块拆分,结构清晰,便于管理
缺点:不同模块是不同的栈,Navigator默认只会找最近的路由表,开发过程中,不注意容易出错;MaterialApp 页面默认没有返回按钮。

本地化

  import 'package:flutter_localizations/flutter_localizations.dart';
  MaterialApp(
   localizationsDelegates: [
     // ... app-specific localization delegate[s] here
     GlobalMaterialLocalizations.delegate,
     GlobalWidgetsLocalizations.delegate,
   ],
   supportedLocales: [
      const Locale('en', 'US'), // English
      const Locale('he', 'IL'), // Hebrew
      // ... other locales the app supports
    ],
    // ...
  )

你可能感兴趣的:(Flutter-MaterialApp)