Home > Software design >  how to initialize SQLite Database variable in flutter app
how to initialize SQLite Database variable in flutter app

Time:11-07

I'm a beginner in flutter, i want to use SQlite database using sqflite package in my Flutter App, when I declare the_database variable with this syntax static Database _database; , I get a compilation error saying _database must be initialized except I don't know how to initialize it ?

class AnnonceDataBase {

  AnnonceDataBase._();
  static final AnnonceDataBase instance = AnnonceDataBase._();
  static Database _database;

  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await initDB();
    return _database;
  }

  initDB() async {
    WidgetsFlutterBinding.ensureInitialized();
    return await openDatabase(
      join(await getDatabasesPath(), 'annonce_database.db'),
      onCreate: (db, version) {
        return db.execute(
            "CREATE TABLE annonce (id INTEGER PRIMARY KEY, titre Text,prix INTEGER, description TEXT, idAnnonceur INTEGER, active INTEGER)");
      },
      version: 1,
    );
  }
}

CodePudding user response:

I will answer here, because without the code this answer would seem out of context on your other question.

You should replace

static Database _database;

with

static Database? _database;

to mark the static variable as an optional (can be null).

CodePudding user response:

i have a compilation error when i replace static Database _database; by static Database? _database;

class AnnonceDataBase {
  AnnonceDataBase._();
  static final AnnonceDataBase instance = AnnonceDataBase._();
  static Database? _database;
  
  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await initDB();
    return _database;
  }

in the method get database a compilation error return _database: A value of type 'Database?' can't be returned from the function 'database' because it has a return type of 'Future<Database>'.

  • Related