trovap
trovap

Reputation: 81

Flutter Sqflite Update

i need some newbie help.

I'm trying to update a column of a db, but i can't think haha...

I have a controller where i put my methods, and a helper to db.

Part of the helper:

    static Future<void> initDb() async {
    if (_db != null) {
      return;
    }
    try {
      String _path = await getDatabasesPath() + 'cities.db';
      _db = await openDatabase(
        _path,
        version: _version,
        onCreate: (db, version) {
          return db.execute(
            "CREATE TABLE $_tableName("
            "id INTEGER PRIMARY KEY AUTOINCREMENT, "
            "name STRING, code STRING, "
            "startDate STRING, startTime STRING, "
            "endDate STRING, endTime STRING, "
            "color INTEGER, isCompleted INTEGER)",
          );
        },
      );
    } catch (e) {
      print(e);
    }
  }

    static updateStatus(int id) async {
        return await _db!.rawUpdate('''
          UPDATE cities
          SET color = ?
          WHERE id = ?
        ''', [1, id]);
      }

In the controller i have the method:

void markColor(int id) async {
    await DBHelper.updateStatus(id);
    getCities();
  }

Somewhere in the app I want to update the String code like the markColor method, based on a textEditingController of the screen... I tried a thousand different forms of do it and none of them work, can someone help?

Upvotes: 1

Views: 293

Answers (1)

Vandad Nahavandipoor
Vandad Nahavandipoor

Reputation: 1574

Update in SQFlite in Flutter is usually done through the update function itself as shown here:

final updateCount = await db.update(
  'PEOPLE',
  {
    'FIRST_NAME': person.firstName,
    'LAST_NAME': person.lastName,
  },
  where: 'ID = ?',
  whereArgs: [person.id],
);
  1. The first parameter PEOPLE in this code is the name of the table that you want to update.
  2. The second parameter is a map of keys and values, where the keys are the names of the columns you want to update, in this case 'FIRST_NAME' and 'LAST_NAME' and their values are the values to update.
  3. The third parameter where defines which rows to update, in this case, only rows whose ID column is equal to a value that you set in the next step.
  4. The fourth parameter whereArgs is a list of arguments that you are using in your where argument.

Upvotes: 2

Related Questions