Flutter中SQFlite数据库插入报错:toMap()调用于空对象
解决Flutter中SQFlite插入时的NoSuchMethodError: The method 'toMap' was called on null
这个错误的根源非常清晰:你在调用insertNote(note)时,传入的note对象是未初始化的null值,导致执行instructor.toMap()时触发了空指针异常。
看你的_MyHomePageState代码,你只声明了Instructor note;,但从来没有给这个变量赋值,点击登录按钮时直接传递了这个null对象,自然会报错。
修复步骤
- 在按钮点击回调中,先从输入框获取用户输入的内容
- 创建一个有效的
Instructor实例,把输入值赋值给它 - 再将这个实例传入
insertNote方法
修改后的Main类按钮点击代码
RaisedButton( child: Text('Login'), onPressed: () async { // 获取输入框的内容,记得trim去除首尾空格 String inputName = nameController.text.trim(); String inputPass = passController.text.trim(); // 创建有效的Instructor实例(根据你的Instructor类构造函数调整参数) Instructor newInstructor = Instructor( name: inputName, password: inputPass, // 如果id是自增字段,这里可以传null或者不写,取决于你的构造函数定义 ); // 调用插入方法,别忘了await异步操作 int insertResult = await _databaseHelper.insertNote(newInstructor); // 可选:打印结果或者给用户反馈 print('插入数据库成功,返回ID:$insertResult'); })
额外检查
确保你的Instructor类已经正确实现了toMap()方法,比如:
class Instructor { int id; String name; String password; Instructor({this.id, this.name, this.password}); // 将对象转换为SQFlite需要的Map格式 Map<String, dynamic> toMap() { final map = <String, dynamic>{ 'name': name, 'password': password, }; // 如果id不为空(比如更新操作时),再加入map if (id != null) { map['id'] = id; } return map; } }
这样修改后,你点击登录按钮时就会传入一个有效的Instructor对象,toMap()方法就能正常执行,不会再触发空指针错误了。
内容的提问来源于stack exchange,提问作者Muhammad Ali Nizami
相关产品推荐
相关产品推荐

