颤振中的多标签/页面视图

apt*_*tik 5 flutter

如何在flutter中创建多页面视图,其中页面对应于bottomnavigationbar中的选项卡,使得与页面对应的窗口小部件仅按需构建一次.

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

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

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

Col*_*son 15

要给出TabBarView一个唯一的滚动位置存储容器的页面,请使用a PageStorageKey.

视频

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'),
          ),
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)