You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter SQFlite CRUD列表项显示Null及类型转换错误问题排查求助

解决Flutter SQFlite ListTile显示Null的问题

我仔细检查了你的代码,问题根源在于数据库字段名与ListTile中使用的取值键不匹配,再加上一处更新操作的参数顺序错误,导致数据无法正确读取显示。下面一步步帮你修复:

1. ListTile使用了错误的字段键

你在main.dart的ListTile里用了带空格的键名:

subtitle: Text(_contacts[index]['Phone Number'].toString()),
title: Text(_contacts[index]['First Name '].toString() + _contacts[index]['Last Name'].toString())

但你的SQFlite数据库表items里的字段名是全小写无空格的:firstname、lastname、phonenumber。用不匹配的键取值自然返回Null。

修正代码:

subtitle: Text(_contacts[index]['phonenumber'].toString()),
title: Text('${_contacts[index]['firstname']} ${_contacts[index]['lastname']}', 
  style: const TextStyle(
    fontWeight: FontWeight.bold,
    fontSize: 20,
    color: Color(0xFFFFFFFF))),

2. 更新操作的参数顺序错误

在main.dart的_updateItem方法中,你调用SQLHelper.updateItem的参数顺序和方法定义不匹配:

// 错误的顺序:address和phonenumber位置颠倒
await SQLHelper.updateItem(
 id,
 _firstnameController.text,
 _lastnameController.text,
 _addressController.text,_phonenumberController.text,_emailController.text,_dobController.text);

而SQLHelper的updateItem方法定义的参数顺序是:id, firstname, lstname, phonenumber, address, email, dob,顺序错误会导致数据存错字段,后续读取自然异常。

修正代码:

await SQLHelper.updateItem(
 id,
 _firstnameController.text,
 _lastnameController.text,
 _phonenumberController.text, // 先传电话号码
 _addressController.text,     // 再传地址
 _emailController.text,
 _dobController.text);

3. 可选字段的Null安全优化

为了彻底避免type 'Null' is not a subtype of type 'String'异常,建议给可能为空的字段添加空值兜底处理:

subtitle: Text(_contacts[index]['phonenumber'] ?? '无电话号码'),
title: Text('${_contacts[index]['firstname'] ?? ''} ${_contacts[index]['lastname'] ?? ''}', 
  style: const TextStyle(
    fontWeight: FontWeight.bold,
    fontSize: 20,
    color: Color(0xFFFFFFFF))),

这样即使某个字段未赋值,也会显示友好的默认文本而不是抛出异常。

完成以上修改后,重新运行App,添加/更新联系人后,ListTile就能正确显示数据库中的数据,不再出现Null的情况了。

内容的提问来源于stack exchange,提问作者Kei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:13:17