【发布时间】:2019-10-03 18:49:17
【问题描述】:
我是 Flutter 和 Dart 的初学者。
我有一个本地 JSON 文件,阅读它,我想在 ListView 中显示 JSON 数据。 但在我的 JSON 数据中,我并不总是拥有所有不同的属性。 所以当我想显示一个文本时,属性的值是不存在的,因为该属性不存在(在这种情况下是属性“描述”。
我该如何解决?
提前感谢您的帮助
我试过三元运算符 我尝试使用函数 containsKey
但也许我做到了?
... json
[
{
"createdBy": "bddae0de-320c-41a9-a69b-75793758b7a7",
"description": "Fhjifgsdsdsd",
"endDateTime": "1477490400000",
"hasPicture": "false",
"isActive": "true",
"isAdminActive": "true",
"maxParticipants": "50",
"startDateTime": "1476799200000",
"title": "Song Church Story Telling",
"type": "Music"
},
{
"createdBy": "-KHzgxS6KBqu1rNmJzpT",
"endDateTime": "1476378000000",
"hasPicture": "false",
"isActive": "true",
"isAdminActive": "true",
"startDateTime":"1476205200000",
"title": "Test greg T",
"titleDate": "Tuesday, 11 Oct 8:00 PM",
"type": "Games"
}
]
...
...颤抖
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Load local JSON file"),
),
body: new Container(
child: new Center(
// Use future builder and DefaultAssetBundle to load the local JSON file
child: new FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString('assets/data/ckevents_data.json'),
builder: (context, snapshot) {
// Decode the JSON
var newData = json.decode(snapshot.data.toString());
return new ListView.builder(
// Build the ListView
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Text("Title: " + newData[index]['title'],
style: new TextStyle(
fontSize: 20.0, color: Colors.blue)),
new Text(
"Description: " +
((newData[index].containsKey('description')) ? ('') : (newData[index]['description'])),
style: new TextStyle(
fontSize: 10.0, color: Colors.pink)),
new Text("Categorie: " + newData[index]['type'],
style: new TextStyle(
fontSize: 15.0, color: Colors.red)),
new Text(
"Date: " +
DateTime.fromMillisecondsSinceEpoch(
newData[index]['startDateTime'])
.add(Duration(days: 700))
.toString(),
style: new TextStyle(
fontSize: 10.0, color: Colors.black))
],
),
);
},
itemCount: newData == null ? 0 : newData.length,
);
}),
),
));
}
}
...
【问题讨论】:
标签: json listview dart flutter listviewitem