我正在使用Flutter编写应用程序,并且必须使用Firestore.instance.runTransaction(Transaction tx)方法进行交易。
在我的Transaction对象(或方法)中,我必须使用文档引用来更新一些数据。

_firestore.runTransaction((Transaction x) async {
  await x.update(Aref, {'data': itemA - y});
  await x.update(Bref, {'data': itemB + y});
})

代码运行时,将引发异常(此处是控制台日志):

最佳答案

当同时调用Firestore API时,会发生错误,您必须将每个函数嵌套在
上一个函数的“whenComplete((){}”)方法。
这是错误的代码:

g.f.runTransaction((transaction) async {
      DocumentSnapshot snap =
          await transaction.get(/my code);

      await transaction.update(/my code).whenComplete(() {});
    });


g.f.runTransaction((transaction) async {
      DocumentSnapshot freshSnap =
              await transaction.get(/my code));

      await transaction.update(/my code).whenComplete(() {});
});  //here is the problem!! I'have to nest this inside "whenComplete(() {})

这是错误:



这是正确的代码
g.f.runTransaction((transaction) async {
  DocumentSnapshot snap =
      await transaction.get(/my code);

  await transaction.update(/my code).whenComplete(() {
    g.f.runTransaction((transaction) async {
      DocumentSnapshot freshSnap =
          await transaction.get(/my code);

      await transaction.update(/my code);
    }).whenComplete(() {});
  });
});

10-01 21:08
查看更多