I created a class for database operations, when i trigger the function of insert to data base to print occurs with this error: Unhandled Exception: Null check operator used on a null value E/flutter (28057): #0 DBHelper._createDB, also there is no print occures once initialize an object of DBHelper
. i think null-able _db object is the reason. what is the solution?
database class:
class DBHelper {
DBHelper._();
factory DBHelper() => instance;
static final DBHelper instance = DBHelper._();
Database? _db;
Future<Database> _createDB() async {
// If the app is opened just now
if (_db == null) return _db!;
// Open db too create a db
// or to take an instance of it
// Get the default databases location.
// and join the name of app db
String path = join(await getDatabasesPath(), 'todo.db');
return _db = await openDatabase(path, version: 1,
onCreate: (Database database, int version) {
database.execute(
"CREATE TABLE tasks(id integer autoincrement PRIMARY KEY,content varchar(150),status varchar(9),isFinished BOOLEAN) ");
print("\n TABLE executed \n");
}, onOpen: (_) {
print("\n opened \n ");
});
}
Future<int> insertNoteToDB(NoteDatabaseModel noteDatabaseModel) async {
Database _database = await _createDB();
return await _database.rawInsert(
'INSERT INTO tasks(content,status) values("${noteDatabaseModel.content}", "today")');
// return await _database!.insert('tasks', noteDatabaseModel.toJason());
}
}
the implementation of sql:
class TodayPage extends StatelessWidget {
const TodayPage();
@override
Widget build(BuildContext context) {
DBHelper dbHelper=DBHelper();
return MaterialButton(
onPressed: () async{
// DBHelper _db = DBHelper.instance;
NoteDatabaseModel note=NoteDatabaseModel(content: "hey",status: "today");
int x= await dbHelper.
insertNodeToDB(note);
print("\n print all Data ${ await dbHelper.
insertNodeToDB(note)}\n");
},
child: const Text("Click Me"),
),
),
],
);
}
}
CodePudding user response:
What do you think this line does:
if (_db == null) return _db!;
If I would have to guess, I'd say it should be:
if (_db != null) return _db;