dart – 保留选项卡视图页面之间的状态

前端之家收集整理的这篇文章主要介绍了dart – 保留选项卡视图页面之间的状态前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题

我使用TabController在TabBarView内部渲染了两个ListView.

如何在每个ListView之间保留状态(缺少更好的单词),以便:1)Widgets不重建,以及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

https://media.giphy.com/media/2ysWhzqHVqL1xcBlBE/giphy.gif

解决方法

简而言之,对你的ListView或其中一个祖先使用PageStorageKey(),在你的情况下使用Container小部件:

child: new Container(
    key: new PageStorageKey(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

猜你在找的Flutter相关文章