Home > Software engineering >  Flutter Error when creating SQL DB table by giving tableName parameter
Flutter Error when creating SQL DB table by giving tableName parameter

Time:04-22

I found a flutter sqfl example on the web and trying to modify it for my personal project.

I need more than one table in a database, so I want to be able to create different tables by giving tableName parameters at runtime.

When I tried to add tableName as a parameter in '_onCreate' method for table creation I got an error that warns me that "The argument type 'Future Function(Database, int, String)' can't be assigned to the parameter type 'FutureOr Function(Database, int)?'."

// this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    String path = join(await getDatabasesPath(), _databaseName);
    return await openDatabase(path,
        version: _databaseVersion, onCreate: _onCreate);
  }

  // SQL code to create the database table
  Future _onCreate(Database db, int version, String tableName) async {
    await db.execute('''
          CREATE TABLE $tableName (
            $columnId INTEGER PRIMARY KEY AUTOINCREMENT,
            $columnName TEXT NOT NULL,
            $columnMiles INTEGER NOT NULL
          )
          ''');
  }

CodePudding user response:

You can create your queries separately and then execute all at a same time like the following

queryForFirstTable = 'CREATE TABLE TABLENAME(your properties here)';
queryForSecondTable= 'CREATE TABLE ANOTHERTABLENAME(your properties here)';
 await openDatabase(
        join(await getDatabasesPath(), dbName),
        version: 1, onCreate: (Database db, int version) async {
      await db.execute(queryForFirstTable);
      await db.execute(queryForSecondTable);
    });

Hopefully by doing this you can easily create multiple tables.

CodePudding user response:

     void _createDb(Database db, int newVersion) async {
 await db.execute('''
   create table $carTable (
    $columnCarId integer primary key autoincrement,
    $columnCarTitle text not null
   )''');
 await db.execute('''
   create table $userTable(
    $userId integer primary key autoincrement,
    $name text not null
   )''');
  }

For creating multiple tables at a time.

  • Related