You need to enable JavaScript to run this app. 如何在Flutter的fetchNotes方法中过滤指定ID的JSON结果
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的fetchNotes方法中过滤指定ID的JSON结果

实现方案

你可以通过以下两种方式在fetchNotes()方法中过滤出id为XPTO68的数据:

方案1:遍历JSON时直接过滤

在遍历原始JSON数组的环节新增id校验,仅符合要求的条目才会被转换为Note对象加入返回列表:

Future<List<Note>> fetchNotes() async {
    var data = await DefaultAssetBundle.of(context)
        .loadString('assets/json/produtos.json');
    var body = json.decode(data);
    var notes = List<Note>();
    for (var noteJson in body) {
      if(noteJson['id'] == 'XPTO68'){
        notes.add(Note.fromJson(noteJson));
      }
    }
    return notes;   
}

方案2:转换为Note列表后过滤

先完成所有JSON到Note对象的转换,再用where方法过滤符合条件的条目,写法更简洁:

Future<List<Note>> fetchNotes() async {
    var data = await DefaultAssetBundle.of(context)
        .loadString('assets/json/produtos.json');
    var body = json.decode(data);
    return body.map((noteJson) => Note.fromJson(noteJson))
               .where((note) => note.id == 'XPTO68')
               .toList();
}

注意:如果使用方案2,请确保你的Note类中已经定义了id属性,且Note.fromJson方法已经完成了id字段的解析赋值。

内容的提问来源于stack exchange,提问作者Celso Spina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 13:45:04