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

Flutter实现Chip列表点击切换激活与非激活颜色方案咨询

实现Flutter Chip组的点击切换颜色效果

这其实是个典型的单选场景,用一个状态变量跟踪选中状态就能优雅解决,我给你梳理下具体思路和代码示例:

核心思路

  • 用一个状态变量(比如_selectedIndex)记录当前选中的Chip索引,初始值设为-1(表示初始无选中状态)
  • 点击任意Chip时,更新这个变量为当前Chip的索引
  • 构建每个Chip时,根据_selectedIndex是否等于当前索引,动态切换背景色(选中为黑色,未选中为灰色)

完整代码示例

import 'package:flutter/material.dart';

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

  @override
  State<ChipSelectionDemo> createState() => _ChipSelectionDemoState();
}

class _ChipSelectionDemoState extends State<ChipSelectionDemo> {
  // 记录选中的Chip索引,初始无选中
  int _selectedIndex = -1;
  // Chip的数据源,可根据需求自定义
  final List<String> _chipLabels = ['选项1', '选项2', '选项3', '选项4'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Chip单选示例')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        // 用Wrap实现自动换行的Chip布局,也可以用ListView
        child: Wrap(
          spacing: 8.0,
          runSpacing: 8.0,
          children: List.generate(_chipLabels.length, (index) {
            return Chip(
              label: Text(_chipLabels[index]),
              // 根据选中状态切换背景色
              backgroundColor: _selectedIndex == index 
                  ? Colors.black 
                  : Colors.grey[300],
              // 点击时更新选中索引
              onPressed: () {
                setState(() {
                  _selectedIndex = index;
                });
              },
              // 可选:选中时文字变白色,增强对比度
              labelStyle: TextStyle(
                color: _selectedIndex == index ? Colors.white : Colors.black,
              ),
            );
          }),
        ),
      ),
    );
  }
}

额外优化点

  • 如果需要支持取消选中(点击已选中的Chip恢复未选中状态),可以在onPressed里加个判断:
    onPressed: () {
      setState(() {
        _selectedIndex = _selectedIndex == index ? -1 : index;
      });
    },
    
  • 可以把颜色提取为常量,方便统一修改和维护
  • 如果Chip数量较多,用List.generate比手动逐个写Chip更高效

这种实现方式逻辑清晰,代码简洁,只用一个状态变量就完成了所有Chip的状态控制,非常容易维护和扩展~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:08:18