我正在做 Flutter 项目。我像这样从服务器获取数据列表:
{
"id": 39,
"user_id": 53,
"boxIdentifiant": 1924589682265246,
"boxName": "boxt germany",
"alert_date": "2021-05-30",
"alert_time": "09:40:00",
"alert_description": "Panne batterie",
"alert_level": "danger"
}
之后我创建 ListTile 来显示这些数据,如下所示:
我的目标是如何添加前导背景颜色而不是后退按钮。背景颜色的变化取决于“警报级别”值。 注意:前导只包含背景颜色
alert level = danger ==> background color of leading is red.
alert level = warning ==> background color of leading is yellow.
alert level = normal ==> background color of leading is blue.
我的代码:
if (snapshot.hasData) {
return new ListView.builder(
itemCount: snapshot.data.alerts.length,
itemBuilder: (context, index) {
var boxName = snapshot.data.alerts[index].boxName;
var date = snapshot.data.alerts[index].alertDate;
var description =
snapshot.data.alerts[index].alertDescription;
var alert = snapshot.data.alerts[index].alertLevel;
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
title: Text("$date"),
subtitle: Text("$description"),
trailing: Text("$boxName"),
// leading: BackButton(color: Colors.black),
),
],
),
);
});
}
答案 0 :(得分:2)
像这样:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int colorState = 0;
@override
Widget build(BuildContext context) {
Color color;
switch (colorState) {
case 0:
color = Colors.red;
break;
case 1:
color = Colors.yellow;
break;
case 2:
color = Colors.green;
break;
default:
color = Colors.grey;
}
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: [
ListTile(
title: Text("Data"),
subtitle: Text("Description"),
trailing: Text("BoxName"),
leading: Icon(
Icons.error,
color: color,
),
),
ListTile(
title: Text("Data"),
subtitle: Text("Description"),
trailing: Text("BoxName"),
leading: Container(
color: color,
child: SizedBox(
width: 40,
height: 40,
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => colorState = (colorState + 1) % 3),
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
使用图标还可以通过图标指示警报级别。