Home > Mobile >  Non-nullable instance field '_database' must be initialized
Non-nullable instance field '_database' must be initialized

Time:10-15

I am trying to use a database form assets folder in my flutter app. I tried this code :

class DatabaseHelper {
  static const _databaseName = "main.db";
  static const _databaseVersion = 1;

  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await _initDatabase(); // only initialize if not created already
    return _database;
  }

  _initDatabase() async {
    String path = join(await getDatabasesPath(), _databaseName);

    if (!(await databaseExists(path))) {
      ByteData data = await rootBundle.load(join("assets", _databaseName));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      await File(path).writeAsBytes(bytes);
    }
    return await openDatabase(path, version: _databaseVersion);
  }
}

But the code is throwning this error at this code DatabaseHelper._privateConstructor(); error: The non-nullable variable '_database' must be initialized. Try adding an initializer expression.

and at this code : static Database _database;

Non-nullable instance field '_database' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.dartnot_initialized_non_nullable_instance_field

i am new to flutter, i don't know what that means... please help me solve this :)

CodePudding user response:

The analyzer is complaining because you have _database as it is right now as non-null because you're using the type Database which means a value is guaranteed to be there... non-null. To make something nullable, which this is, you need to put a ? behind the type e.g. Database?

static Database _database;

should be

static Database? _database;

CodePudding user response:

You can try late keyword

late Database _database;
  • Related