Flutter -- Tab

Flutter – Tab

本文通过提供几个例子介绍Flutter Tab的使用
http://cairuoyu.com/flutter_demo
在这里插入图片描述

Demo

使用TabController

使用时需要with TickerProviderStateMixin

List<Tab> tabs = <Tab>[
  Tab(text: 'tab1'),
  Tab(text: 'tab2'),
];

List<Widget> tabBarViews = <Widget>[
  Center(child: Text('tabPage1')),
  Center(child: Text('tabPage2')),
];
class TabSimple extends StatefulWidget {
  @override
  _TabSimpleState createState() => _TabSimpleState();
}

class _TabSimpleState extends State<TabSimple> with TickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    var result = Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        bottom: TabBar(controller: _tabController, tabs: tabs),
      ),
      body: TabBarView(controller: _tabController, children: tabBarViews),
    );
    return result;
  }
}

使用DefaultTabController

简单的功能可以使用DefaultTabController,它其实是对TabController的封装,可以减少代码量

class TabSimpleDefault extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var result = DefaultTabController(
      length: tabs.length,
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          bottom: TabBar(tabs: tabs),
        ),
        body: TabBarView(children: tabBarViews),
      ),
    );
    return result;
  }
}

切换Tab时保持状态

当切换Tab时,页面会调用init和build重新渲染,从而失去状态。官方推荐使用AutomaticKeepAliveClientMixin来控制每个页面是否需要保持状态

import 'package:flutter/material.dart';

import 'data.dart';

class TabKeepAlive extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var result = DefaultTabController(
      length: tabs.length,
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          bottom: TabBar(tabs: tabs),
        ),
        body: TabBarView(children: [
          KeepAlivePage(
            title: 'page1',
          ),
          KeepAlivePage(
            title: 'page2',
          ),
        ]),
      ),
    );
    return result;
  }
}

class KeepAlivePage extends StatefulWidget {
  final String title;

  const KeepAlivePage({Key key, this.title}) : super(key: key);

  @override
  _KeepAlivePageState createState() => _KeepAlivePageState();
}

class _KeepAlivePageState extends State<KeepAlivePage> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
    print('init--' + widget.title);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    print('build--' + widget.title);
    var result = TextField(
      decoration: InputDecoration(hintText: '请输入' + widget.title),
    );
    return result;
  }

  @override
  bool get wantKeepAlive => true;
}

动态Tab

可动态增加或减少Tab

class TabDynamic extends StatefulWidget {
  @override
  _TabDynamicState createState() => _TabDynamicState();
}

class _TabDynamicState extends State<TabDynamic> with TickerProviderStateMixin {
  TabController tabController;
  int tabNum = 3;

  @override
  Widget build(BuildContext context) {
    int index = tabController?.index ?? 0;
    index = tabNum > index ? index : tabNum - 1;
    tabController?.dispose();
    tabController =
        TabController(length: tabNum, vsync: this, initialIndex: index);
    tabController.animateTo(tabNum - 1);
    var tabs = List.generate(
      tabNum,
      (index) => Tab(
        child: Row(
          children: [
            Text('tab' + index.toString()),
            IconButton(
              splashRadius: 10,
              iconSize: 10,
              icon: Icon(Icons.close_outlined),
              onPressed: () {
                setState(() {
                  tabNum--;
                });
              },
            )
          ],
        ),
        // icon: Icon(Icons.add),
      ),
    );
    var tabPages = List.generate(
      tabNum,
      (index) => Center(
        child: TestPage(index),
      ),
    );

    var tabBar = TabBar(
      isScrollable: true,
      tabs: tabs,
      controller: tabController,
    );
    var tabBarView = TabBarView(
      children: tabPages,
      controller: tabController,
    );
    var result = Scaffold(
      appBar: AppBar(automaticallyImplyLeading: false, bottom: tabBar),
      body: tabBarView,
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          setState(() {
            tabNum++;
          });
        },
      ),
    );
    return result;
  }
}

源码地址:

https://github.com/cairuoyu/flutter_demo

更多复杂功能参考:

https://github.com/cairuoyu/flutter_admin/blob/master/lib/pages/layout/layout_center.dart

相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页