【发布时间】:2021-01-06 08:09:12
【问题描述】:
Firebase:如何使用离线用户更新库存?
我有一个使用 Flutter 和 Firebase 构建的 Agro 应用程序。该应用程序的工作原理如下:
- 您的仓库中有食品库存
- 用户在离线模式下外出喂动物(他们在农场)
- 然后它们返回并根据 Firebase 的 Offline 属性执行数据库写入
当用户在喂食时在线时,一切正常,但是在离线模式下喂食时,我遇到了专门更新库存的问题,因为离线用户缓存的库存可能与真实库存不同(或者因为新食物已经引入或由于其他用户的在线更新)。
我将数据写入 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 数量分配给 Inventory,而是执行“减少 Inventory 中数量的 _consumoTotal”之类的操作,这样用户是离线还是在线都无关紧要。这可能吗?
我审查过的另一种选择是使用事务来确保您使用的是最新数据,但是当用户离线时事务会丢失,因此这是不可能的。
考虑到我的用户经常离线,我如何才能以正确的方式更新库存?
【问题讨论】:
标签: firebase flutter firebase-realtime-database transactions