Issue
I want to change dynamically box color depending status in a JSON API.
For example, Approved = Colors.green, Rejected = Colors.red, Submitted = Colors.blue.
this is the image of my current app
i underline the status
how can achieve it?
this is how i get the 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;
}
this is how i loop the data :
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(",") });
}
});
this is my widget :
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(),
);
}
Solution
You can create a method to return the Color according the condition (assuming event.toString() = Rejected
, Approved
or Submitted
):
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),
),
Answered By – diegoveloper
Answer Checked By – Senaida (FlutterFixes Volunteer)