如何修复";不可为null的变量'_db'必须初始化.尝试添加初始值设定项表达式"



"必须初始化不可为null的变量"_db"。尝试添加初始值设定项表达式";有人能帮我解决这个不可为null的错误吗?我正在使用flutter制作一个android应用程序,在使用"sqflite"和制作数据库时,出现了这个错误,我不知道如何真正解决这个问题下面是我的代码,我正在使用Flutter&飞镖

import 'dart:io';
import 'package:newtodoapp/taskmodel.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseHelper {
static final DatabaseHelper instance = DatabaseHelper._instance();
static Database _db;

DatabaseHelper._instance();

String tasksTable = 'task_table';
String colId = 'id';
String colTitle = 'title';
String colDate = 'date';
String colPriority = 'priority';
String colStatus = 'status';
// Task Tables
// Id | Title | Date | Priority | Status
// 0     ''      ''      ''         0
// 2     ''      ''      ''         0
// 3     ''      ''      ''         0
Future<Database> get db async {
if (_db == null) {
_db = await _initDb();
}
return _db;
}
Future<Database> _initDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + '/todo_list.db';
final todoListDb =
await openDatabase(path, version: 1, onCreate: _createDb);
return todoListDb;
}
void _createDb(Database db, int version) async {
await db.execute(
'CREATE TABLE $tasksTable($colId INTEGER PRIMARY KEY AUTOINCREMENT,'
' $colTitle TEXT, $colDate TEXT, $colPriority TEXT, $colStatus INTEGER)',
);
}
Future<List<Map<String, dynamic>>> getTaskMapList() async {
Database db = await this.db;
final List<Map<String, dynamic>> result = await db.query(tasksTable);
return result;
}
Future<List<Task>> getTaskList() async {
final List<Map<String, dynamic>> taskMapList = await getTaskMapList();
final List<Task> taskList = [];
taskMapList.forEach((taskMap) {
taskList.add(Task.fromMap(taskMap));
});
taskList.sort((taskA, taskB) => taskA.date.compareTo(taskB.date));
return taskList;
}
Future<int> insertTask(Task task) async {
Database db = await this.db;
final int result = await db.insert(tasksTable, task.toMap());
return result;
}
Future<int> updateTask(Task task) async {
Database db = await this.db;
final int result = await db.update(
tasksTable,
task.toMap(),
where: '$colId = ?',
whereArgs: [task.id],
);
return result;
}
Future<int> deleteTask(int id) async {
Database db = await this.db;
final int result = await db.delete(
tasksTable,
where: '$colId = ?',
whereArgs: [id],
);
return result;
}
}

这样声明您的变量。

静态数据库_数据库;

相关内容

  • 没有找到相关文章

最新更新