Home > database >  LateInitializationError: Field '_database@29391942' has not been initialized
LateInitializationError: Field '_database@29391942' has not been initialized

Time:01-03

I have a Flutter application that Inserts data into a databass. And It gets and displays data from the database.

But I got a *Late Initialization Error.

I think the cause is in >
static late Database _database;

Error :

E/flutter ( 6700): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: 
LateInitializationError: Field '_database@29391942' has not been initialized.

Code:

class ProductDBHelper{

  static final _databaseName = 'mydb.db';
  static final _databaseVersion = 1;


  static final _table_products = 'products';
  static late String path;

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

  static late Database _database;


  //// Check whether the database created or not.
  Future get database async{

    if(_database != null) return _database;

    _database = await _initDatabase();
    print('Database : $_database');
    return _database;
    
  }
  //// Initialise database with local file path , db name.
  _initDatabase() async{
    
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    //// localstorage path/databasename.db
    String path = join(documentDirectory.path , _databaseName);
    return await openDatabase(
      path,
      version: _databaseVersion,
      onCreate: _onCreate);

  }
  //// on Create for creating database.
  Future _onCreate(Database db, int version) async{

    await db.execute('CREATE TABLE $_table_products(id INTEGER PRIMARY KEY autoincrement, name TEXT, price TEXT, quantity INTEGER)');
  }

  static Future getFileData(){
    return getDatabasesPath().then((value)
    {
      return path = value;
    }
    );
  }

  Future insertProduct(Product product) async{

    Database db = await instance.database;
    return await db.insert(
        _table_products, Product.toMap(product),
        conflictAlgorithm: ConflictAlgorithm.ignore
    );
  }

Can Anyone advice me for solving this error ?

CodePudding user response:

While you are doing null check,

    if(_database != null) return _database;

you need to make datatype as nullable, replace

  static late Database _database;

with

  static  Database? _database;
  • Related