Flutter 通过TabController实现顶部tab切换

在这里插入图片描述

import 'package:flutter/material.dart';

class TabBarControllerPage extends StatefulWidget {

  const TabBarControllerPage({Key key}) : super(key: key);
  @override
  _TabBarControllerPageState createState() => _TabBarControllerPageState();
}

class _TabBarControllerPageState extends State<TabBarControllerPage> with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController=new TabController(length: 2, vsync: this);//固定写法,length为tab数
    _tabController.addListener((){//监听滑动或者点击
      print(_tabController.index);
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TabBar(
          controller: _tabController,//必要
          tabs: <Widget>[
            Tab(text: '推荐',),
            Tab(text: '热销',),
          ],
        ),
      ),
      body: TabBarView(
        controller: this._tabController,//必要
        children: <Widget>[
           Center(child: Text('推荐'),),
           Center(child: Text('热销'),)
        ],
      ),
    );
  }
}

猜你喜欢

转载自blog.csdn.net/qq_42572245/article/details/106713747