Flutter 容器控制元件篇-->MaterialApp

夜夕i發表於2019-09-30

文章轉載於:juejin.im/post/5b5ed0…

Flutter 控制元件中的 MaterialApp 作為App的頂層主頁入口,一般是用來配置主題、語言、頁面跳轉等...

MaterialApp屬性

引數 型別
navigatorKey(導航鍵) GlobalKey
home(主頁) Widget
routes(路由) Map<String, WidgetBuilder>
initialRoute(初始路由) String
onGenerateRoute(生成路由) RouteFactory
onUnknownRoute(未知路由) RouteFactory
navigatorObservers(導航觀察器) List
builder(建造者) TransitionBuilder
title(標題) String
onGenerateTitle(生成標題) GenerateAppTitle
color(顏色) Color
theme(主題) ThemeData
locale(地點) Locale
localizationsDelegates(本地化委託) Iterable<LocalizationsDelegate>
localeResolutionCallback(區域分辨回撥) LocaleResolutionCallback
supportedLocales(支援區域) Iterable
debugShowMaterialGrid(除錯顯示材質網格) bool
showPerformanceOverlay(顯示效能疊加) bool
checkerboardRasterCacheImages(棋盤格光柵快取影象) bool
checkerboardOffscreenLayers(棋盤格層) bool
showSemanticsDebugger(顯示語義偵錯程式) bool
debugShowCheckedModeBanner(除錯顯示檢查模式橫幅) bool

原始碼示例

建構函式如下:

const MaterialApp({
    Key key,
    this.navigatorKey,
    this.home,
    this.routes = const <String, WidgetBuilder>{},
    this.initialRoute,
    this.onGenerateRoute,
    this.onUnknownRoute,
    this.navigatorObservers = const <NavigatorObserver>[],
    this.builder,
    this.title = '',
    this.onGenerateTitle,
    this.color,
    this.theme,
    this.darkTheme,
    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,
})
複製程式碼

屬性解釋

1.navigatorKey

navigatorKey.currentState 相當於 Navigator.of(context)

使用:

GlobalKey<NavigatorState> _navigatorKey=new GlobalKey();

new MaterialApp(
  navigatorKey: _navigatorKey,
);
複製程式碼

2.home

進入程式後顯示的第一個頁面,傳入的是一個Widget,但實際上這個Widget需要包裹一個Scaffold以顯示該程式使用Material Design風格

使用:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}
//這是一個可改變的Widget
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text('Title'),
      ),
      body: Center(
        child: Text('Home'),
      ),
    );
  }
}
複製程式碼

3.routes

宣告程式中有哪個通過Navigation.of(context).pushNamed跳轉的路由
引數以鍵值對的形式傳遞 key:路由名字 value:對應的Widget

使用:

new MaterialApp(
  routes: {
   '/home':(BuildContext context) => HomePage(),
   '/home/one':(BuildContext context) => OnePage(),
    //....
  },
);
複製程式碼

4.initialRoute

初始路由,當使用者進入程式時,自動開啟對應的路由。

使用:

new MaterialApp(
  routes: {
   '/home':(BuildContext context) => HomePage(),
   '/home/one':(BuildContext context) => OnePage(),
   //....
  },
  initialRoute: '/home/one',
);
複製程式碼

5.onGenerateRoute

當通過Navigation.of(context).pushNamed跳轉路由時, 在routes查詢不到時,會呼叫該方法

使用:

new MaterialApp(
  routes: {
   '/home':(BuildContext context) => HomePage(),
   '/home/one':(BuildContext context) => OnePage(),
   //....
  },
  onGenerateRoute: (setting){
	//setting.isInitialRoute; bool型別 是否初始路由
	//setting.name; 要跳轉的路由名key
	return new PageRouteBuilder(
		pageBuilder: (BuildContext context, _, __) {
	//這裡為返回的Widget
		  return HomePage();
		},
		opaque: false,
	//跳轉動畫
		transitionDuration: new Duration(milliseconds: 200),
		transitionsBuilder:
			(___, Animation<double> animation, ____, Widget child) {
		  return new FadeTransition(
			opacity: animation,
			child: new ScaleTransition(
			  scale: new Tween<double>(begin: 0.5, end: 1.0)
				  .animate(animation),
			  child: child,
			),
		  );
		});
  }
);
複製程式碼

