我的应用有两个标签,切换标签不会保持其状态。我在网上搜索,发现将AutomaticKeepAliveClientMixin
与wantKeepAlive
和true
一起使用super.build(context)
。我完全按照网络和stackoverflow上其他用户的指示进行了操作,但是问题仍然存在。
这是我的代码:
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with AutomaticKeepAliveClientMixin{
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return MaterialApp(
title: 'Flutter GridView',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.blue,
accentColor: Colors.white,
),
home: DefaultTabController(
length: 2,
child: Scaffold(
drawer: Drawer(),
backgroundColor: Colors.blueAccent,
appBar: AppBar(
backgroundColor: Colors.blueAccent,
title: Text('AIO'),
bottom: TabBar(
tabs: <Widget>[
Tab(icon: Icon(Icons.search)),
Tab(icon: Icon(Icons.favorite)),
],
),
),
body: TabBarView(
children: <Widget>[
gridView,
SecondPage(),
],
),
),
),
);
}}
答案 0 :(得分:0)
使用PageStorage,PageStorageBucket和PageStorageKey。
创建PageStorageBucket的实例字段,用PageStorage包装TabBarView,然后将PageStorageKey添加到GridView。
class _MyAppState extends State<MyApp> {
final PageStorageBucket bucket = PageStorageBucket();
//...
body: PageStorage(
bucket: bucket,
child: TabBarView(
children: <Widget>[
gridView, // add to GridView(key: PageStorageKey('MyGridViewKey'), //...
SecondPage(),
],
),
),
//...