未处理的异常:NoSuchMethodError:在null上调用了getter'id'。在Flutter

时间:2020-08-10 03:47:58

标签: flutter dart floor

我试图在用户每次插入或更新数据时显示所有插入的数据,但是在开发过程中我遇到了此错误“未处理的异常:NoSuchMethodError:将getter'id'调用为null。” 任何建议将不胜感激。

这是我的代码

    saveContactData() {
    final database = $FloorContactDatabase.databaseBuilder('Contacts.db').build();
    database.then((onValue) {
      onValue.contactsDao.getMaxTodo().then((isvalue) {
        int id = 1;
        if(onValue != null) {
          print(onValue);
          id = isvalue.id + 1; //MY ERROR IS HERE
        }
          onValue.contactsDao.insertContact(ContactObject(id: id,
              firstname: firstnameController.text,
              lastname: lastnameController.text,
              birthday: int.parse(firstnameController.text.trim()),
              contactnumber: int.parse(contactnumberController.text.trim()),
              profilepicture: Image.file(_image).toString()
          ));


      });
    });
  }

这是我的回购电话,我叫ID

    @entity
class ContactObject {
    @PrimaryKey(autoGenerate: true)
    int id;
    String firstname;
    String lastname;
    int birthday;
    int contactnumber;
    String profilepicture;

    @ignore
    bool isSelect = false;
    ContactObject ({this.id , this.firstname, this.lastname, this.birthday, this.contactnumber, this.profilepicture});//need to change if needed

    @override
    String toString(){
      return 'ContactObject{id: $id, firstname: $firstname, lastname: $lastname, birthday: $birthday, contactnumber: $contactnumber, profilepicture: $profilepicture}';
    }

    static ContactObject formMap(Map<String, dynamic> extend) {
        if(extend == null) return null;
          ContactObject contacts = ContactObject();
          contacts.id = extend['id'];
          contacts.firstname = extend['firstname'];
          contacts.lastname = extend['lastname'];
          contacts.birthday = extend['birthday'];
          contacts.contactnumber = extend['contactnumber'];
          contacts.profilepicture = extend['profilepicture'];
          return contacts;
    }

  Map<String, dynamic> toMap(){
      return{
        "id": id,
        "firstname": firstname,
        "lastname": lastname,
        "birthday": birthday,
        "contactnumber": contactnumber,
        "profilepicture" : profilepicture
      };
  }

}

这是我在数据库中的查询

`@override
  Future<ContactObject> getMaxTodo() {
    return _queryAdapter.query('SELECT * FROM ContactObject order by id desc limit 1',
        mapper: _todoMapper);
  }
`

1 个答案:

答案 0 :(得分:0)

只需使用dart null避免运算符

if(onValue != null) {
    print(onValue);
    id = isvalue?.id??0 + 1; 
}

在上面的代码中,isvaluenull,然后id首先退回到0,最后得到1