You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Flutter中为Firestore创建库存数量变量及更新方案

Flutter + Firestore 库存管理实现方案

1. 创建库存集合与文档结构

Firestore无需手动提前创建集合,添加第一个文档时集合会自动生成。推荐的文档结构如下:

  • 集合名:inventory
  • 每个文档对应一件商品,建议用商品唯一编码(如SKU)作为文档ID,字段包含:
    • productName:商品名称(字符串)
    • sku:商品唯一编码(字符串,确保唯一性)
    • stockQuantity:当前库存数量(整数类型)
    • lastUpdated:最后更新时间(服务器时间戳,可选)

示例代码(添加新商品到库存):

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> addNewProduct(String productName, String sku, int initialStock) async {
  try {
    // 用SKU作为文档ID保证唯一性,也可使用Firestore自动生成ID
    await FirebaseFirestore.instance.collection('inventory').doc(sku).set({
      'productName': productName,
      'sku': sku,
      'stockQuantity': initialStock,
      'lastUpdated': FieldValue.serverTimestamp(),
    });
  } catch (e) {
    print('添加商品失败: $e');
  }
}

2. 入库操作(增加库存)

必须用原子更新方式修改库存,避免并发操作导致数据错误。Firestore提供FieldValue.increment()方法,在服务器端执行增量计算,保证数据一致性。

示例代码:

// 商品入库:增加指定数量
Future<void> stockIn(String sku, int quantity) async {
  try {
    await FirebaseFirestore.instance.collection('inventory').doc(sku).update({
      'stockQuantity': FieldValue.increment(quantity),
      'lastUpdated': FieldValue.serverTimestamp(),
    });
  } catch (e) {
    print('入库失败: $e');
  }
}

3. 出库操作(减少库存)

同样使用FieldValue.increment(),传入负数即可。为避免库存变为负数,可通过客户端校验或Firestore安全规则限制(推荐后者,防止客户端篡改)。

方式1:客户端先校验库存再出库

// 商品出库:减少指定数量,先检查库存是否足够
Future<void> stockOut(String sku, int quantity) async {
  try {
    final docRef = FirebaseFirestore.instance.collection('inventory').doc(sku);
    final docSnapshot = await docRef.get();
    
    if (docSnapshot.exists) {
      final currentStock = docSnapshot.data()!['stockQuantity'] as int;
      if (currentStock >= quantity) {
        await docRef.update({
          'stockQuantity': FieldValue.increment(-quantity),
          'lastUpdated': FieldValue.serverTimestamp(),
        });
      } else {
        print('库存不足,当前库存: $currentStock');
      }
    } else {
      print('商品不存在');
    }
  } catch (e) {
    print('出库失败: $e');
  }
}

方式2:Firestore安全规则强制限制(更安全)

在Firebase控制台的Firestore规则中添加校验,确保出库后库存不小于0:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /inventory/{sku} {
      allow update: if request.resource.data.stockQuantity >= 0;
    }
  }
}

即使客户端跳过校验,服务器也会拒绝非法操作。

4. 读取当前库存

如果需要展示库存数量,直接读取对应文档即可:

// 获取指定商品的当前库存
Future<int?> getCurrentStock(String sku) async {
  try {
    final docSnapshot = await FirebaseFirestore.instance.collection('inventory').doc(sku).get();
    if (docSnapshot.exists) {
      return docSnapshot.data()!['stockQuantity'] as int;
    } else {
      return null;
    }
  } catch (e) {
    print('获取库存失败: $e');
    return null;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:05:34