[Flutter]未处理的异常:NoSuchMethodError:方法'[]'被调用为空

时间:2020-01-07 13:52:44

标签: android json flutter

class Resistencia100{
  int id;
  double r_pos1;
  double r_pos2;
  double r_pos3;
  double r_pos4;
  double r_pos5;

  Resistencia100({
    this.id, this.r_pos1, this.r_pos2, this.r_pos3, this.r_pos4,
    this.r_pos5
    });

  Map<String, dynamic> toMap() => {
    "id": id,
    "r_pos1": r_pos1,
    "r_pos2": r_pos2,
    "r_pos3": r_pos3,
    "r_pos4": r_pos4,
    "r_pos5": r_pos5,

  };
  factory Resistencia100.fromMap(Map<String, dynamic> json) => new Resistencia100(
    id:     json["id"],
    r_pos1: json["r_pos1"],
    r_pos2: json["r_pos2"],
    r_pos3: json["r_pos3"],
    r_pos4: json["r_pos4"],
    r_pos5: json["r_pos5"],
  );

}

这是我的Model类Resistencia100,现在我们将看到如何通过get方法请求数据

  Future<List<Resistencia100>> getAllResistencia100() async {
    final db = await database;
    var response = await db.query("Resistencia100");
    List<Resistencia100> list = response.map((c) => Resistencia100.fromMap(c)).toList();
    print("Cantidad ID: "+list[0].id.toString());
    print("Cantidad r_pos1: "+list[0].r_pos1.toString());
    print("Cantidad r_pos2: "+list[0].r_pos2.toString());
    print("Cantidad r_pos3: "+list[0].r_pos3.toString());
    print("Cantidad r_pos4: "+list[0].r_pos4.toString());
    print("Cantidad r_pos5: "+list[0].r_pos5.toString());
    return list;
  }

信息正确地传递到方法中,现在我尝试提取该信息,并且错误即将出现。


List <Resistencia100> resistencia100 = new List<Resistencia100>();

Future<List<Resistencia100>> getResistencia100() async {
    await ClientDatabaseProvider.db.getAllResistencia100();
  }

  void validate() async {

    resistencia100 = await getResistencia100();

    print("RESISTENCIA ID: "+resistencia100[0].id.toString());


  }

事实是我不太了解错误的原因,希望您能理解,我将在以下几行中留下文本错误,这是在“打印”中生成的。

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: [](0)
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _ConfigConcretoState.validate (package:entremuros/vistas/configconcreto.dart:282:44)

1 个答案:

答案 0 :(得分:1)

您的方法getResistencia100()未返回任何内容。因此,在validate(),您的变量resistencia100在等待getResistencia100()

之后将转换为null

一种解决方案是更改getResistencia100(),添加一条return语句

Future<List<Resistencia100>> getResistencia100() async {
    return await ClientDatabaseProvider.db.getAllResistencia100();
}