Flutter使用ChipsChoice带回调获取选中索引时如何更新选中UI
你当前代码的问题在于ChipsChoice的onChanged事件直接绑定了外部传入的回调函数,没有更新组件内部维护的tag状态,所以UI不会跟着选中状态变化。
只需要调整onChanged的实现逻辑,先更新本地状态再触发外部回调即可,如果你需要支持自定义初始选中项,还可以补充初始值参数,修改后的完整代码如下:
import 'package:flutter/material.dart'; import 'package:flutter_chip_choice/flutter_chip_choice.dart'; class TagChoices extends StatefulWidget { const TagChoices({ required this.options, required this.itemCallBack, this.initialValue = 0, // 可选初始值参数,默认选中第一个选项 Key? key }) : super(key: key); final List<Enum> options; final Function(int?) itemCallBack; final int initialValue; @override _TagChoicesState createState() => _TagChoicesState(); } class _TagChoicesState extends State<TagChoices> { late int tag; @override void initState() { super.initState(); // 初始化时赋值默认选中的索引 tag = widget.initialValue; } @override Widget build(BuildContext context) { return ChipsChoice<int>.single( value: tag, // 核心改动:先更新本地状态刷新UI,再触发外部回调传值 onChanged: (value) { setState(() { tag = value ?? widget.initialValue; }); widget.itemCallBack(value); }, choiceItems: C2Choice.listFrom<int, Enum>( source: widget.options, style: (i, v) { return const C2ChoiceStyle( borderRadius: BorderRadius.all(Radius.circular(10)), showCheckmark: false, ); }, activeStyle: (i, v) { return const C2ChoiceStyle( brightness: Brightness.dark, ); }, value: (i, v) => i, label: (i, v) => v.toString().split(".").last.replaceAll("_", " ").toUpperCase(), ), choiceStyle: const C2ChoiceStyle( color: Colors.blueGrey, avatarBorderColor: Colors.white, ), choiceActiveStyle: const C2ChoiceStyle( color: Color(0xFFff004d), ), ); } }
修改后组件内部会自动更新选中状态刷新UI,你传入的itemCallBack也可以正常拿到最新的选中索引处理业务逻辑,使用方式和之前保持一致即可。
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

