在Flutter中使用Firestore创建库存数量变量

huangapple go评论70阅读模式
英文:

Create Stock Quantity Variable in Firestore with Flutter

问题

我想通过Flutter在Firestore中创建一个集合,用于存储一个数量变量,该变量在我通过Flutter应用程序进行进货和出货时会更新。然而,我似乎不明白如何创建它。我应该如何存储它,以及如何在进货和出货物品时更新数量字段?

英文:

I want to create a collection in Firestore through flutter where I can store a quantity variable which gets updated when I stock in and stock out items through my flutter app. However I can't seem to understand how to create that. How should I store that and how should I update the quantity field on stocking in and out items?

答案1

得分: 1

一个集合在创建其第一个文档时会自动创建。

因此,如果您只需要管理一个库存,可以在例如 stock 集合中创建(初始化)一个唯一的文档,并分配初始库存。这种初始化可以很好地通过 Firestore 控制台完成。

然后,要调整库存数量,这取决于您的全局功能需求:

  1. 如果您只想增加/减少库存数量,而不影响Firestore中的任何其他文档,可以使用 FieldValue.increment() 方法(使用负值来减少)。
  2. 如果您的操作必须是事务性的并涉及Firestore中的其他一些文档(例如,您修改银行账户、电子商务购物篮或者与此库存操作并行的其他库存),您应该使用 Transaction

您还可以考虑是否真的想要允许此操作来自您的Flutter应用,而不是来自后端(例如,Cloud Functions)。要允许最终用户从应用中执行此操作,您将不得不打开对一个或多个集合的写入访问权限,如果无法实施防止恶意用户以不希望的方式更改库存值的安全规则,恶意用户可能会改变库存值。

英文:

A collection is automatically created when its first document is created.

So if you need to manage only one stock you can create (initiate) a unique document in e.g. a stock collection and assign the initial stock. This initialization can very well be done through the Firestore console,

Then, to adapt the stock quantity, it depends on your global functional requirement:

  1. If you just want to increment/decrement the stock quantity without impacting any other document in Firestore you can use the FieldValue.increment() method (use a negative value to decrement).
  2. If your operation must be transactional and involves some other Firestore document (e.g. you modify a bank account, or a e-commerce basket, or another stock in parallel to this stock operation) you should use a Transaction.

You may also consider if you really want to allow this operation from your Flutter app and not from a back-end (e.g. Cloud Functions). To allow end users to do this from an app you'll have to open the write access to one or more collections and a malicious user could change the stock value in an undesired way if you cannot implement a security rule that prevents that.

huangapple
  • 本文由 发表于 2023年2月8日 18:51:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384718.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定