如何使用 Firebase 中的离线用户更新清单?

How to update an inventory with offline users in Firebase?

Firebase:如何使用离线用户更新清单?

我有一个使用 Flutter 和 Firebase 构建的 Agro 应用程序。该应用程序的工作方式如下:

  1. 您的仓库中有食品库存
  2. 用户在离线模式下外出喂养动物(他们在农场)
  3. 然后他们return和数据库写入根据Firebase
  4. 的离线属性执行

当用户在喂食时在线时,一切正常,但在离线模式下喂食时我有一个问题,特别是更新库存,因为离线用户缓存的库存可能与真实库存不同(或者因为新食品已被介绍或因为其他用户的在线更新)。

我将数据写入 Firebase 的方式(使用 BLOC 模式)如下:

  Future<bool> actualizarCantidad(String idAlimento, double cantidadActualizada) async {
  try {
      db.child('alimento/$idAlimento').update({ "cantidad": cantidadActualizada});
    } catch (e) {
      print(e);
    }
    return true;
  }

读取库存和更新数据库的函数如下:

Future<void> _submit() async {

    _alimento = await alimentoBloc.cargarAlimento(alimentar.idAlimento); 
    //To read the inventory for the specific food type (alimentar.idAlimento)

    final _cantAlimento = _alimento.cantidad - _consumoTotal; 
    //_alimento.cantidad is refered to the inventory
    //_consumoTotal is the quantity to reduce (eaten food)

    _alimentoBloc.actualizarCantidad(alimentar.idAlimento, _cantAlimento);
    //Use the BLOC and PROVIDER pattern to Update the Inventory with a new Quantity (_cantAlimento)
}

我想在 Firebase 中做的是,不是将 _cantAlimento 数量分配给库存,而是执行类似“减少库存数量的 _consumoTotal”之类的操作,这样用户是离线还是在线都没有关系。这可能吗?

我审查过的另一种选择是使用事务来确保您使用的是最新数据,但是当用户离线时事务会丢失,所以这不可能。

考虑到我的用户经常离线,我如何以正确的方式更新库存?

从几个月前开始,Firebase 实时数据库支持 ServerValue.increment() 操作,即使客户端未连接到服务器,也可用于自动 increment/decrement 数据库中的值。

这个新方法也刚刚登陆 FlutterFire firebase_database 插件的 4.1 版 ServerValue class. If you have issues with it, I'd file a bug or leave a comment on the feature request.

根据@puf 的回答,在 Firebase 中使用 ServerValue.increment() 更新库存或数字的过程如下:

  db.child('alimento/$idAlimento/cantidad')
    .set(ServerValue.increment(-consumo.round()));

重要的是要注意 ServerValue.increment() 仅支持整数(到目前为止,它不支持双精度数)。如果你有一个双数,你应该把它四舍五入,你可以尝试使用一个更小的单位(在我的例子中是 grs 而不是 Kgs)。