6.onUnknownRoute

效果跟onGenerateRoute一樣 呼叫順序為onGenerateRoute --> onUnknownRoute

7.navigatorObservers

路由觀察器,當呼叫Navigator的相關方法時,會回撥相關的操作

使用:

new MaterialApp(
      navigatorObservers: [
        MyObserver(),
      ],
    );
//繼承NavigatorObserver
class MyObserver extends NavigatorObserver{
  @override
  void didPush(Route route, Route previousRoute) {
    // 當呼叫Navigator.push時回撥
    super.didPush(route, previousRoute);
    //可通過route.settings獲取路由相關內容
    //route.currentResult獲取返回內容
    //....等等
    print(route.settings.name);
  }
}
複製程式碼

8.builder

當構建一個Widget前呼叫 一般做字型大小,方向,主題顏色等配置

使用:

new MaterialApp(
  builder: (BuildContext context, Widget child) {
	return MediaQuery(
	  data: MediaQuery.of(context).copyWith(
		//字型大小
			textScaleFactor: 1.4,
		  ),
	  child: child,
	);
  },
);
複製程式碼

9.title

該標題出現在 :

  • Android:工作管理員的程式快照之上
  • IOS: 程式切換管理器中

使用:

new MaterialApp(
  title: 'Flutter應用',
);
複製程式碼

10.onGenerateTitle

跟上面的tiitle一樣,但含有一個context引數 用於做本地化

使用:

new MaterialApp(
  onGenerateTitle: (context){
	return 'Flutter應用';
  },
);
複製程式碼

11.color

該顏色為Android中程式切換中應用圖示背景的顏色

使用:

new MaterialApp(
  color: Colors.blue,
)
複製程式碼

12.theme

應用程式的主題,各種的定製顏色都可以設定,用於程式主題切換

使用:

new MaterialApp(
  theme: new ThemeData(
   //主題色
	primarySwatch: Colors.blue,
  ),
);
複製程式碼

13.locale

當前區域,如果為null則使用系統區域 一般用於語言切換

使用:

//傳入兩個引數,語言程式碼,國家程式碼
new MaterialApp(
      Locale('yy','zh'),
    );
