在iOS/Android中,如果希望在点击切换到对应的界面之后刷新当前页面,iOS/Android提供了一套完整的生命周期供我们使用,同时tabbar也了提供点击后对应的协议/接口。可以说是非常成熟和方便了。
Flutter也有自己的生命周期,但却没有原生那么成熟,下一篇我们单独来说下Flutter生命周期的使用,今天我们来说一种通过GlobalKey来实现点击后刷新当前界面的方法。
我们来假定一个场景,我们有一个app,有四个tabber,我们希望在点击个人中心的tab时可以刷新个人中心中的用户信息数据,这个时候我们需要分三步来做:
- 第一步,在个人中心定义GlobalKey和要刷新的方法,并在initState中初始化该方法
import 'package:flutter/material.dart';
///定义GlobalKey
GlobalKey<_MinePageState> mineGlobalKey = GlobalKey();
class MinePage extends StatefulWidget {
///就是一个空的构造方法,传key用的
MinePage({Key key}) : super(key: key);
@override
_MinePageState createState() => _MinePageState();
}
void initState() {
// TODO: implement initState
super.initState();
///这个方法要初始化,否则不会执行
refreshMineView();
}
///点击tabbar之后,调用个人中心界面的这个方法来刷新接口数据
void refreshMineView() {
print('mineView');
}
- 第二步,在tabbar所在的界面,定义个人中心界面的时候,用带key的构造方法
///这里的构造方法需要把我们在个人中心定义的GlobalKey传进来
MinePage(key: mineGlobalKey,)
- 第三步,在点击tab的地方通过GlobalKey调用个人中心的刷新方法
///点击个人中心后,这么来调用刷新个人中心的方法
mineGlobalKey.currentState.refreshMineView();
接下来,我们来看下tabbar中完整的使用方法,和调用所在的位置,方便大家做参考。我们以一个最简单的tabbar页面为例:
///这是一个tabbar的页面
Widget build(BuildContext context) {
return Container(
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) {
_currentIndex = index;
setState(() {});
_controller.jumpToPage(index);
switch(index) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
///点击个人中心后,这么来调用刷新个人中心的方法
mineGlobalKey.currentState.refreshMineView();
break;
}
},
selectedFontSize: 12.0,
type: BottomNavigationBarType.fixed,
fixedColor: Colors.green,
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(
icon: Image(
height: 20,
width: 20,
image: AssetImage('images/tabbar_chat.png')),
activeIcon: Image(
height: 20,
width: 20,
image: AssetImage('images/tabbar_chat_hl.png')),
title: Text('微信')),
BottomNavigationBarItem(
icon: Image(
height: 20,
width: 20,
image: AssetImage('images/tabbar_friends.png')),
activeIcon: Image(
height: 20,
width: 20,
image: AssetImage('images/tabbar_friends_hl.png')),
title: Text('通讯录')),
BottomNavigationBarItem(
icon: Image(
height: 20,
width: 20,
image: AssetImage('images/tabbar_discover.png')),
activeIcon: Image(
height: 20,
width: 20,
image: AssetImage('images/tabbar_discover_hl.png')),
title: Text('发现')),
BottomNavigationBarItem(
icon: Image(
height: 20,
width: 20,
image: AssetImage('images/tabbar_mine.png')),
activeIcon: Image(
height: 20,
width: 20,
image: AssetImage('images/tabbar_mine_hl.png')),
title: Text('我的')),
]),
body: PageView(
onPageChanged: (int index) {
_currentIndex = index;
setState((){});
},
// physics: NeverScrollableScrollPhysics(),
controller: _controller,
children: <Widget>[
ChatPage(),
FriendPage(),
DiscoverPage(),
///这里的构造方法需要把我们在个人中心定义的GlobalKey传进来
MinePage(key: mineGlobalKey,)
],
),
)
);
}