在选项卡视图页面之间保留状态 [英] Preserving state between tab view pages

查看:25
本文介绍了在选项卡视图页面之间保留状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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/PageStorage-class.html

https://docs.flutter.io/flutter/widgets/ScrollView/controller.html

这篇关于在选项卡视图页面之间保留状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