我在 StateFull 小部件的 initState 函数中动态生成 FilterChips,如下所示。
List<Category> categories;
List<FilterChip> chips;
(...)
in initState() :
for (Category c in categories) {
chips.add(FilterChip(
label: chipText(context, c.name),
onSelected: (val) {
print(val); // val is always false !
c.enabled = !c.enabled;
print(categories); // this is ok, categories values are perfectly updated
setState(() {});
},
selected: c.enabled, // however, the filterchip selected state does not reflect c.enabled value changes
selectedColor: accentColor(context),
));
}
当我点击filterchip时,Categoy的值完美更新,但是chip selection状态没有改变。有谁知道为什么?
回答我如何使用芯片:这是在构建函数中,如下所示:
@override
build(BuildContext context) {
return SliverToBoxAdapter(
child: Wrap(
children: chips
)
最佳答案
pskink 给出了完美的答案:谢谢!
这是工作代码,其中芯片是直接在构建函数中动态创建的:
@override
build(BuildContext context) {
if (categories != null) {
chips = categories
.map((c) => FilterChip(
label: chipText(context, c.name ?? ""),
onSelected: (val) {
setState(() {
c.enabled = val;
});
updateSelection();
},
selected: c.enabled,
selectedColor: accentColor(context),
))
.toList();
}
return SliverToBoxAdapter(
child: Wrap(
children: chips
关于Flutter 动态创建的 FilterChip 未在 onSelected() 上更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63939113/