我想根据JSON API中的状态动态更改框颜色。 例如,已批准= Colors.green,已拒绝= Colors.red,已提交= Colors.blue。
this is the image of my current app 我强调状态
如何实现?
这是我获取API的方式:
Future getCalendar() async{
List<Events> list;
String api = "http://200.0.0.104/api/dynamic/uspGetCalendarEvents_mobile?EmployeeId=5";
var res = await http.get(Uri.encodeFull(api), headers: {"Accept": "application/json"});
var data = json.decode(res.body);
var rest = data["data"] as List;
list = rest.map<Events>((json) => Events.fromJson(json)).toList();
return list;
}
这就是我循环数据的方式:
getCalendar().then((data){
for (var a =0; a < data.length; a++ )
{
_events.addAll({DateTime.parse(data[a].start.toString().replaceAll("-", "")) : data[a].title.toString().split(",") });
}
});
这是我的小部件:
Widget _buildEventList() {
return ListView(
children: _selectedEvents
.map((event) => Container(
decoration: BoxDecoration(
color: Colors.blue, // i want to change the color
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: ListTile(
title: Text(event.toString()),
onTap: () => print('$event tapped!'),
),
))
.toList(),
);
}
答案 0 :(得分:2)
您可以创建一种根据条件(假设event.toString()= Rejected
,Approved
或Submitted
)返回Color的方法:
Color _getColorByEvent(String event) {
if (event == "Approved") return Colors.green;
if (event == "Rejected") return Colors.red;
return Colors.blue;
}
...
BoxDecoration(
color: _getColorByEvent(event.toString()), // i want to change the color
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
答案 1 :(得分:0)
例如颜色调用方法
return ListView(
children: _selectedEvents
.map((event) => Container(
decoration: BoxDecoration(
color: Colors.blue, // i want to change the color
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: ListTile(
title: Text(event.toString()),
onTap: () => print('$event tapped!'),
),
))
.toList(),
);
}
Color _getColor(Map event){ swith(event) { return value } }
答案 2 :(得分:0)
像这样创建一个映射键值对。
Map<String, Color> colorCode ={"Approved":Colors.green,"Rejected":Colors.red};
eg:-
final color=colorCode["Approved"];
然后传递密钥来映射,您将获得对应的密钥的值。
答案 3 :(得分:0)
这就是我的做法...
Color getColorForStatus(OrderStatus event) {
switch (event) {
case OrderStatus.PLACED:
return Colors.black;
break;
case OrderStatus.ORDER_CONFIRMED:
return Colors.lightBlue;
break;
case OrderStatus.OUT_FOR_DELIVERY:
return new Color(0xFFE5AC0E);
break;
case OrderStatus.DELIVERED:
return Colors.green;
break;
case OrderStatus.PAYMENT_DECLINED:
return new Color(0xFFFFA401);
break;
case OrderStatus.CANCELED:
return Colors.red;
break;
default:
return Colors.black;
break;
}
}