Update method with flutter and sqlite generating error

Asked

Viewed 54 times

0

Good morning, I am updating to sqlite with Flutter and am having the following error:

NoSuchMethodError: The method 'update' was called on null.

I built the code according to the documentation where I receive a Model and make a map of the appropriate fields.

Future<void> updateCategoria(CategoriasModel categoriasModels) async {
  try {
   await db.update('categoria', categoriasModels.toMap(),
      where: "id = ?", whereArgs: [categoriasModels.id]);
   } catch (error) {
    print(error.toString());
  }
 }

and the model:

class CategoriasModel with ChangeNotifier {
  final int id;
  final String descricao;
  final int isReceita;

  CategoriasModel({
    this.id,
    this.descricao,
    this.isReceita,
  });

  Map<String, dynamic> toMap() {
    return {'id': id, 'descricao': descricao, 'isReceita': isReceita};
 }
}

other CRUD function are working normally.

  • 2

    By the message the error is in your database instance. At what point do you initialize it? It is null and calling the method "update".

  • I really forgot to boot. Thanks my friend.

  • I will post as reply to leave registered for other dev’s

1 answer

3


The problem is occurring because the database was not initialized and has the value nulo. With that the method update cannot be used. The solution is to initialize the db before the method call update.

Example

Future<void> updateCategoria(CategoriasModel categoriasModels) async {
  try {
   // Inicialização do Database de exemplo (essa abordagem do exemplo
   // segue a implementação de utilizar um Helper Singleton, não é regra
   // e depende de como o projeto está trabalhando).
   final db = await DbHelper.getInstance().db;

   await db.update('categoria', categoriasModels.toMap(),
      where: "id = ?", whereArgs: [categoriasModels.id]);
   } catch (error) {
    print(error.toString());
  }
 }
  • If possible give an example of how to initialize database, to make your reply more complete.

  • 2

    I believe that the initialization depends on how he implemented the code. I do not see it correct to induce an interpretation of myself to the occasion even more than he mentioned in the comment that he forgot to initialize and the other methods are working correctly. Anyway I will put a generic example just for reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.