如何在Flutter ListView构建期间测试json属性是否存在

时间:2019-05-16 13:12:03

标签: json listview dart flutter listviewitem

我是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,
                  );
                }),
          ),
        ));
  }
}

...

2 个答案:

答案 0 :(得分:0)

您可以使用null合并运算符,如下所示:

 new Text("Description: " + newData[index]['description'] ?? ''),

这将打印描述(如果存在),如果不存在则为空字符串。

答案 1 :(得分:0)

尝试这种方式 1.以这种方式为您的响应json创建模型类。

class UserData {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;

UserData({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

factory UserData.fromJson(Map<String, dynamic> json) {
return new UserData(
    albumId: json['albumId'],
    id: json['id'],
    title: json['title'],
    url: json['url'],
    thumbnailUrl: json['thumbnailUrl']);
}
}

现在使列表对象..

  List<UserData> list = List();

然后添加数据。

list = (json.decode(response.body) as List)
      .map((data) => UserData.fromJson(data))
      .toList();

以这种方式读取json文件。

class _ApiCallScreenState extends State<ApiCallScreen> {
@override
void initState() {
String data = await  DefaultAssetBundle.of(context).loadString("assets/data.json");
 list = (json.decode(data) as List)
  .map((data) => UserData.fromJson(data))
  .toList();
super.initState();
}