static DatabaseHelper? _databaseHelper;

  DatabaseHelper._craeteInstance();

    factory DatabaseHelper(){
    if(_databaseHelper == null){
      _databaseHelper = DatabaseHelper._craeteInstance();
    }
    return _databaseHelper;
  }

currently, I cant return _databaseHelper because this function can only return DatabaseHelper value instead of DatabaseHelper? I tried to change _databasehelper form DatabaseHelper? to DatabaseHelper, but in that way, the first two lines is errored, because the _databaseHelper must be initialized. what should I do to make both sides right?

2

There are 2 best solutions below

0
On

No need to check for null, just create your singleton once and return it.

class DatabaseHelper {
  static final DatabaseHelper _databaseHelper = DatabaseHelper._createInstance();

  DatabaseHelper._createInstance();

  factory DatabaseHelper(){
    return _databaseHelper;
  }
}
1
On

you can also add 'late' keyword.

static late DatabaseHelper _databaseHelper;

DatabaseHelper._craeteInstance();

factory DatabaseHelper(){
if(_databaseHelper == null){
  _databaseHelper = DatabaseHelper._craeteInstance();
}
return _databaseHelper;

}