保留标签视图页面之间的状态
问题内容:
问题
我ListViews
在TabBarView
使用时有两个渲染TabController
。
如何保持每个状态之间的状态(因为缺少更好的用词),ListView
以便:1.)小部件不重建,以及2.)ListView
在选项卡之间记住位置。
相关代码
class AppState extends State<App> with SingleTickerProviderStateMixin {
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = new TabController(
vsync: this,
length: _allPages.length,
);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
Widget _buildScaffold(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('headlines'),
bottom: new TabBar(
controller: _tabController,
isScrollable: true,
tabs: _allPages
.map((_Page page) => new Tab(text: page.country))
.toList()),
),
body: new TabBarView(
controller: _tabController,
children: _allPages.map((_Page page) {
return new SafeArea(
top: false,
bottom: false,
child: new Container(
key: new ObjectKey(page.country),
child: new Newsfeed(country: page.country),
),
);
}).toList()),
);
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'news app',
home: _buildScaffold(context),
);
}
}
插图gif
问题答案:
长话短说,对您的ListView或其祖先之一使用PageStorageKey(),在您的情况下为Container小部件:
child: new Container(
key: new PageStorageKey(page.country),
child: new Newsfeed(country: page.country),
),
在这里查看详细信息:
-
https://docs.flutter.io/flutter/widgets/PageStorageKey-class.html
-
https://docs.flutter.io/flutter/widgets/PageStorage-class.html
-
https://docs.flutter.io/flutter/widgets/ScrollView/controller.html