加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 14:48:19 所属栏目:百科 来源:网络整理
导读:问题 我使用TabController在TabBarView内部渲染了两个ListView. 如何在每个ListView之间保留状态(缺少更好的单词),以便:1)Widgets不重建,以及2.)在选项卡之间记住ListView位置. 相关代码 class AppState extends StateApp with SingleTickerProviderStateMi
问题

我使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读