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

Flutter如何实现支持单选的动态动画容器chip标签列表

问题原因

你当前所有标签共用同一个全局布尔状态_isTapped,因此任意标签触发状态更新都会让所有标签同步响应样式,就会出现全选变色的问题。

解决方案

将状态修改为记录当前选中标签的下标/内容,仅匹配到的标签才加载选中样式即可。单选场景下只需要存储一个选中值即可,无需为每个标签单独维护状态。

修改后的完整代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:flutter/painting.dart';

import 'package:scree/constants.dart';

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

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


class _SiteAbooutScreenState extends State<SiteAbooutScreen> {
// 替换原有布尔状态,存储当前选中的标签下标,未选中时为null
int? _selectedIndex;
@override Widget build(BuildContext context) {

return Scaffold(
  body: Padding(
    padding: EdgeInsets.only(left: 24, right: 24, top: 74.75),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Wrap(
          spacing: 16,
          runSpacing: 16,
          // 转为带下标映射的遍历
          children: _stuff
              .asMap()
              .entries
              .map(
                (entry) => GestureDetector(
                  onTap: () {
                    setState(() {
                      // 直接赋值为当前选中的下标,需要支持取消选中可改为:_selectedIndex = _selectedIndex == entry.key ? null : entry.key
                      _selectedIndex = entry.key;
                    });
                    // 选中后跳转逻辑,YourNextPage替换为你自己的目标页面组件,可按需传递选中的标签内容
                    Navigator.push(context, MaterialPageRoute(builder: (context)=> YourNextPage(selectedTag: entry.value)));
                  },
                  child: AnimatedContainer(
                    padding:
                        EdgeInsets.symmetric(horizontal: 24, vertical: 10),
                    duration: Duration(milliseconds: 200),
                    decoration: BoxDecoration(
                        // 仅当前下标和选中下标一致时用选中色
                        color: _selectedIndex == entry.key ? primary1 : Colors.transparent,
                        border: Border.all(color: Colors.black54),
                        borderRadius: BorderRadius.circular(100)),
                    child: Text(
                      entry.value,
                      style: Small.copyWith(
                          fontSize: 14,
                          color:
                              _selectedIndex == entry.key ? Colors.white : Color(0xff929292)),
                    ),
                  ),
                ),
              )
              .toList(),
        )
      ],
    ),
  ),
);
 }

  List<String> _stuff = [
'Portfolio',
'Art',
'Marketing',
'Education',
'Blog',
'Travel',
'Fashion',
'Beauty',
'Design',
'Online Store',
'Fitness',
'Food'
 ];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:15:04