Flutter问题:无法从数据库方法获取返回数据及行数如何解决?
问题解决方案
核心问题分析
你的代码存在三个关键错误,导致无法正确获取数据库行数:
- 模型类构造函数拼写错误,
TESTTypeModel和类名TestTypeModel大小写不一致,无法正确实例化。 fromJson方法语法错误,使用了冒号而非赋值语句,导致属性无法被正确赋值。- 数据库查询返回的键是
COUNT(id),但模型中期望的是id,二者不匹配,无法读取统计值;同时返回实体类的设计不适合获取行数的场景。
修正后的代码
1. 修复 test_type_model.dart
class TestTypeModel { int? id; String? testTitle; // 修正构造函数名拼写错误 TestTypeModel({ this.id, this.testTitle, }); // 修正fromJson的赋值逻辑,正确映射字段 TestTypeModel.fromJson(Map<String, dynamic> json) : id = json['id'], testTitle = json['test_title']; Map<String, dynamic> toJson() { return { 'id': id, 'testTitle': testTitle, }; } }
2. 重构 databaseHelper.dart
新增专门获取行数的方法,直接返回int类型,更适配ListView.builder的itemCount参数:
class DataBaseHelper { late Database database; // 获取test_type表的总行数,直接返回int Future<int> getTestTypeCount() async { final db = await database; // 给统计结果取别名`total_count`,方便取值 final maps = await db.rawQuery('SELECT COUNT(id) AS total_count FROM test_type'); // 用Sqflite工具方法直接提取int值,为空则返回0 return Sqflite.firstIntValue(maps) ?? 0; } // 可选:获取完整的TestTypeModel列表(用于列表内容展示) Future<List<TestTypeModel>> getTestTypeList() async { final db = await database; final List<Map<String, dynamic>> maps = await db.query('test_type'); return List.generate(maps.length, (i) => TestTypeModel.fromJson(maps[i])); } }
在ListView中使用
结合FutureBuilder异步获取行数并渲染列表:
FutureBuilder<int>( future: DataBaseHelper().getTestTypeCount(), builder: (context, snapshot) { if (snapshot.hasData) { return ListView.builder( itemCount: snapshot.data ?? 0, itemBuilder: (context, index) { // 若需展示具体数据,可结合getTestTypeList获取对应项 return ListTile(title: Text('测试类型 ${index + 1}')); }, ); } else if (snapshot.hasError) { return Text('加载失败:${snapshot.error}'); } return const CircularProgressIndicator(); }, )
内容的提问来源于stack exchange,提问作者Sulaiman Fazli
相关产品推荐
相关产品推荐

