Home > Mobile >  The non-nullable variable '_db' must be initialized. Try adding an initializer expression
The non-nullable variable '_db' must be initialized. Try adding an initializer expression

Time:01-02

I'm using flutter to develop my mobile apps and in my database has an error that i can't solve it `

import 'package:fitness_app/Login/login_data.dart';
import 'package:fitness_app/user.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:io' as io;

class DbHelper {
  static Database _db;

  static const String DB_Name = 'test.db';
  static const String Table_User = 'user';
  static const int Version = 1;

  static const String C_UserID = 'user_id';
  static const String C_UserName = 'user_name';
  static const String C_Email = 'email';
  static const String C_Password = 'password';

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();
    return _db;
  }

  initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, DB_Name);
    var db = await openDatabase(path, version: Version, onCreate: _onCreate);
    return db;
  }

  _onCreate(Database db, int intVersion) async {
    await db.execute("CREATE TABLE $Table_User ("
        " $C_UserID TEXT, "
        " $C_UserName TEXT, "
        " $C_Email TEXT,"
        " $C_Password TEXT, "
        " PRIMARY KEY ($C_UserID)"
        ")");
  }

  Future<int> saveData(UserModel user) async {
    var dbClient = await db;
    var res = await dbClient.insert(Table_User, user.toMap());
    return res;
  }

  Future<UserModel?> getLoginUser(String userId, String password) async {
    var dbClient = await db;
    var res = await dbClient.rawQuery("SELECT * FROM $Table_User WHERE "
        "$C_UserID = '$userId' AND "
        "$C_Password = '$password'");

    if (res.length > 0) {
      return UserModel.fromMap(res.first);
    }

    return null;
  }

  Future<int> updateUser(UserModel user) async {
    var dbClient = await db;
    var res = await dbClient.update(Table_User, user.toMap(),
        where: '$C_UserID = ?', whereArgs: [user.user_id]);
    return res;
  }

  Future<int> deleteUser(String user_id) async {
    var dbClient = await db;
    var res = await dbClient
        .delete(Table_User, where: '$C_UserID = ?', whereArgs: [user_id]);
    return res;
  }
}

` This is the code i use for the databasehelper and it shows error in _database like this: The non-nullable variable '_db' must be initialized. Try adding an initializer expression

enter image description here

Can anyone help me to solve this problem, thank you

CodePudding user response:

What you have here, is a static variable

static Database _db;

It is of type Database, so it must not be null. But you only set a value for it using initDb(), which is called after your initializer. That's too late for the compiler, so it throws an error.

So what you can do is to make the variable nullable.

Change the above line to

static Database? _db;

Then your line if (_db != null) will also make sense, because it checks for nullability which was not possible before

You can also adjust the other methods to adress this change

Future<Database> get db async {
    if (_db != null) {
      return _db!; // ! force-unwraps the optional
    }
    _db = await initDb();
    return _db!; // ! force-unwraps the optional. This assumes your initDb() always returns an actual value
  }
  • Related