Flutter BottomNavigationBar点击tab widget重绘问题

最近学习用flutter做一个app,做首页时用viewpage实现,后发现每次切换底部tab,页面都会重绘。

随即网上查了好多资料,基本上都是继承AutomaticKeepAliveClientMixin,然后重写wantKeepAlive = true;

实际做法就是:

class MainScreenState extends State<MainScreen> with AutomaticKeepAliveClientMixin 

然后重写:

@override
bool get wantKeepAlive => true;

但是在我这里并没有起作用,具体原因有待查明。

然后发现了另外一种方法。

就是,不使用PageView 而是使用IndexedStack。

IndexedStack所有child的状态都被保持,仅显示指定页面,其它页面是不可见的。

使用IndexedStack后页面也比PageView更简洁了。

代码如下:

int _selectedIndex = 0; // 当前选中的索引

/// tabs的名字
final bottomBarTitles = ["资讯", "方案", "排行", "我的"];

var pages = <Widget>[
  HomeScreen(),
  PlanWidget(),
  ReportCardWidget(),
  MyWidget()
];

@override
Widget build(BuildContext context) {
  // TODO: implement build
  return WillPopScope(
    onWillPop: _onWillPop,
    child: Scaffold(
      body: IndexedStack(
        index: _selectedIndex,
        children: pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        type: BottomNavigationBarType.fixed, // 设置显示模式
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              icon: Icon(Icons.art_track), title: Text(bottomBarTitles[0])),
          BottomNavigationBarItem(
              icon: Icon(Icons.videogame_asset),
              title: Text(bottomBarTitles[1])),
          BottomNavigationBarItem(
              icon: Icon(Icons.assessment), title: Text(bottomBarTitles[2])),
          BottomNavigationBarItem(
              icon: Icon(Icons.account_box), title: Text(bottomBarTitles[3]))
        ],
        onTap: (int index) {
          setState(() {
            _selectedIndex = index;
          });
        },
      ),
    ),
  );
}

完整代码:https://github.com/YY-tomorrow/flutter_zjy

当然使用IndexedStack也是参考了一篇文章:https://www.jb51.net/article/157680.htm,还讲述了一些其他的方法,个人采用了IndexedStack这种方式。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值