Search code examples
sqliteflutterdartsqflite

No such table error when accessing SQLite with Flutter SQFlite


I am creating my first Flutter project with SQLite. It is a shopping list app. This is the utility class that makes the database call:

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DbHelper {
  final int version = 1;
  Database db;

  Future testDb() async {
    db = await openDb();
    await db.execute('INSERT or IGNORE INTO lists VALUES (0, "Fruit", 2)');
    await db.execute(
        'INSERT or IGNORE INTO items VALUES (0, 0, "Apples", "2 Kg", "Better if they are green")');
    List lists = await db.rawQuery('select * from lists');
    List items = await db.rawQuery('select * from items');
    print(lists[0].toString());
    print(items[0].toString());
  }

  Future<Database> openDb() async {
    if (db == null) {
      db = await openDatabase(join(await getDatabasesPath(), 'shopping.db'),
          onCreate: (database, version) {
            database.execute(
                'CREATE TABLE lists(id INTEGER PRIMARY KEY, name TEXT, priority INTEGER)');
            database.execute(
                'CREATE TABLE items(id INTEGER PRIMARY KEY, idList INTEGER, name TEXT, quantity TEXT, note TEXT, ' +
                    'FOREIGN KEY(idList) REFERENCES lists(id))');
          }, version: version);
    }
    return db;
  }
}

And this is my main Flutter widget:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    DbHelper dbHelper = DbHelper();
    dbHelper.testDb();

    return MaterialApp(
      title: appTitle,
      theme: ThemeData(
        primarySwatch: Colors.indigo
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
          centerTitle: false,
        ),
      )
    );
  }
}

As soon as I run the app, I get this message:

[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: DatabaseException(Error Domain=FMDatabase Code=1 "no such table: items" UserInfo={NSLocalizedDescription=no such table: items}) sql 'INSERT or IGNORE INTO items VALUES (0, 0, "Apples", "2 Kg", "Better if they are green")' args []}
#0      wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7)
<asynchronous suspension>

I don't understand what is causing this error to happen. It is obvious that I have created a table called items, so I can't figure out why there is no such table.

I am using the following versions of sqflite. I have also tried to upgrade them but the error persists

  sqflite: ^1.2.0
  path: ^1.6.4

I have read many similar StackOverflow questions before but have been unable to find an answer so far.


Solution

  • From the documentation at https://pub.dev/packages/sqflite

    Database database = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      // When creating the db, create the table
      await db.execute(
          'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
    });
    

    db.execute is async so you'll need to await for it and onCreate should be defined as awaitable too.