I'm a beginner in Flutter development.
We are currently using Sqflite to deploy Database to the app, and we are trying to build it by referring to the following sites:
Example of a simple SQFlite database on Flutter
Create a Todo app using sqlite on Flutter
However, as flutter has been promoting null safety recently, even if you write the code according to the site you are referring to, it will not be able to deploy it well.
The problem is Database_database
in line 6 of the following code DBProvider
.
The error statement reads Non-nullable instance field'_database'must be initialized.
and I know I should initialize it, but I don't know how to correct the code.
Thank you for your cooperation.
pubspec.yaml
environment:
sdk: ">=2.12.0<3.0.0"
dependencies:
flutter:
sdk —flutter
flutter_localizations:
sdk —flutter
intl —^0.17.0
cupertino_icons —^1.0.2
flutter_riverpod:^0.14.0+3
path_provider —^2.0.2
sqflite —^2.0.0
DBProvider
class DBProvider{
DBProvider._();
static final DBProvider instance=DBProvider._();
Database_database;
Future<Database>get database async {
if(_database!=null)return_database;
_database=wait_initDatabase();
return_database;
}
Future<Database>_initDatabase()async{
Directory documentDirectory=wait getApplicationDocumentsDirectory();
String path=join( documentDirectory.path,_dbName);
return wait openDatabase(
path,
version:_dbVersion,
onCreate:_onCreate,
);
}
Future<void>_onCreate (Database db, int version) async {
wait db.execute(' ''
US>CREATE TABLE$_tableName(
$_Id INTEGER PRIMARY KEY,
$_DateCreatedTEXT NOT NULL,
$_Note TEXT NOT NULL
)''');
}
Future<int>insert(Memo memo) async {
Database db = wait instance.database;
return wait db.insert(_tableName, memo.toMap());
}
....
}
late
late Database_database;
https://dart.dev/null-safety/understanding-null-safety #late-variables
Or nullable
Database?_database;
In this case, I think the database
function should also be modified.
//Modified Example
Future<Database>get database async {
if(_database!=null)return_database!;
_database=wait_initDatabase();
return_database!;
}
© 2024 OneMinuteCode. All rights reserved.