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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 06:06:03