Flutter之底部tab切換
阿新 • • 發佈:2020-12-12
效果見上圖:(主要是底部的切換實現)
import 'package:flutter/material.dart'; import 'file:///D:/henanproject/flutter_weight_ui/lib/home/home_tab_page.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false,//去掉debug標籤 theme: ThemeData( primarySwatch: Colors.blue,//主題顏色 visualDensity: VisualDensity.adaptivePlatformDensity, ), home: HomeTabPage(), ); } }
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_weight_ui/list/article_list_page.dart'; import 'file:///D:/henanproject/flutter_weight_ui/lib/home/banner_page.dart'; import 'package:flutter_weight_ui/setting_page.dart'; import 'package:flutter_weight_ui/tab/top_tab_page.dart'; class HomeTabPage extends StatefulWidget{ @override State<StatefulWidget> createState() => _homeTabPage(); } // ignore: camel_case_types class _homeTabPage extends State<HomeTabPage>{ final List<BottomNavigationBarItem> list = [ BottomNavigationBarItem( backgroundColor: Colors.blue, icon: Icon(Icons.home), label: "首頁", ), BottomNavigationBarItem( backgroundColor: Colors.blue, icon: Icon(Icons.account_circle), label: "文章", ), BottomNavigationBarItem( backgroundColor: Colors.blue, icon: Icon(Icons.security), label: "分類", ), BottomNavigationBarItem( backgroundColor: Colors.blue, icon: Icon(Icons.mail), label: "訊息", ), BottomNavigationBarItem( backgroundColor: Colors.blue, icon: Icon(Icons.menu), label: "我的", ), ]; int current; // 這塊可以自己隨便寫幾個page 比如Text("文章") final pages = [BannerPage(),ArticlePage(),TabTopPage(),SettingPage(),SettingPage()]; @override void initState() { super.initState(); current =0;//初始化預設展示的page } @override Widget build(BuildContext context) { return Scaffold( bottomNavigationBar: BottomNavigationBar( items: list,//item陣列 currentIndex: current,//當前選中的 type: BottomNavigationBarType.fixed,//shifting模式目前我是接受不了,傳統的用fixed onTap: (index) { _changPage(index);//動態改變選中的tab }, ), body: pages[current],//選中的page ); } void _changPage(int index){ if(index!=current){ setState(() {//實時改變選中的index,跟微信小程式的setData類似 current =index; }); } } }
flutter寫這種導航的tab還是挺簡單的,比原生簡單。