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

人气:1,026 发布:2022-10-16 标签: listview flutter dart flutter-layout tabview

问题描述

我有两个 ListViews 使用 TabControllerTabBarView 内呈现.

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

推荐答案

长话短说,为您的 ListView 或其祖先之一使用 PageStorageKey(),在您的案例中为 Container 小部件:

Long story short, use a PageStorageKey() for your ListView or one of it's ancestors, the Container widget in your case:

child: Container(
    key: PageStorageKey(page.country),
    child: Newsfeed(country: page.country),
),

在此处查看详细信息:

https://api.flutter.dev/flutter/小部件/PageStorageKey-class.html

https://api.flutter.dev/flutter/小部件/PageStorage-class.html

https://api.flutter.dev/flutter/小部件/ScrollView/controller.html

225