要是上一页有一个数据列表,很多数据,你滚动到了下头,切换页面后,想再看一下下头的数据,但是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 {
int _currentIndex = 0;
final List _children = [Home(), Book(), Music(), Movie()];
final List _list = [
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://www.cnblogs.com/hupo376787/p/10624636.html