Dart/Flutter中如何在Text组件中获取Future<int>返回的数据库统计结果
解决方案
问题根因
getCountTodo是异步方法,返回Future<int>类型对象而非直接的int结果,直接调用toString()只会输出Future对象的类型描述,无法拿到异步查询返回的实际统计值。
标准修复方案
使用Flutter内置的FutureBuilder组件处理异步值渲染,替换原有Text组件即可:
FutureBuilder<int>( // 传入要执行的异步查询方法 future: DatabaseHelper.instance.getCountTodo(task.tasklist[index].id), builder: (context, snapshot) { // 异步查询中展示加载状态 if (snapshot.connectionState == ConnectionState.waiting) { return const Text( '加载中...', style: TextStyle( fontSize: 14.0, color: Colors.grey, fontWeight: FontWeight.bold ), ); } // 查询异常/无数据时展示默认值 if (snapshot.hasError || !snapshot.hasData) { return const Text( '0 ITEM', style: TextStyle( fontSize: 14.0, color: Colors.grey, fontWeight: FontWeight.bold ), ); } // 查询完成拿到结果正常渲染 final todoCount = snapshot.data!; return Text( '$todoCount ITEM', style: const TextStyle( fontSize: 14.0, color: Colors.grey, fontWeight: FontWeight.bold ), ); }, )
额外优化建议
- 避免SQL注入风险,原有查询语句直接拼接参数的写法不安全,建议改用占位符传参:
// 修改getCountTodo中的查询代码 List<Map<String, dynamic>> x = await db.rawQuery( 'SELECT COUNT (*) from $todoTable where taskId = ?', [taskId] ); - 如果是在长列表中使用该查询,建议提前一次性查询所有任务对应的统计值存入状态列表,避免每个列表项单独发起异步查询造成性能损耗。
内容的提问来源于stack exchange,提问作者Ishwor Subedi
相关产品推荐
相关产品推荐

