You need to enable JavaScript to run this app. Flutter async/await数据库事务循环中GamePlayer更新值全为1 如何实现counter每次更新后递增
优惠活动
大模型
产品
解决方案
定价
更多

Flutter async/await数据库事务循环中GamePlayer更新值全为1 如何实现counter每次更新后递增

问题原因

该现象由两个Dart异步特性共同导致:

  • forEach是同步遍历方法,遇到传入的async回调时,仅会同步触发所有回调的前半段代码(直到第一个await位置),不会等待每个回调的异步操作执行完成。
  • async函数中,第一个await之前的代码为同步执行逻辑。在同步遍历所有列表元素时,所有更新result_position的SQL语句都会被立刻构造完成,此时counter还停留在初始值1(counter++在后续的异步微任务中才会执行),因此所有SQL语句里的result_position都被替换成了1。

额外存在执行顺序问题:因为forEach瞬间执行完毕,后续更新game表的语句会先于循环内的数据库操作被调用,破坏业务逻辑预期的执行顺序。

解决方案

将同步的forEach替换为支持异步等待的for-in循环,保证每次迭代的所有数据库操作完成、counter递增后,再进入下一次迭代;同时确保事务会等待所有循环操作完成后,再执行game表的更新。
修改后的代码如下:

Future<bool> closeGame(List<GamePlayer> sortedWinnerList, Game game) async {
try {
  int counter = 1;
  await _database.transaction((txn) async {
    for (final element in sortedWinnerList) {
      print('xx update gamePlayer, counter= $counter');
      await txn.execute(
          'update $tableName_GAMEPLAYER set result_position = $counter where id=${element.id}');
      GameResult newResult = new GameResult(
          gameId: game.id,
          playerId: element.playerId,
          amount: element.gameWinAmount);
      await txn.insert(tableName_GAMERESULT, newResult.toJson());
      print('xx loop end, counter= $counter');
      counter++;
    }
    await txn.execute(
        'update $tableName_GAME set ended = ${DateTime.now().millisecondsSinceEpoch}');
  });

  return true;
} catch (e) {
  print('Game not closed: $e');
}

return false;
}

修改后,for-in循环在async函数中会串行执行:每次迭代等待execute和insert两个异步操作全部完成后,再执行counter++,随后才进入下一次迭代构造SQL,此时counter的值已经是当前位次的正确值,最终result_position会按列表顺序依次被更新为1、2、3……符合预期。同时事务会等待所有循环内的操作完成后,再执行game表的更新,执行顺序也符合业务逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 11:57:09