//原始碼糾正,一些曾經用過的程式碼(註釋後面的日期為不再使用的日期),原始碼會自動糾正
//來看一下原始碼
//languageCode 第一個引數
switch (languageCode) {
      case 'in': return 'id'; // Indonesian; deprecated 1989-01-01
      case 'iw': return 'he'; // Hebrew; deprecated 1989-01-01
      case 'ji': return 'yi'; // Yiddish; deprecated 1989-01-01
      case 'jw': return 'jv'; // Javanese; deprecated 2001-08-13
      case 'mo': return 'ro'; // Moldavian, Moldovan; deprecated 2008-11-22
      case 'aam': return 'aas'; // Aramanik; deprecated 2015-02-12
      case 'adp': return 'dz'; // Adap; deprecated 2015-02-12
      case 'aue': return 'ktz'; // =/Kx'au//'ein; deprecated 2015-02-12
      case 'ayx': return 'nun'; // Ayi (China); deprecated 2011-08-16
      case 'bgm': return 'bcg'; // Baga Mboteni; deprecated 2016-05-30
      case 'bjd': return 'drl'; // Bandjigali; deprecated 2012-08-12
      case 'ccq': return 'rki'; // Chaungtha; deprecated 2012-08-12
      case 'cjr': return 'mom'; // Chorotega; deprecated 2010-03-11
      case 'cka': return 'cmr'; // Khumi Awa Chin; deprecated 2012-08-12
      case 'cmk': return 'xch'; // Chimakum; deprecated 2010-03-11
      case 'coy': return 'pij'; // Coyaima; deprecated 2016-05-30
      case 'cqu': return 'quh'; // Chilean Quechua; deprecated 2016-05-30
      case 'drh': return 'khk'; // Darkhat; deprecated 2010-03-11
      case 'drw': return 'prs'; // Darwazi; deprecated 2010-03-11
      case 'gav': return 'dev'; // Gabutamon; deprecated 2010-03-11
      case 'gfx': return 'vaj'; // Mangetti Dune !Xung; deprecated 2015-02-12
      case 'ggn': return 'gvr'; // Eastern Gurung; deprecated 2016-05-30
      case 'gti': return 'nyc'; // Gbati-ri; deprecated 2015-02-12
      case 'guv': return 'duz'; // Gey; deprecated 2016-05-30
      case 'hrr': return 'jal'; // Horuru; deprecated 2012-08-12
      case 'ibi': return 'opa'; // Ibilo; deprecated 2012-08-12
      case 'ilw': return 'gal'; // Talur; deprecated 2013-09-10
      case 'jeg': return 'oyb'; // Jeng; deprecated 2017-02-23
      case 'kgc': return 'tdf'; // Kasseng; deprecated 2016-05-30
      case 'kgh': return 'kml'; // Upper Tanudan Kalinga; deprecated 2012-08-12
      case 'koj': return 'kwv'; // Sara Dunjo; deprecated 2015-02-12
      case 'krm': return 'bmf'; // Krim; deprecated 2017-02-23
      case 'ktr': return 'dtp'; // Kota Marudu Tinagas; deprecated 2016-05-30
      case 'kvs': return 'gdj'; // Kunggara; deprecated 2016-05-30
      case 'kwq': return 'yam'; // Kwak; deprecated 2015-02-12
      case 'kxe': return 'tvd'; // Kakihum; deprecated 2015-02-12
      case 'kzj': return 'dtp'; // Coastal Kadazan; deprecated 2016-05-30
      case 'kzt': return 'dtp'; // Tambunan Dusun; deprecated 2016-05-30
      case 'lii': return 'raq'; // Lingkhim; deprecated 2015-02-12
      case 'lmm': return 'rmx'; // Lamam; deprecated 2014-02-28
      case 'meg': return 'cir'; // Mea; deprecated 2013-09-10
      case 'mst': return 'mry'; // Cataelano Mandaya; deprecated 2010-03-11
      case 'mwj': return 'vaj'; // Maligo; deprecated 2015-02-12
      case 'myt': return 'mry'; // Sangab Mandaya; deprecated 2010-03-11
      case 'nad': return 'xny'; // Nijadali; deprecated 2016-05-30
      case 'nnx': return 'ngv'; // Ngong; deprecated 2015-02-12
      case 'nts': return 'pij'; // Natagaimas; deprecated 2016-05-30
      case 'oun': return 'vaj'; // !O!ung; deprecated 2015-02-12
      case 'pcr': return 'adx'; // Panang; deprecated 2013-09-10
      case 'pmc': return 'huw'; // Palumata; deprecated 2016-05-30
      case 'pmu': return 'phr'; // Mirpur Panjabi; deprecated 2015-02-12
      case 'ppa': return 'bfy'; // Pao; deprecated 2016-05-30
      case 'ppr': return 'lcq'; // Piru; deprecated 2013-09-10
      case 'pry': return 'prt'; // Pray 3; deprecated 2016-05-30
      case 'puz': return 'pub'; // Purum Naga; deprecated 2014-02-28
      case 'sca': return 'hle'; // Sansu; deprecated 2012-08-12
      case 'skk': return 'oyb'; // Sok; deprecated 2017-02-23
      case 'tdu': return 'dtp'; // Tempasuk Dusun; deprecated 2016-05-30
      case 'thc': return 'tpo'; // Tai Hang Tong; deprecated 2016-05-30
      case 'thx': return 'oyb'; // The; deprecated 2015-02-12
      case 'tie': return 'ras'; // Tingal; deprecated 2011-08-16
      case 'tkk': return 'twm'; // Takpa; deprecated 2011-08-16
      case 'tlw': return 'weo'; // South Wemale; deprecated 2012-08-12
      case 'tmp': return 'tyj'; // Tai Mène; deprecated 2016-05-30
      case 'tne': return 'kak'; // Tinoc Kallahan; deprecated 2016-05-30
      case 'tnf': return 'prs'; // Tangshewi; deprecated 2010-03-11
      case 'tsf': return 'taj'; // Southwestern Tamang; deprecated 2015-02-12
      case 'uok': return 'ema'; // Uokha; deprecated 2015-02-12
      case 'xba': return 'cax'; // Kamba (Brazil); deprecated 2016-05-30
      case 'xia': return 'acn'; // Xiandao; deprecated 2013-09-10
      case 'xkh': return 'waw'; // Karahawyana; deprecated 2016-05-30
      case 'xsj': return 'suj'; // Subi; deprecated 2015-02-12
      case 'ybd': return 'rki'; // Yangbye; deprecated 2012-08-12
      case 'yma': return 'lrr'; // Yamphe; deprecated 2012-08-12
      case 'ymt': return 'mtm'; // Mator-Taygi-Karagas; deprecated 2015-02-12
      case 'yos': return 'zom'; // Yos; deprecated 2013-09-10
      case 'yuu': return 'yug'; // Yugh; deprecated 2014-02-28
      default: return languageCode;
    }

