前言:
在flutter应用中,导航栏切换页面后默认情况下会丢失原页面状态,即每次进入页面时都会重新初始化状态,如果在initstate中打印日志,会发现每次进入时都会输出,显然这样增加了额外的开销,并且带来了不好的用户体验。
在正文之前,先看一些常见的app导航,以喜马拉雅fm为例:
它拥有一个固定的底部导航以及首页的顶部导航,可以看到不管是点击底部导航切换页面还是在首页左右侧滑切换页面,之前的页面状态都是始终维持的,下面就具体介绍下如何在flutter中实现类似喜马拉雅的导航效果
第一步:实现固定的底部导航
在通过flutter create生成的项目模板中,我们先简化一下代码,将myhomepage提取到一个单独的home.dart文件,并在scaffold脚手架中添加bottomnavigationbar底部导航,在body中展示当前选中的子页面。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
/// home.dart import 'package:flutter/material.dart' ; import './pages/first_page.dart' ; import './pages/second_page.dart' ; import './pages/third_page.dart' ; class myhomepage extends statefulwidget { @override _myhomepagestate createstate() => _myhomepagestate(); } class _myhomepagestate extends state<myhomepage> { final items = [ bottomnavigationbaritem(icon: icon(icons.home), title: text( '首页' )), bottomnavigationbaritem(icon: icon(icons.music_video), title: text( '听' )), bottomnavigationbaritem(icon: icon(icons.message), title: text( '消息' )) ]; final bodylist = [firstpage(), secondpage(), thirdpage()]; int currentindex = 0 ; void ontap( int index) { setstate(() { currentindex = index; }); } @override widget build(buildcontext context) { return scaffold( appbar: appbar( title: text( 'demo' ), ), bottomnavigationbar: bottomnavigationbar( items: items, currentindex: currentindex, ontap: ontap ), body: bodylist[currentindex] ); } } |
其中的三个子页面结构相同,均显示一个计数器和一个加号按钮,以first_page.dart为例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
/// first_page.dart import 'package:flutter/material.dart' ; class firstpage extends statefulwidget { @override _firstpagestate createstate() => _firstpagestate(); } class _firstpagestate extends state<firstpage> { int count = 0 ; void add() { setstate(() { count++; }); } @override widget build(buildcontext context) { return scaffold( body: center( child: text( 'first: $count' , style: textstyle(fontsize: 30 )) ), floatingactionbutton: floatingactionbutton( onpressed: add, child: icon(icons.add), ) ); } } |
当前效果如下:
可以看到,从第二页切换回第一页时,第一页的状态已经丢失
第二步:实现底部导航切换时保持原页面状态
可能有些小伙伴在搜索后会开始直接使用官方推荐的automatickeepaliveclientmixin,通过在子页面的state类重写wantkeepalive为true 。 然而,如果你的代码和我上面的类似,body中并没有使用pageview或tabbarview,很不幸的告诉你,踩到坑了,这样是无效的,原因后面再详述。现在我们先来介绍另外两种方式:
① 使用indexedstack实现
indexedstack继承自stack,它的作用是显示第index个child,其它child在页面上是不可见的,但所有child的状态都被保持,所以这个widget可以实现我们的需求,我们只需要将现在的body用indexedstack包裹一层即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/// home.dart class _myhomepagestate extends state<myhomepage> { ... ... ... @override widget build(buildcontext context) { return scaffold( appbar: appbar( title: text( 'demo' ), ), bottomnavigationbar: bottomnavigationbar( items: items, currentindex: currentindex, ontap: ontap), // body: bodylist[currentindex] body: indexedstack( index: currentindex, children: bodylist, )); } |
保存后再次测试一下
② 使用offstage实现
offstage的作用十分简单,通过一个参数来控制child是否显示,所以我们同样可以组合使用offstage来实现该需求,其实现原理与indexedstack类似
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/// home.dart class _myhomepagestate extends state<myhomepage> { ... ... ... @override widget build(buildcontext context) { return scaffold( appbar: appbar( title: text( 'demo' ), ), bottomnavigationbar: bottomnavigationbar( items: items, currentindex: currentindex, ontap: ontap), // body: bodylist[currentindex], body: stack( children: [ offstage( offstage: currentindex != 0 , child: bodylist[ 0 ], ), offstage( offstage: currentindex != 1 , child: bodylist[ 1 ], ), offstage( offstage: currentindex != 2 , child: bodylist[ 2 ], ), ], )); } } |
在上面的两种方式中都可以实现保持原页面状态的需求,但这里有一些开销上的问题,有经验的小伙伴应该能发现当应用第一次加载的时候,所有子页状态都被实例化了(>这里的细节并不是因为我直接把子页实例化放在bodylist里...<),如果在子页state的initstate中打印日志,可以在终端看到一次性输出了所有子页的日志。下面就介绍另一种通过继承automatickeepaliveclientmixin的方式来更好的实现保持状态。
第三步:实现首页的顶部导航
首先我们通过配合使用tabbar+tabbarview+automatickeepaliveclientmixin来实现顶部导航(注意:tabbar和tabbarview需要提供controller,如果自己没有定义,则必须使用defaulttabcontroller包裹)。此处也可以选择使用pageview,后面会介绍。
我们先在home.dart文件移除scaffold脚手架中的appbar顶部工具栏,然后开始重写首页first_page.dart:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
/// first_page.dart import 'package:flutter/material.dart' ; import './recommend_page.dart' ; import './vip_page.dart' ; import './novel_page.dart' ; import './live_page.dart' ; class _tabdata { final widget tab; final widget body; _tabdata({ this .tab, this .body}); } final _tabdatalist = <_tabdata>[ _tabdata(tab: text( '推荐' ), body: recommendpage()), _tabdata(tab: text( 'vip' ), body: vippage()), _tabdata(tab: text( '小说' ), body: novelpage()), _tabdata(tab: text( '直播' ), body: livepage()) ]; class firstpage extends statefulwidget { @override _firstpagestate createstate() => _firstpagestate(); } class _firstpagestate extends state<firstpage> { final tabbarlist = _tabdatalist.map((item) => item.tab).tolist(); final tabbarviewlist = _tabdatalist.map((item) => item.body).tolist(); @override widget build(buildcontext context) { return defaulttabcontroller( length: tabbarlist.length, child: column( children: <widget>[ container( width: double .infinity, height: 80 , padding: edgeinsets.fromltrb( 20 , 24 , 0 , 0 ), alignment: alignment.centerleft, color: colors.black, child: tabbar( isscrollable: true , indicatorcolor: colors.red, indicatorsize: tabbarindicatorsize.label, unselectedlabelcolor: colors.white, unselectedlabelstyle: textstyle(fontsize: 18 ), labelcolor: colors.red, labelstyle: textstyle(fontsize: 20 ), tabs: tabbarlist), ), expanded( child: tabbarview( children: tabbarviewlist, // physics: neverscrollablescrollphysics(), // 禁止滑动 )) ], )); } } |
其中推荐页、vip页、小说页、直播页的结构仍和之前的首页结构相同,仅显示一个计数器和一个加号按钮,以推荐页recommend_page.dart为例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
/// recommend_page.dart import 'package:flutter/material.dart' ; class recommendpage extends statefulwidget { @override _recommendpagestate createstate() => _recommendpagestate(); } class _recommendpagestate extends state<recommendpage> { int count = 0 ; void add() { setstate(() { count++; }); } @override void initstate() { super .initstate(); print( 'recommend initstate' ); } @override widget build(buildcontext context) { return scaffold( body:center( child: text( '首页推荐: $count' , style: textstyle(fontsize: 30 )) ), floatingactionbutton: floatingactionbutton( onpressed: add, child: icon(icons.add), )); } } |
保存后测试,
可以看到,现在添加了首页顶部导航,且默认支持左右侧滑,接下来再进一步的完善状态保持
第四步:实现首页顶部导航切换时保持原页面状态
③ 使用automatickeepaliveclientmixin实现
写到这里已经很简单了,我们只需要在首页导航内需要保持页面状态的子页state中,继承automatickeepaliveclientmixin并重写wantkeepalive为true即可。
notes:subclasses must implement wantkeepalive, and their build methods must call super.build (the return value will always return null, and should be ignored)
以首页推荐recommend_page.dart为例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
/// recommend_page.dart import 'package:flutter/material.dart' ; class recommendpage extends statefulwidget { @override _recommendpagestate createstate() => _recommendpagestate(); } class _recommendpagestate extends state<recommendpage> with automatickeepaliveclientmixin { int count = 0 ; void add() { setstate(() { count++; }); } @override bool get wantkeepalive => true ; @override void initstate() { super .initstate(); print( 'recommend initstate' ); } @override widget build(buildcontext context) { super .build(context); return scaffold( body:center( child: text( '首页推荐: $count' , style: textstyle(fontsize: 30 )) ), floatingactionbutton: floatingactionbutton( onpressed: add, child: icon(icons.add), )); } } |
再次保存测试,
现在已经可以看到,不管是切换底部导航还是切换首页顶部导航,所有的页面状态都可以被保持,并且在应用第一次加载时,终端只看到recommend initstate的日志,第一次切换首页顶部导航至vip页面时,终端输出vip initstate,当再次返回推荐页时,不再输出recommend initstate。
所以,使用tabbarview+automatickeepaliveclientmixin这种方式既实现了页面状态的保持,又具有类似惰性求值的功能,对于未使用的页面状态不会进行实例化,减小了应用初始化时的开销。
更新
前面在底部导航介绍了使用indexedstack和offstage两种方式实现保持页面状态,但它们的缺点在于第一次加载时便实例化了所有的子页面state。为了进一步优化,下面我们使用pageview+automatickeepaliveclientmixin重写之前的底部导航,其中pageview和tabbarview的实现原理类似,具体选择哪一个并没有强制要求。更新后的home.dart文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
/// home.dart import 'package:flutter/material.dart' ; import './pages/first_page.dart' ; import './pages/second_page.dart' ; import './pages/third_page.dart' ; class myhomepage extends statefulwidget { @override _myhomepagestate createstate() => _myhomepagestate(); } class _myhomepagestate extends state<myhomepage> { final items = [ bottomnavigationbaritem(icon: icon(icons.home), title: text( '首页' )), bottomnavigationbaritem(icon: icon(icons.music_video), title: text( '听' )), bottomnavigationbaritem(icon: icon(icons.message), title: text( '消息' )) ]; final bodylist = [firstpage(), secondpage(), thirdpage()]; final pagecontroller = pagecontroller(); int currentindex = 0 ; void ontap( int index) { pagecontroller.jumptopage(index); } void onpagechanged( int index) { setstate(() { currentindex = index; }); } @override widget build(buildcontext context) { return scaffold( bottomnavigationbar: bottomnavigationbar( items: items, currentindex: currentindex, ontap: ontap), // body: bodylist[currentindex], body: pageview( controller: pagecontroller, onpagechanged: onpagechanged, children: bodylist, physics: neverscrollablescrollphysics(), // 禁止滑动 )); } } |
然后在bodylist的子页state中继承automatickeepaliveclientmixin并重写wantkeepalive,以second_page.dart为例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
/// second_page.dart import 'package:flutter/material.dart' ; class secondpage extends statefulwidget { @override _secondpagestate createstate() => _secondpagestate(); } class _secondpagestate extends state<secondpage> with automatickeepaliveclientmixin { int count = 0 ; void add() { setstate(() { count++; }); } @override bool get wantkeepalive => true ; @override void initstate() { super .initstate(); print( 'second initstate' ); } @override widget build(buildcontext context) { super .build(context); return scaffold( body: center( child: text( 'second: $count' , style: textstyle(fontsize: 30 )) ), floatingactionbutton: floatingactionbutton( onpressed: add, child: icon(icons.add), )); } } |
ok,更新后保存运行,应用第一次加载时不会输出second initstate,仅当第一次点击底部导航切换至该页时,该子页的state被实例化。
至此,如何实现一个类似的 底部 + 首页顶部导航 完结 ~
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。
原文链接:https://juejin.im/post/5c7e4a02e51d4541bd34b40e