flutter - 在选项卡 View 页面之间保留状态

标签 flutter listview dart flutter-layout tabview

问题

我有两个 ListViews 使用 TabControllerTabBarView 中呈现。

我如何在每个 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

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

最佳答案

如果您想在 TabBarView 中保持屏幕状态,您可以在 State 类中使用名为 AutomaticKeepAliveClientMixin 的混合类。

之后,您必须覆盖 wantKeepAlive 方法并返回 true。它看起来像:

class _SearchScreenState extends State<SearchScreen> with AutomaticKeepAliveClientMixin<SearchScreen>{

...

  @override
  Widget build(BuildContext context) { 
    // call this method
    super.build(context); 

    /// your widget here
  }

  @override
  bool get wantKeepAlive => true;

}

我在这里写了一篇关于这个的帖子:https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

关于flutter - 在选项卡 View 页面之间保留状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53119017/

相关文章:

flutter - 在 Flutter 中创建私有(private)路由

flutter - 我如何使用第一次 API 调用的结果作为第二次 API 调用的输入?

android - 如何将单选列表添加到android中的自定义对话框?

firebase - 无法将FLUTTER参数分配给参数类型

ubuntu - Ubuntu 中的 Dartium

sqlite - Dart-使用泛型将List <SuperType>转换为List <SubType>

xcode - flutter ios 应用程序在 xcode 上运行,但无法在 vscode 和 android studio 上运行

android - 列表显示。单击 imageView 时获取 itemId

android - 在 Sherlock Fragment 中实现列表搜索 View

dart - bin 子目录没有生成的包目录