//_countryCode 第二個引數
switch (_countryCode) {
  case 'BU': return 'MM'; // Burma; deprecated 1989-12-05
  case 'DD': return 'DE'; // German Democratic Republic; deprecated 1990-10-30
  case 'FX': return 'FR'; // Metropolitan France; deprecated 1997-07-14
  case 'TP': return 'TL'; // East Timor; deprecated 2002-05-20
  case 'YD': return 'YE'; // Democratic Yemen; deprecated 1990-08-14
  case 'ZR': return 'CD'; // Zaire; deprecated 1997-07-14
  default: return regionCode;
} 
複製程式碼

14.localizationsDelegates

本地化委託,用於更改Flutter Widget預設的提示語,按鈕text

使用:

new MaterialApp(
      localizationsDelegates: [
          MyLocalizationsDelegates(),
      ],
      locale: Locale('zh','cn'),
    );

class MyLocalizationsDelegates extends LocalizationsDelegate
<MaterialLocalizations>{
  @override
  bool isSupported(Locale locale) {
//是否支援該locale,如果不支援會報異常
    if(locale == const Locale('zh','cn')){
      return true;
    }
    return false;
  }
  @override//是否需要過載
  bool shouldReload(LocalizationsDelegate old)  => false;

  @override
  Future<MaterialLocalizations> load(Locale locale) {
//載入本地化
    return new SynchronousFuture(new MyLocalizations(locale));
  }
}
//本地化實現,繼承DefaultMaterialLocalizations
class MyLocalizations extends DefaultMaterialLocalizations{
  final Locale locale;
  MyLocalizations(this.locale, );
  @override
  String get okButtonLabel {
    if(locale == const Locale('zh','cn')){
      return '好的';
    }else{
      return super.okButtonLabel;
    }
  }
  @override
  String get backButtonTooltip {
    if(locale == const Locale('zh','cn')){
      return '返回';
    }else{
      return super.okButtonLabel;
    }
  }
}
複製程式碼

15.localeResolutionCallback

當傳入的是不支援的語種,可以根據這個回撥,返回相近,並且支援的語種

使用:

new MaterialApp(
  localeResolutionCallback: (local,support){
	if(support.contains(support)){
	  print('support');
	  return local;
	}
	print('no_support');
	return const Locale('us','uk');
  },
  locale: Locale('zh-Hans','zh-Hant'),
);
複製程式碼

16.supportedLocales

傳入支援的語種陣列

new MaterialApp(
  supportedLocales: [
	const Locale('uok'),
	const Locale('meg'),
  ],
);
複製程式碼

17.debugShowMaterialGrid

debug模式下是否顯示材質網格,傳入bool型別,一般不適用

18.showPerformanceOverlay

當為true時應用程式頂部覆蓋一層GPUUI曲線圖,可即時檢視當前流暢度情況

19.checkerboardRasterCacheImages

當為true時,開啟光柵快取影象的棋盤格

20.checkerboardOffscreenLayers

當為true時,開啟呈現到螢幕點陣圖的層的棋盤格

21.showSemanticsDebugger

當為true時,開啟Widget邊框,類似Android開發者模式中顯示佈局邊界

22.debugShowCheckedModeBanner

當為true時,在debug模式下顯示右上角的debug字樣的橫幅,false即為不顯示


+_+

相關文章