英文:
Flutter Sqflite : null check operator used on a null value
问题
我正在尝试使用Flutter和sqflite创建任务列表应用程序。我的表格已创建并在模拟器上正常显示,但是当我尝试在真实设备上测试我的应用程序时,我在点击"创建任务"按钮后会出现以下错误:在空值上使用了空检查运算符。
请帮助我找到正确的解决方案。
这是我的 db_helper.dart 代码:
我在以下这行代码上遇到了错误: return await _db!.query(_tableName);
class DBHelper {
static Database? _db;
static final int _version = 1;
static final String _tableName = "tasks";
static Future<void> initDb() async {
if (_db != null) {
return;
}
try {
String _path = await getDatabasesPath() + 'tasks.db';
_db =
await openDatabase(_path, version: _version, onCreate: (db, version) {
print("Creating A New One");
return db.execute("CREATE TABLE $_tableName("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"title STRING, note TEXT, date STRING, "
"startTime STRING, endTime STRING, "
"remind INTEGER, repeat STRING, "
"color INTEGER, "
"isCompleted INTEGER)");
});
} catch (e) {
print(e);
}
}
static Future<int> insert(Task? task) async {
print("Insert Function Called");
return await _db?.insert(_tableName, task!.toJson()) ?? 1;
}
static Future<List<Map<String, dynamic>>> query() async {
print("Query Function Called");
return await _db!.query(_tableName); // --> **这里是我遇到错误的地方**
}
}
这是我的 task_controller.dart 代码:
class TaskController extends GetxController {
@override
void onReady() {
super.onReady();
}
var taskList = <Task>[].obs;
Future<int> addTask({Task? task}) async {
return await DBHelper.insert(task);
}
// 从表格获取数据
void getTasks() async {
List<Map<String, dynamic>> tasks = await DBHelper.query();
taskList.assignAll(tasks.map((data) => new Task.fromJson(data)).toList());
}
}
这是我的 home_page.dart 文件的一部分:
_showTasks() {
return Expanded(
child: Obx(() {
return ListView.builder(
itemCount: _taskController.taskList.length,
itemBuilder: (_, index) {
return Container(
width: 100,
height: 50,
color: Colors.green,
margin: const EdgeInsets.only(bottom: 10),
child: Text(
_taskController.taskList[index].title.toString(),
),
);
});
}),
);
}
}
英文:
I am trying to create a Task List app with Flutter and sqflite. My table is created and displays well on an Emulator but as soon I as try to test my app on a real device I get the following error: null check operator used on a null value after I try to to on the create task button.
Please help me with a proper solution.
This is my db_helper.dart Code:
I am getting the error on the Line: return await _db!.query(_tableName);
class DBHelper {
static Database? _db;
static final int _version = 1;
static final String _tableName = "tasks";
static Future<void> initDb() async {
if (_db != null) {
return;
}
try {
String _path = await getDatabasesPath() + 'tasks.db';
_db =
await openDatabase(_path, version: _version, onCreate: (db, version) {
print("Creating A New One");
return db.execute("CREATE TABLE $_tableName("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"title STRING, note TEXT, date STRING, "
"startTime STRING, endTime STRING, "
"remind INTEGER, repeat STRING, "
"color INTEGER, "
"isCompleted INTEGER)");
});
} catch (e) {
print(e);
}
}
static Future<int> insert(Task? task) async {
print("Insert Function Called");
return await _db?.insert(_tableName, task!.toJson()) ?? 1;
}
static Future<List<Map<String, dynamic>>> query() async {
print("Query Function Called");
return await _db!.query(_tableName); --> **This is where I get the error**
}
}
This is my task_controller.dart Code:
class TaskController extends GetxController {
@override
void onReady() {
super.onReady();
}
var taskList = <Task>[].obs;
Future<int> addTask({Task? task}) async {
return await DBHelper.insert(task);
}
// get data from the table
void getTasks() async {
List<Map<String, dynamic>> tasks = await DBHelper.query();
taskList.assignAll(tasks.map((data) => new Task.fromJson(data)).toList());
}
}
This is a part of my home_page.dart file :
_showTasks() {
return Expanded(
child: Obx(() {
return ListView.builder(
itemCount: _taskController.taskList.length,
itemBuilder: (_, index) {
return Container(
width: 100,
height: 50,
color: Colors.green,
margin: const EdgeInsets.only(bottom: 10),
child: Text(
_taskController.taskList[index].title.toString(),
),
);
});
}),
);
}
答案1
得分: 1
你正尝试使用空值检查操作符访问空值。错误发生的原因是在执行 _db!.query(_tableName)
时 _db
为空。
确保在调用查询方法之前初始化 _db
:
static Future<List<Map<String, dynamic>>> query() async {
print("Query Function Called");
if (_db == null) {
await initDb(); // 确保在查询之前初始化数据库
}
return await _db!.query(_tableName);
}
英文:
you are trying to access a null value using the null check operator. the error is occuring because _db is null when you try to execute _db!.query(_tableName)
make sure _db is initialized before calling the query method:
static Future<List<Map<String, dynamic>>> query() async {
print("Query Function Called");
if (_db == null) {
await initDb(); // Ensure the database is initialized before querying
}
return await _db!.query(_tableName);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论