flutter - Flutter OnSelected - how to access "this"
问题描述
I need to know how to access "this" when using the onSelected function within my button.
Using latest flutter I have the following code:
FilterChip(
backgroundColor: _colorNavFilter,
padding: EdgeInsets.only(
top: 8, right: 4, bottom: 8, left: 12),
elevation: 2,
avatar: CircleAvatar(
backgroundColor: Colors.transparent,
child: _filter[index]['icon'],
),
label: Text(
_filter[index]['title'],
style: TextStyle(color: _colorNav),
),
onSelected: (bool value) {
setState(() {
if (postCategory == 'false') {
postCategory = _filter[index]['title'];
_colorNav = Colors.black; // This will end up coloring all buttons in the list - but I want only this specific one
_colorNavFilter = Colors.black;
} else {
postCategory = 'false';
_colorNav = _colorBlue;
_colorNavFilter = Colors.white;
}
});
},
);
The problem is that it will color all buttons having that variable in black. I'm aware I could define a dedicated variable for every button and then modify this one with index but that seems rather ugly. Can I not do something like "this.color = Colors.black"?
解决方案
onSelected
是正确的,但您应该将它与selected
. 尝试这个:
bool selectedValue = false;
FilterChip(
backgroundColor: selectedValue? Colors.black : Colors.white,
selected: selectedValue, // This is important
padding: EdgeInsets.only(
top: 8, right: 4, bottom: 8, left: 12),
elevation: 2,
avatar: CircleAvatar(
backgroundColor: Colors.transparent,
child: _filter[index]['icon'],
),
label: Text(
_filter[index]['title'],
style: TextStyle(color: selectedValue? Colors.black : _colorBlue),
),
onSelected: (bool value) {
setState(() {
if (postCategory == 'false') {
postCategory = _filter[index]['title'];
selectedValue = true;
} else {
postCategory = 'false';
selectedValue = false;
}
});
},
);
推荐阅读
- common-lisp - Common Lisp 声明的范围(例如,用于优化)
- powerbi - 为什么 PowerBI 报表无法在移动设备上显示?
- azure-data-factory-2 - 数据流接收到 csv 不使用文件名
- python - TypeError: 'int' 对象不可迭代 - 但它是一个列表
- jquery - 无法等待多个 AJAX 调用完成
- css - (sass):26096 如何修复 Rails 中的“Sass::SyntaxError: Invalid CSS after”错误
- javascript - 为三个 JS 导出时,Blender 模型和动画变形
- angular - 使用全局错误处理程序处理 NGXS(角度)中的错误
- javascript - 使用javascript将图像和文本从剪贴板复制到tinyMCE
- android - 如何在使用 javax.xml.soap 库时修复“NoClassDefFoundError: com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl”错误