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

Flutter 如何自定义 AppBar 中的 tabs 实现默认无分类选中效果

Flutter 分类Tab默认不选中实现思路

以下是两种可行的实现方案,可以根据你的业务复杂度选择:

方案1:完全自定义Tab组件(灵活度最高,推荐)

  • 单独维护选中状态变量,初始值设为null或者-1,代表没有选中任何分类,页面首次加载时默认请求全品类商品接口即可。
  • 自行实现Tab的布局和样式:每个Tab的选中/未选中样式完全根据你维护的选中变量判断,当选中值为初始的null/-1时,所有Tab都展示未选中样式。
  • 给每个Tab绑定独立的点击事件,点击时更新选中状态变量,同时触发对应分类的商品数据请求,不需要依赖系统TabBar自带的状态管理逻辑。
  • 商品列表区域直接使用普通的ListView/GridView,根据当前选中的分类值动态渲染数据即可,如果需要切换动画可以用AnimatedSwitcher包裹列表实现过渡效果。

核心代码示例:

// 分类数据模型
class Category {
  final String id;
  final String name;
  Category(this.id, this.name);
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 初始值为null代表未选中任何分类
  int? _selectedCategoryIndex;
  final List<Category> _categoryList = [
    Category('1', '女装'),
    Category('2', '男装'),
    Category('3', '数码'),
    Category('4', '食品'),
  ];
  List _goodsList = [];

  @override
  void initState() {
    super.initState();
    // 页面初始化默认加载全品类商品
    _loadGoods();
  }

  // 加载商品数据,categoryId为空时加载全品类
  Future<void> _loadGoods([String? categoryId]) async {
    // 调用你的商品接口,此处省略接口请求逻辑
    // final response = await Api.getGoods(categoryId: categoryId);
    // setState(() => _goodsList = response.data);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 自定义Tab区域
          SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            scrollDirection: Axis.horizontal,
            child: Row(
              spacing: 12,
              children: _categoryList.asMap().entries.map((entry) {
                final index = entry.key;
                final category = entry.value;
                final isSelected = _selectedCategoryIndex == index;
                return GestureDetector(
                  onTap: () {
                    setState(() => _selectedCategoryIndex = index);
                    // 加载对应分类商品
                    _loadGoods(category.id);
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    decoration: BoxDecoration(
                      color: isSelected ? Colors.blue : Colors.white,
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color: Colors.grey.shade300),
                    ),
                    child: Text(
                      category.name,
                      style: TextStyle(
                        color: isSelected ? Colors.white : Colors.black87,
                        fontSize: 14,
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
          // 商品列表区域
          Expanded(
            child: ListView.builder(
              itemCount: _goodsList.length,
              itemBuilder: (context, index) {
                // 你的商品项布局,此处省略
                return const SizedBox();
              },
            ),
          )
        ],
      ),
    );
  }
}

方案2:基于系统TabBar改造(适合不想完全重写Tab的场景)

系统默认TabController初始下标为0,会默认选中第一个Tab,我们可以通过加占位Tab的方式绕过这个逻辑:

  • 在Tab数组的最前面插入一个宽度为0的隐藏占位Tab,视觉上完全不会显示。
  • 初始化TabController时指定初始index为0,对应这个占位Tab,此时所有可见的分类Tab都处于未选中状态。
  • 自己做下标映射:index=0对应全品类,用户点击可见Tab时的下标n对应第n-1个分类,点击时请求对应分类的商品数据即可。

内容的提问来源于stack exchange,提问作者Mohamad Jabaly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:06:05