flutter - flutter 中的多选项卡/页面 View

标签 flutter

我如何在 flutter 中创建多页面 View ,其中页面对应于底部导航栏中的选项卡,以便与页面对应的小部件仅按需构建一次。

例如,考虑一个简单的 facebook 应用程序类型的 UI,它具有两个选项卡 - 具有以下行为的提要和通知:

  1. 提要和通知都是通过网络获取的项目列表。
  2. 假设原始标签是提要,只有当用户点击通知标签时才应该获取通知
  3. 如果用户在 Feed 中滚动,然后点击通知图标,然后再次点击 Feed 图标,应该记住滚动位置。

如果我使用 TabBarView,它会在每次更改选项卡时重建小部件,因此不会保留滚动位置。

最佳答案

要为 TabBarView 的页面提供唯一的滚动位置存储容器,请使用 PageStorageKey

video

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  TabController _controller;
  int _tab = 0;

  @override
  void initState() {
    _controller = new TabController(length: 2, vsync: this);
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text('Example App')),
      body: new TabBarView(
        controller: _controller,
        children: <Widget>[
          new ListView.builder(
            key: new PageStorageKey('feed'),
            itemBuilder: (BuildContext context, int index) {
              return new ListTile(
                title: new Text('Feed Item $index'),
              );
            },
          ),
          new ListView.builder(
            key: new PageStorageKey('notifications'),
            itemBuilder: (BuildContext context, int index) {
              return new ListTile(
                title: new Text('Notification $index'),
              );
            },
          ),
        ],
      ),
      bottomNavigationBar: new BottomNavigationBar(
        onTap: (int value) {
          _controller.animateTo(value);
          setState(() {
            _tab = value;
          });
        },
        currentIndex: _tab,
        items: <BottomNavigationBarItem>[
          new BottomNavigationBarItem(
            icon: new Icon(Icons.home),
            title: new Text('Home'),
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.notifications),
            title: new Text('Notifications'),
          ),
        ],
      ),
    );
  }
}

关于flutter - flutter 中的多选项卡/页面 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042537/

相关文章:

android - 在 Flutter 中显示 100 张或更多图像的最快方法

flutter - 如何在不需要打开应用程序的情况下显示对话框

android - 如何定义与另一个列表长度相同的默认列表

dart - 如何提取 Dart/Flutter 视频元数据

flutter - 使用NotificationListener检测滚动到列表末尾

flutter - 无论如何,是否可以在 flutter web 的新选项卡中打开页面?

android - 如何在 Flutter 中调整图标/图标按钮的大小?

flutter - 仅将指定的可选参数传递给基础小部件

firebase - flutter 火 : Calling cloud function throws an internal error with no details - FirebaseFunctionsException [firebase_functions/17999]

flutter - 是否有Dart函数来检查对象是否具有特定的属性或方法?