在 GoRoute 中使用 NavigationBar
前言
在App 中通常会把主要的几个页面放在下方icon,让使用者能够方便操作,这个元件在flutter 中称为BottomNavigationBar。
而GoRouter则是Flutter 官方所提供的套件,可以用来整合整个专案的路由。
当这两个功能整合在一起的时候,一个不小心呈现出来的效果就会差很多。
准备:先创建一个新的项目 叫做my_app!
flutter create my_app
cd my_app
加入BottomNavigationBar
在MyHomePage元件中找到build的方法,在Scaffold 加上bottomNavigationBar的属性,加上两个有icon 的元件。
之后执行指令flutter run就可以看到:画面的下方有一个icon 的区块,显示刚刚所加入的search 和add。
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'search',
),
BottomNavigationBarItem(
icon: Icon(Icons.add),
label: 'add',
),
],
),
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
);
}

加入GoRouter
接着要来加入GoRouter这个插件。
定义Router
定义两个route,会使用同一个元件,但是透过传入不同title 的内容来做识别。
找到MyApp 这个元件,在build 里面加上这段。
var router = GoRouter(
initialLocation: '/page1',
routes: [
GoRoute(
path: '/page1',
name: 'page1',
builder: (BuildContext context, GoRouterState state) =>
const MyHomePage(
title: 'search',
),
),
GoRoute(
path: '/page2',
name: 'page2',
builder: (BuildContext context, GoRouterState state) =>
const MyHomePage(
title: 'add',
),
),
],
);
接着要调整MyApp 的 return 的行为:原本是用MaterialApp,现在要来改用MaterialApp.router才能加上路由的设定。
return MaterialApp.router(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
// 把原本的 home 属性刪除并加上这段
routeInformationProvider: router.routeInformationProvider,
routeInformationParser: router.routeInformationParser,
routerDelegate: router.routerDelegate,
);
最后 回去调整BottomNavigationBar 的行为,监听onTap的事件,来达到切换页面的效果。
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'search',
),
BottomNavigationBarItem(
icon: Icon(Icons.add),
label: 'add',
),
],
// 监听点击事件
onTap: (index) => context.go('/page${index + 1}'),
改好以后重新启动,即可看到效果,整个页面包含NavigationBar 随着导航的切换也都会跟着重新载入(请先忽略点选了第二页但是icon 还是停留在第一页的问题)。
使用ShellRoute
根据GoRouter 的介绍,当有需要BottomNavigationBar 的时候,应该要采用ShellRoute的架构,就能够只有内容重新载入。
接着就要动一个比较大的工程,要将Scaffold 整个拉出来放到ShellRoute 中。
建立一个新的组件,就叫它ScaffoldWithBottomNavBar
,这里为方便 我就不摘取核心代码了,偷个懒直接一个main.dart 到底。
class ScaffoldWithBottomNavBar extends StatefulWidget {
const ScaffoldWithBottomNavBar({Key? key, required this.child})
: super(key: key);
final Widget child;
@override
State<ScaffoldWithBottomNavBar> createState() =>
_ScaffoldWithBottomNavBarState();
}
class _ScaffoldWithBottomNavBarState extends State<ScaffoldWithBottomNavBar> {
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'search',
),
BottomNavigationBarItem(
icon: Icon(Icons.add),
label: 'add',
),
],
onTap: (index) => context.go('/page${index + 1}'),
),
// 內容由外面來決定
body: widget.child,
);
}
}
然后 把这个元件加到路由的定义中。
var router = GoRouter(
initialLocation: '/page1',
routes: [
// 在原本的路由前面加上 ShellRoute 并且回传刚刚所建立的元件
ShellRoute(
builder: ((context, state, child) =>
ScaffoldWithBottomNavBar(child: child)),
routes: [
GoRoute(
path: '/page1',
name: 'page1',
builder: (BuildContext context, GoRouterState state) =>
const MyHomePage(
title: 'search',
),
),
GoRoute(
path: '/page2',
name: 'page2',
builder: (BuildContext context, GoRouterState state) =>
const MyHomePage(
title: 'add',
),
),
],
),
],
);
最后 回到MyHomePage元件将原本加关于 BottomNavigationBar 代码移除掉(因为前面已经将其抽出去放到ShellRoute 中)。
@override
Widget build(BuildContext context) {
return Scaffold(
// 移除 bottomNavigationBar 属性
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
);
}
都改完后可以看到,BottomNavigationBar 的区块是固定的了,点击切换只有内容页是不同。
结论
在web 上会很习惯这种功能的存在,转到flutter 时,一时间没找到也没特别注意到问题,后来是测试的时候才被点出来😅。
一个元件使用上的小地方,用错方法就会让使用者看起来没有那么舒服!
最后附上完整的程式码。
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
var router = GoRouter(
initialLocation: '/page1',
routes: [
ShellRoute(
builder: ((context, state, child) =>
ScaffoldWithBottomNavBar(child: child)),
routes: [
GoRoute(
path: '/page1',
name: 'page1',
builder: (BuildContext context, GoRouterState state) =>
const MyHomePage(
title: 'search',
),
),
GoRoute(
path: '/page2',
name: 'page2',
builder: (BuildContext context, GoRouterState state) =>
const MyHomePage(
title: 'add',
),
),
],
),
],
);
return MaterialApp.router(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
routeInformationProvider: router.routeInformationProvider,
routeInformationParser: router.routeInformationParser,
routerDelegate: router.routerDelegate,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class ScaffoldWithBottomNavBar extends StatefulWidget {
const ScaffoldWithBottomNavBar({Key? key, required this.child})
: super(key: key);
final Widget child;
@override
State<ScaffoldWithBottomNavBar> createState() =>
_ScaffoldWithBottomNavBarState();
}
class _ScaffoldWithBottomNavBarState extends State<ScaffoldWithBottomNavBar> {
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'search',
),
BottomNavigationBarItem(
icon: Icon(Icons.add),
label: 'add',
),
],
onTap: (index) => context.go('/page${index + 1}'),
),
body: widget.child,
);
}
}
如果上边完整例子的你不喜欢,我再来一个更加通俗易懂的完整例子
最后附上完整的代码。
```dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
// 定义标签栏和标签页
var _barItems = <BottomNavigationBarItem>[
const BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '首页',
),
const BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
label: '我的',
),
];
// 定义路由路径
var _routes = <String>[
'/home',
'/about',
];
class ScaffoldWithNavBar extends StatefulWidget {
const ScaffoldWithNavBar({super.key, required this.child});
final Widget child;
@override
State<ScaffoldWithNavBar> createState() => _ScaffoldWithNavBarState();
}
class _ScaffoldWithNavBarState extends State<ScaffoldWithNavBar> {
int currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
currentIndex: currentIndex,
items: _barItems,
onTap: (index) {
setState(() {
currentIndex = index;
});
context.go(_routes[index]);
},
),
body: widget.child, // 这里应该是从路由中传入的页面
);
}
}
// GoRouter配置
final GoRouter _router = GoRouter(
initialLocation: '/home',
routes: [
ShellRoute(
builder: (context, state, child) {
return ScaffoldWithNavBar(child: child);
},
routes: [
GoRoute(
path: '/home',
builder: (context, state) {
return const HomeScreen();
},
),
GoRoute(
path: '/about',
builder: (context, state) {
return const AboutScreen();
},
),
],
),
],
);
void main() {
runApp(MaterialApp.router(
routerConfig: _router,
));
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('首页')),
body: const Center(child: Text('这是首页 页面')),
);
}
}
class AboutScreen extends StatelessWidget {
const AboutScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('关于')),
body: const Center(child: Text('这是关于页 页面')),
);
}
}

注意: 如果切换底部导航切换页面的时候出现一瞬黑屏闪烁,那是官方bug,将flutter 升级到 v3.27 及其以上就好了。