You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中实现这种下拉式设计的Tab Bar?

Flutter 实现自定义样式 Tab Bar

自定义Tab Bar样式

请问如何在Flutter中实现图中这种样式的Tab Bar?

实现思路

图中Tab Bar的核心是自定义选中状态的底部指示器,同时区分Tab文字的选中/未选中样式。我们可以通过TabBar的内置属性快速实现,无需额外第三方包。

完整代码示例

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const CustomTabBarPage(),
      theme: ThemeData(primarySwatch: Colors.blue),
    );
  }
}

class CustomTabBarPage extends StatefulWidget {
  const CustomTabBarPage({super.key});

  @override
  State<CustomTabBarPage> createState() => _CustomTabBarPageState();
}

class _CustomTabBarPageState extends State<CustomTabBarPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    // 初始化Tab控制器,length对应Tab数量
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    // 销毁控制器避免内存泄漏
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        bottom: TabBar(
          controller: _tabController,
          // 自定义选中指示器:圆角背景+内边距适配文字宽度
          indicator: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            color: Colors.blueAccent.withOpacity(0.2),
          ),
          indicatorPadding: const EdgeInsets.symmetric(horizontal: 10),
          // 文字样式区分
          labelStyle: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          unselectedLabelStyle: const TextStyle(fontSize: 14),
          labelColor: Colors.blueAccent,
          unselectedLabelColor: Colors.grey,
          // Tab列表
          tabs: const [
            Tab(text: '全部'),
            Tab(text: '待付款'),
            Tab(text: '待发货'),
          ],
        ),
        title: const Text('订单Tab示例'),
      ),
      body: TabBarView(
        controller: _tabController,
        children: const [
          Center(child: Text('全部订单页面')),
          Center(child: Text('待付款订单页面')),
          Center(child: Text('待发货订单页面')),
        ],
      ),
    );
  }
}

关键细节说明

  • 自定义指示器:用BoxDecoration设置圆角和背景色,通过indicatorPadding控制指示器与文字的间距,实现宽度贴合文字的效果;如果需要底部下划线样式,可替换为UnderlineTabIndicator,自定义边距和线条宽度。
  • 状态区分:通过labelStyle/unselectedLabelStyle、labelColor/unselectedLabelColor直接设置文字的选中/未选中样式。
  • 控制器管理:TabController必须同时绑定TabBar和TabBarView,确保Tab切换与页面内容同步,记得在页面销毁时释放控制器。

内容的提问来源于stack exchange,提问作者Yogesh Dubey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 16:16:04