Fork me on GitHub

Flutter - BottomNavigationBar底部导航栏切换后,状态丢失

如果你用过BottomNavigationBarTabBar、还有Drawer,你就会发现,在切换页面之后,原来的页面状态就会丢失。

要是上一页有一个数据列表,很多数据,你滚动到了下头,切换页面后,想再看一下下头的数据,但是Flutter给你重回页面了。。。

这谁能顶得住啊。

 

 

看了一下解释,原来Flutter中为了节约内存不会保存widget的状态,widget都是临时变量。

不过还是有很多办法解决的,网上传言用 AutomaticKeepAliveClientMixin 配合

@override
bool get wantKeepAlive => true;

 

服用,效果会达到保持状态。但是这个方法貌似只对TabBar起作用,BottomNavigationBar 对 AutomaticKeepAliveClientMixin 有免疫,不起作用。

 

后来一顿猛于虎的番羽土啬操作后,还是找到了解决方案,完美实现BottomNavigationBar底部导航栏切换,状态保持。

 

答案就是body使用IndexedStack即可。

 

参考我的代码:

import 'package:flutter/material.dart';

import './pages/home_page.dart';
import './pages/book_page.dart';
import 'package:bottom_nav_bar_test/pages/movie_page.dart';
import 'package:bottom_nav_bar_test/pages/music_page.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bottom Navigation',
      home: Main(),
      theme: ThemeData(primaryColor: Colors.orange),
    );
  }
}

class Main extends StatefulWidget {
  @override
  _MainState createState() => _MainState();
}

class _MainState extends State<Main> {
  int _currentIndex = 0;
  final List<Widget> _children = [Home(), Book(), Music(), Movie()];

  final List<BottomNavigationBarItem> _list = <BottomNavigationBarItem>[
    BottomNavigationBarItem(
        icon: Icon(Icons.home),
        title: Text('Home'),
        //backgroundColor: Colors.orange
        ),
    BottomNavigationBarItem(
        icon: Icon(Icons.book),
        title: Text('Book'),
        //backgroundColor: Colors.orange
        ),
    BottomNavigationBarItem(
        icon: Icon(Icons.music_video),
        title: Text('Music'),
        //backgroundColor: Colors.orange
        ),
    BottomNavigationBarItem(
        icon: Icon(Icons.movie),
        title: Text('Movie'),
        //backgroundColor: Colors.orange
        ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bottom Navigation'),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        items: _list,
      ),
      //body: _children[_currentIndex],
      body: IndexedStack(
        index: _currentIndex,
        children: _children,
      ),
    );
  }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}

 

 

参考 https://stackoverflow.com/questions/53011686/flutter-automatickeepaliveclientmixin-is-not-working-with-bottomnavigationbar 中 hfimy 的回答。

posted @ 2019-03-29 22:32  猫叔Vincent  阅读(5594)  评论(2编辑  收藏  举报