我在popupmenubutton内使用了自定义popupmenuitem,我想在点击时更改图标的颜色,因此我使用布尔符号进行识别。问题是,我使用setState更改值,值当然会更改,但是ui(color)不会更改!我无法弄清楚。我在这里粘贴我的代码。这些都在应用栏中。我也尝试使用构建器小部件,但它不能解决我的问题。
actions: <Widget>[
PopupMenuButton(
tooltip: 'Filters',
padding: EdgeInsets.all(0),
icon: Icon(
Icons.filter_list,
color: Colors.black54,
),
itemBuilder: (BuildContext context) {
{
return <PopupMenuEntry>[
//locN
PopupItem(
child: GestureDetector(
onTap: () {
if(!_nearMe && !_specificLoc){
FilterList.selectedFilter.add(FilterList.nearMe);
print(FilterList.selectedFilter);
setState(() {
_nearMe = true;
});
}
else if (_specificLoc){
FilterList.selectedFilter.remove(FilterList.specificLoc);
FilterList.selectedFilter.add(FilterList.nearMe);
setState(() {
_specificLoc = false;
_nearMe = true;
});
print(FilterList.selectedFilter);
}
else{
setState(() {
_nearMe = false;
});
FilterList.selectedFilter.remove(FilterList.nearMe);
print(FilterList.selectedFilter);
}
},
child: ListTile(
leading: Icon(Icons.info_outline, color: _nearMe?Colors.green:Colors.black54,),
title: Text(FilterList.nearMe),
),
),
),
//loc
PopupItem(
child: GestureDetector(
onTap: () {
if(!_nearMe && !_specificLoc){
FilterList.selectedFilter.add(FilterList.specificLoc);
print(FilterList.selectedFilter);
setState(() {
_specificLoc = true;
});
}
else if (_nearMe){
FilterList.selectedFilter.remove(FilterList.nearMe);
FilterList.selectedFilter.add(FilterList.specificLoc);
setState(() {
_nearMe = false;
_specificLoc = true;
});
print(FilterList.selectedFilter);
}
else{
setState(() {
_specificLoc = false;
});
FilterList.selectedFilter.remove(FilterList.specificLoc);
print(FilterList.selectedFilter);
}
},
child: ListTile(
leading: Icon(Icons.info_outline, color: _specificLoc?Colors.green:Colors.black54,),
title: Text(FilterList.specificLoc),
),
),
),
bool _specificLoc和_nearMe用于更改弹射中的颜色。
我对此进行了研究,但针对这种情况的唯一可行解决方案是流生成器。请告诉我您是否有更好的方法。 setState通常不适用于使用父级上下文的itemBuilder或小部件。再次告诉我我是否错!这是我的解决方案
//This the class for streams
class BlocDemo{
StreamController streamListController = StreamController<Color>.broadcast();
//sink
Sink get colorSink => streamListController.sink;
//stream
Stream<Color> get colorStream => streamListController.stream;
changeColorGreen() {
colorSink.add(Colors.green);
}
changeColorBlac(){
colorSink.add(Colors.black54);
}
}
和用法
actions: <Widget>[
PopupMenuButton(
tooltip: 'Filters',
padding: EdgeInsets.all(0),
icon: Icon(
Icons.filter_list,
color: Colors.black54,
),
itemBuilder: (context) {
{
return <PopupMenuEntry>[
PopupItem(
child: GestureDetector(
onTap: () {
//the color is added to the sink
colorBloc.changeColorGreen();
},
child: StreamBuilder<Object>(
initialData: Colors.black54,
stream: colorBloc.colorStream,
builder: (context, snapshot) {
return ListTile(
leading: Icon(Icons.info_outline, color: snapshot.data),
title: Text(FilterList.nearMe),
);
}
),
),
),