问题描述
我在 TabBarView
中使用 TabController
渲染了两个 ListViews
.
I have two ListViews
rendering inside of a TabBarView
using a TabController
.
我如何在每个 ListView
之间保留状态(因为没有更好的词),以便:1.) 小部件不会重建和 2.) ListView
> 标签之间的位置被记住.
How do I preserve state (for lack of a better word) between each ListView
so that: 1.) the Widgets don't rebuild and 2.) the ListView
position is remembered between tabs.
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
https://media.giphy.com/media/2ysWhzqHVqL1xcBlBE/giphy.gif
推荐答案
长话短说,将 PageStorageKey() 用于您的 ListView 或其祖先之一,在您的案例中为 Container 小部件:
Long story short, use a PageStorageKey() for your ListView or one of it's ancestors, the Container widget in your case:
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