使用Flutter接收器获取数据:空错误

时间:2019-10-15 16:10:32

标签: json flutter dart fetch flutter-layout

我尝试获取api json,这是链接https://api.myjson.com/bins/ut9kq 当我在循环之前打印输出时,它确实获取了数据,但在列表之后却给了我错误

”未处理的异常:NoSuchMethodError:在null上调用了吸气剂“图像”。 E / flutter(30730):接收者:null E / flutter(30730):尝试致电:图片”

这是我的代码

    List lists;

    Future<List> getLists() async {
      lists = new List();
      await api.httpGet('bins/ut9kq').then((reponse) {
        var data = jsonDecode(reponse.body);
        print(data); // i get the json data => [{},{}..]
        data.forEach((l) {
          lists.add(ArticleModal().fromJson(l));
        });
        // print(lists[0].image);//Receiver: null
      });
      return lists;
    }

2 个答案:

答案 0 :(得分:1)

您正在使用两种方法来进行将来的处理:.then回调以及async和await。尝试以下操作,您可以将它们包装在try / catch块中以进行错误处理。

Future<List<ArticleModal>> getLists() async {
  lists = new List();

  var response = await http.get('bins/ut9kq');

  // a switch may be used for a wider range of codes
  if (response.statusCode == 200) {
    var decodedResponse = json.decode(response.body);
    print(decodedResponse);
    //if response is a collection
    var listAricleModal = (decodedResponse as List).map((collectionElement) => ArticleModal.fromJson(collectionElement)).toList();
    return listAricleModal;
  }
  //Your future is an empty collection
  return [];
}

为正确回答您的问题,在空值上调用image是很明显的消息。 在某个时候,您有一个image字段,该对象未创建。可能是列表中的对象,所以可能会发生两件事:

  • 列表为空,因此没有可调用的图片。
  • 从Json呼叫时出现问题。

无论哪种方式,都可以使用调试器并在每个方法的第一行上设置断点,以清楚地了解正在发生的事情。 如果map函数难以调试,请使用普通的for循环,直到知道错误在哪里。

从Google观看此系列视频。 https://youtu.be/vl_AaCgudcY

也是官方文档:https://dart.dev/codelabs/async-await

答案 1 :(得分:-1)

很好,谢谢大家的帮助,看来我只是忘了在“ fromJson”方法中添加return了

ArticleModal fromJson(Map<String, dynamic> json) {
    "should be return here " ArticleModal(
        title: json['title'],
        image: json['image'],
        date: json['date'],
        author: json['author'],
        body: json['body'],
        imageAuthor: json['imageAuthor']);
  }