TabBarController实现顶部导航

TabBarController实现顶部导航

  1. 继承(with) SingleTickerProviderStateMixin类
  2. 定义TabBarController对象
TabController _tabController;
  1. 重写initState()方法,实例化TabBarController
  @override
  void initState() {
    
    
    // TODO: implement initState
    super.initState();
    _tabController = new TabController(length: 2, vsync: this);
  }
// ignore_for_file: prefer_const_constructors_in_immutables, prefer_const_literals_to_create_immutables, unnecessary_new, avoid_print, prefer_const_constructors

import 'package:flutter/material.dart';

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

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

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

//组件加载时就会触发
  @override
  void 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("TabBarControllerPage"),
        bottom: TabBar(
            controller: _tabController,
            tabs: [Tab(text: "热销"), Tab(text: "推荐")]),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          Center(
            child: Text("热销"),
          ),
          Center(child: Text("推荐"))
        ],
      ),
    );
  }
}

猜你喜欢

转载自blog.csdn.net/m0_46527751/article/details/122547343