flutter3.0学习笔记

MaterialApp

Preview
  • 构造函数

MaterialApp 是 Flutter 中提供入口的一个类。在创建MaterialApp之前,我们必须导入。

import 'package:flutter/material.dart';

构造函数

 const MaterialApp({
    super.key,
    this.navigatorKey,//导航键,GlobalKey< NavigatorState >
    this.scaffoldMessengerKey,
    this.home,//主页
    Map<String, WidgetBuilder> this.routes = const <String, WidgetBuilder>{},//路由
    this.initialRoute,//初始路由
    this.onGenerateRoute,//生成路由
    this.onGenerateInitialRoutes,//路由匹配
    this.onUnknownRoute,//未知路由
    List<NavigatorObserver> this.navigatorObservers = const <NavigatorObserver>[],//导航观察器
    this.builder,//构造器
    this.title = '',//标题
    this.onGenerateTitle,//生成标题
    this.color,//颜色
    this.theme,//主题
    this.darkTheme,//暗黑主题
    this.highContrastTheme,
    this.highContrastDarkTheme,
    this.themeMode = ThemeMode.system,//主题模式
    this.locale,//地点
    this.localizationsDelegates,
    this.localeListResolutionCallback,
    this.localeResolutionCallback,
    this.supportedLocales = const <Locale>[Locale('en', 'US')],
    this.debugShowMaterialGrid = false,
    this.showPerformanceOverlay = false,
    this.checkerboardRasterCacheImages = false,
    this.checkerboardOffscreenLayers = false,
    this.showSemanticsDebugger = false,
    this.debugShowCheckedModeBanner = true,
    this.shortcuts,
    this.actions,
    this.restorationScopeId,
    this.scrollBehavior,
    this.useInheritedMediaQuery = false,
  }) 

MaterialApp必须至少具有home、routes、onGenerateRoutebuilder非空属性之一。

  • home

通常,我们定义主页、登录、注册、启动画面,但您可以将任何小部件放在这里。

MaterialApp(
    home: MyFirstPage(),
);
  • title标题
MaterialApp(
   title: "Widget In Detail",
   home: MyFirstPage(),
);
  • debugShowCheckedModeBanner

应用程序正在以“调试模式”运行,此属性的默认值为true

MaterialApp(
    debugShowCheckedModeBanner: true,
    title: "Widget In Detail",
    home: MyFirstPage(),
);
  • builder

创建widget的构建器,builder函数有两个参数contextwidget,的返回类型builderWidget

MaterialApp(
  builder: (context,widget) {
      return widget;
  }
);

通过使用builder属性,我们可以覆盖Navigator、MediaQueryinternationalization。 如下:

class MyApp extends StatelessWidget {
     @override
     Widget build(BuildContext context) {
         return MaterialApp(
            builder: (context, child) {
               return MyHomePage();
          });
     }
}

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: ElevatedButton(
        onPressed: () => Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => SecondPage(),
          ),
        ),
        child: Text('To Second Screen'),
      ),
    ),
  );
}
}

目前builder我们只是简单地返回 MyHomePage()。用Navigator并传递路由信息。

MaterialApp(
    builder: (context, child) {
    return Navigator(
      initialRoute: "/",
      onGenerateRoute: (settings) {
      if (settings.name == '/') {
        return MaterialPageRoute(builder: (_) => MyHomePage());
      }
      return null; 
    },
    );
});

这样就可以跳转到第二个页面。

  • initialRoute,初始页面的设置
MaterialApp(
    initialRoute: "/",
    routes: {
      '/': (_) => HomePage(),
    },
),
  • routes
MaterialApp(
    routes: {
      "/": (_)=> MyHomePage(),
      "/secondScreen": (_) => MySecondPage(),
    },
);

可以用Navigator.pushNamed(context, "/secondScreen")跳转。

class HomePage extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () => Navigator.pushNamed(context, "/secondScreen"),
            child: Text('To Second Screen'),
          ),
        ),
      );
    }
}
  • onGenerateRoute

如果没有设置routes表,则会查询onGenerateRoute,所有的路由都是discardedNavigator.defaultRouteName 而不是 (/)。

MaterialApp(
    onGenerateRoute: (settings) {
      return null;
    },
    home: MyHomePage(),
);

如果有匹配的路由则:

MaterialApp(
    onGenerateRoute: (settings) {
      if (settings.name == "/secondScreen") {
        return MaterialPageRoute(builder: (_) => MySecondPage());
      }
    },
    home: MyHomePage(),
);

  • onGenerateInitialRoutes

用于生成初始路由的路由生成器回调initialRoute,多用于授权

MaterialApp(
    onGenerateInitialRoutes: (route) {
        if (isAuthorized) {
          return <Route>[
            MaterialPageRoute(builder: (context) => HomePage())
          ];
        } else {
          return <Route>[
            MaterialPageRoute(builder: (context) => IntroPage())
          ];
        }
    },
    onGenerateRoute: (settings) {
      switch (settings.name) {
        case '/':
          return MaterialPageRoute(builder: (_) => IntroPage());
        case '/homePage':
          return MaterialPageRoute(builder: (_) => HomePage());
      }
    },
),
  • onUnknownRoute

onGenerateRoute生成路由失败时,这将返回一个路由。此回调通常用于错误处理。例如,此回调可能始终生成一个“未找到”页面,描述未找到的路由。

MaterialApp(
    onUnknownRoute: (RouteSettings settings) {
      return MaterialPageRoute<void>(
        settings: settings,
        builder: (BuildContext context) =>
            Scaffold(body: Center(child: Text('Not Found'))),
      );
    },
    home: HomePage(),
  ),
  • darkTheme

darkTheme是为了支持设备暗黑模式而定义的主题

  • theme主题颜色
MaterialApp(
  title: 'Flutter Demo',
  themeMode: ThemeMode.light,//改变light/dark
  theme: ThemeData(
    brightness: Brightness.light,
    primarySwatch: Colors.green
  ),
  darkTheme: ThemeData(
    brightness: Brightness.dark,
    primarySwatch: Colors.blueGrey
  ),
 }

image.png

  • locale

Locale(String _languageCode, [String? _countryCode])

MaterialApp(
locale: Locale('hi', ''),
home: HomeScreen()
);