美文网首页
Flutter(十六):TabController

Flutter(十六):TabController

作者: 林ze宏 | 来源:发表于2020-07-22 09:42 被阅读0次

相比与 TabBar,使用 TabController 更有利于事件的监听,便于控制相关内容。

import 'package:flutter/material.dart';

class SettingsPage extends StatefulWidget {
  SettingsPage({Key key}) : super(key: key);

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

// 1 实现 SingleTickerProviderStateMixin
class _SettingsPageState extends State<SettingsPage>
    with SingleTickerProviderStateMixin {
  // 2 定义 TabController 变量
  TabController _tabController;

  // 3 覆盖重写 initState,实例化 _tabController
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = new TabController(length: 2, vsync: this);

    _tabController.addListener(() {
      print(_tabController.index);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('tabController'),
        bottom: TabBar(
          controller: _tabController, // 4 需要配置 controller!!!
          // isScrollable: true,
          tabs: <Widget>[
            Tab(text: '推荐'),
            Tab(text: '最新'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController, // 4 需要配置 controller!!!
        children: <Widget>[
          ListView(
            children: <Widget>[
              ListTile(
                title: Text(
                  'diyigezuixin  推荐',
                  style: TextStyle(fontSize: 14.0),
                ),
              ),
              ListTile(
                title: Text('diyigezuixin  推荐'),
              ),
            ],
          ),
          Container(
            child: Text('zuixidddd'),
          ),
        ],
      ),
    );
  }
}

效果

相关文章

网友评论

      本文标题:Flutter(十六):TabController

      本文链接:https://www.haomeiwen.com/subject/pwqzfktx.html