Flutter入門(三)-路由
- 2019 年 12 月 27 日
- 筆記
* StatefulWidget
如果想改變頁面中的數據就要用到StatefulWidget,之前自定義組件繼承的StatelessWidget是不能動態修改頁面數據的
//自定義有狀態組件 class HomePage extends StatefulWidget { HomePage({Key key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { int countNum = 0; @override Widget build(BuildContext context) { return Center( child: Column( children: <Widget>[ SizedBox(height: 100), Chip( label: Text('${this.countNum}'), ), SizedBox(height: 20), RaisedButton( child: Text('按鈕'), onPressed: () { setState(() { //只有有狀態組件里才有 this.countNum++; }); }, ) ], ), ); } }
效果圖

class HomePage extends StatefulWidget { HomePage({Key key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { List list = new List(); @override Widget build(BuildContext context) { return ListView( children: <Widget>[ Column( children: this.list.map((value) { return ListTile( title: Text(value), ); }).toList(), ), SizedBox(height: 20), RaisedButton( child: Text("按鈕"), onPressed: () { setState(() { list.add('新增數據'); }); }, ) ], ); } }
效果圖

* bottomNavigationBar(底部導航按鈕)+Navigator(路由/替換路由+傳值)
命名路由比普通路由更適合統一管理
程式碼結構

貼一下很重要的路由管理類
import 'package:flutter/material.dart'; import '../pages/Tabs.dart'; import '../pages/Form.dart'; import '../pages/Search.dart'; import '../pages/Product.dart'; import '../pages/ProductInfo.dart'; import '../pages/user/Login.dart'; import '../pages/user/RegisterFirst.dart'; import '../pages/user/RegisterSecond.dart'; import '../pages/user/RegisterThird.dart'; //配置路由 final routes = { '/': (context, {arguments}) => Tabs(), '/form': (context) => FormPage(), '/product': (context) => ProductPage(), '/productInfo': (context, {arguments}) => ProductInfoPage(arguments: arguments), '/search': (context, {arguments}) => SearchPage(arguments: arguments), '/login': (context) => LoginPage(), '/registerFirst': (context) => RegisterFirstPage(), '/registerSecond': (context) => RegisterSecondPage(), '/registerThird': (context) => RegisterThirdPage(), }; //固定寫法 //參考https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments var onGenerateRoutes = (RouteSettings settings) { //統一處理 final String name = settings.name; final Function pageContentBuilder = routes[name]; if (pageContentBuilder != null) { if (settings.arguments != null) { final Route route = MaterialPageRoute( builder: (context) => pageContentBuilder(context, arguments: settings.arguments)); return route; } else { final Route route = MaterialPageRoute(builder: (context) => pageContentBuilder(context)); return route; } } };
效果圖

程式碼地址:https://github.com/king1039/FlutterRoute/tree/master/lib
歡迎關注我的微信公眾號:Android圈