Search code examples
fluttersqflite

How to Update a row in Flutter with SQFlite


I try to update a row, but nothing happens, I don't know what I have missed. Could some please check what I have done wrong ?

This is my helper class.

class DBHelper {
 static Future<sql.Database> database() async {
   final dbPath = await sql.getDatabasesPath();

   //einmal die Datenbank erstellen in einer Variablen
   return sql.openDatabase(path.join(dbPath, 'wanderwege.db'),
       onCreate: (db, version) {
     return db.execute(
         'CREATE TABLE user_places(id TEXT PRIMARY KEY, title TEXT, image TEXT, createTime TEXT, place TEXT, description TEXT)');
     // 'CREATE TABLE user_places(id TEXT PRIMARY KEY, title TEXT, image TEXT, loc_lat REAL, loc_lng REAL, address TEXT)');
   }, version: 1);
 }

 static Future<void> insert(String table, Map<String, Object> data) async {
   final db = await DBHelper.database();

   db.insert(table, data, conflictAlgorithm: sql.ConflictAlgorithm.replace);
 }

 //Delete data from table
 static Future<void> delete(String id) async {
   final db = await DBHelper.database();
   var res = await db.delete('user_places', where: "id = ?", whereArgs: [id]);
   return res;
 }
 //Update Data
 static Future<void> updateData(String title) async {
   final db = await DBHelper.database();
   int res =
       await db.rawUpdate('UPDATE user_places SET title = ? WHERE id = ?');
   return res;
 }
}

And on my Edit_Screen I used this, first I just wanted to try to update the title, with the new value from _titleController.text

   //Update für die jeweiligen einträge zu Kontrollieren
   checkupdate() {
     if (_titleController.text.isEmpty) {
       var errorMessage = 'Bitte gib einen Titel ein';
       return _showErrorDialog(errorMessage);
     }
    
     DBHelper.updateData(_titleController.text);
  
     print(DBHelper.updateData(_titleController.text));

     Navigator.of(context).pop();
   }

But nothing happen, I dont now where exactly I have done the misstake.

Thanks for the help :)


Solution

  • I assume you miss update arguments in rawUpdate query.

     //Update Data
     static Future<void> updateData(String title, String id) async {
       final db = await DBHelper.database();
       int res =
           await db.rawUpdate('UPDATE user_places SET title = ? WHERE id = ?', [title, id]);
       return res;
     }
    

    Refer rawUpdate example here: https://pub.dev/packages/sqflite