前言

在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 及其以上就好了。


参考

[flutter] 在GoRoute 中使用NavigationBar

在 GoRoute 中使用 NavigationBar的更多相关文章

  1. Android 如何Android中自定义Navigationbar

    在如何控制Android系统中NavigationBar 的显示与隐藏文章里简要地介绍了Navigationbar的背景知识, NavigationBar的代码是放在... rameworksasep ...

  2. IOS 在IOS6中设置navigationBar背景图片 会有一条 黑色阴影 --- 解决方案

    //给navigationBar设置背景图片 if ([self.navigationController.navigationBar respondsToSelector:@selector(set ...

  3. iOS系统中导航栏的转场解决方案与最佳实践

    背景 目前,开源社区和业界内已经存在一些 iOS 导航栏转场的解决方案,但对于历史包袱沉重的美团 App 而言,这些解决方案并不完美.有的方案不能满足复杂的页面跳转场景,有的方案迁移成本较大,为此我们 ...

  4. Android开发之自定义组件和接口回调

    说到自定义控件不得不提的就是接口回调,在Android开发中接口回调用的还是蛮多的.在这篇博客开始的时候呢,我想聊一下iOS的自定义控件.在iOS中自定义控件的思路是继承自UIView, 在UIVie ...

  5. Swift主题色顶级解决方案

    一.常规主题色使用点 应用在发布前都会对主题色进行设置,以统一应用的风格(可能有多套主题).在主题色设置上有几个方面,如下: 1. TabBar部分,设置图片高亮.文本高度颜色2. Navigatio ...

  6. Swift主题色顶级解决方案一

    一.常规主题色使用点 应用在发布前都会对其主题色进行设置,以统一应用的风格(可能有多套主题).在主题色设置上有几个方面,如下: 1.TabBar部分,设置图片高亮.文本高度颜色 2.Navigatio ...

  7. iOS开发 改变UINavigationController的UINavigationBar的高度和背景图片

    1.改变高度 自定义UINavigationBar的新类别: //UINavigationBar+BackgoundImage.h #import <Foundation/Foundation. ...

  8. Visual Studio 跨平台開發實戰(3) - Xamarin iOS 多頁面應用程式開發 (转帖)

    前言 在前一篇教學中, 我們學會如何使用Visual Studio 搭配Xcode 進行iOS基本控制項的操作. 但都是屬於單一畫面的應用程式. 這次我們要來練習如何透過Navigation Cont ...

  9. ios UINavigationController 导航栏

    添加全屏侧滑返回 .获取到系统的pop返回手势 .获取pop在哪个view上 .获取target,action .自定义UIPanGestureRecognizer //1.获取手势 guard le ...

  10. Python开源框架

    info:更多Django信息url:https://www.oschina.net/p/djangodetail: Django 是 Python 编程语言驱动的一个开源模型-视图-控制器(MVC) ...

随机推荐

  1. 《数组》--DAY2--快慢指针法

    1.什么是双指针? 双指针,指的是在遍历对象的过程中,不是普通的使用单个指针进行访问,而是使用两个相同方向(快慢指针)或者相反方向(对撞指针)的指针进行扫描,从而达到相应的目的. 2.快慢指针 2.1 ...

  2. Java+Selenium+Junit实现web自动化demo

    1.新建maven工程 打开IDEA新建maven项目并引入相关依赖,步骤如下: 需要引入的依赖 <dependencies> <dependency> <groupId ...

  3. 使用 StreamJsonRpc 在 ASP.NET Core 中启用 JSON-RPC

    StreamJsonRpc 是微软开发的一个开源库,用于在 .NET 平台中实现基于 JSON-RPC 2.0 规范 的远程过程调用(RPC).它通过流(如管道.网络流等)实现高效的跨进程或跨网络通信 ...

  4. idea git建立分支、切换分支、合并分支

    为什么要建立分支 git默认的主分支名字为master,一般团队开发时,都不会在master主分支上修改代码,而是建立新分支,测试完毕后,在将分支的代码合并到master主分支上 2.操作如下: 2. ...

  5. Linux四剑客grep、find、sed、awk使用

    ‌介绍 Linux四剑客‌是指在Linux系统中非常常用的四个命令工具,它们分别是grep.find.sed和awk.这四个工具在Linux系统中具有非常强大的功能,可以方便快捷地对文本进行搜索.处理 ...

  6. 36.3K star!开发者专属PPT神器,Markdown秒变炫酷幻灯片!

    嗨,大家好,我是小华同学,关注我们获得"最新.最全.最优质"开源项目和高效工作学习方法 Slidev 是专为开发者打造的现代化幻灯片制作工具,基于 Markdown + Vue 技 ...

  7. 逆序对计数问题之C#实现(O(nlogn))

    逆序对计数问题是一个经典的算法问题,常见于计算机科学和数据结构领域.它的目标是计算数组中所有的逆序对的数量.逆序对是指数组中两个元素满足位置关系(i,j),且有 A[i]>A[j]. 它的应用有 ...

  8. C#中的弱引用

    弱引用保持的是一个GC"不可见"的引用,是指弱引用不会增加对象的引用计数,也不会阻止垃圾回收器对该对象进行回收.因此,弱引用的目标对象可以被垃圾回收器回收,而弱引用本身不会对垃圾回 ...

  9. ISCC2025破阵夺旗赛三阶段Misc详解 By Alexander

    ISCC2025破阵夺旗赛三阶段Misc详解 By Alexander 写在前面:十八天吃石终于结束了,第一次就让我见到了这个比赛有多么的构式,平台是构式的,睡一觉就1000解了,全是对flag的渴望 ...

  10. 关于 Newtonsoft.Json 和 System.Text.Json 混用导致的的序列化不识别的问题

    最近,我在做一个我们一个产品的OTA的功能,在调试跟后台对接Json数据的时候,发现序列化的数据一直跟期待的不一致.这让我很纳闷,明明一个简单的序列化和反序列化的问题,怎么数据就不对了.于是乎,就直接 ...