如何在Fire Base中存储图像并在Firestore中存储URL

时间:2020-03-26 14:22:25

标签: firebase flutter dart

我想将优惠券卡发送到包含(名称-地址-优惠券)的消防商店,并且我想让用户为每张卡设置特定的图片

那是我的FireStoreService文件

class FireStoreService {

  FireStoreService._internal();
  static final FireStoreService firestoreService = FireStoreService._internal();
  Firestore db = Firestore.instance ;

  factory FireStoreService() {
    return firestoreService;
  }

  Stream<List<Coupon>> getCoupon() {
    return db.collection('coupon').snapshots().map(
          (snapshot) => snapshot.documents.map(
            (doc) => Coupon.fromMap(doc.data, doc.documentID),
      ).toList(),
    );
  }

  Future<void> addCoupon(Coupon coupon) {
    return db.collection('coupon').add(coupon.toMap());
  }

  Future<void> deleteCoupon(String id) {
    return db.collection('coupon').document(id).delete();
  }

  Future<void> updateCoupon(Coupon coupon) {
    return db.collection('coupon').document(coupon.id).updateData(coupon.toMap());
  }



}

这是优惠券模型文件

class Coupon {
  final String id;
  final String storeName;
  final String storeLink;
  final String couponCode;

  Coupon(
      {this.id, this.storeName, this.storeLink, this.couponCode});

  Coupon.fromMap(Map<String, dynamic> data, String id)
      : storeName = data["storeName"],
        storeLink = data['storeLink'],
        couponCode = data["couponCode"],
        id = id;

  Map<String, dynamic> toMap() {
    return {
      "storeName": storeName,
      'storeLink': storeLink,
      'couponCode': couponCode,
    };
  }
}

这是图像选择器代码,可以正常工作并拾取图像

Future getImage() async {
    try {
      File image = await ImagePicker.pickImage(source: ImageSource.gallery);

      setState(() {
        image = image;
      });
    } catch (e) {
      print(e);
    }
  }

有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

这是一个要求imageFile的函数。如果您运行代码(getImage函数):将image变量传递给uploadImage函数。

String myUrl = await uploadImage(file);

然后,您可以使用setData或updateData将URL放入数据库中。

  Firestore.instance.collection('books').document()
      .setData({ 'title': 'title', 'url': '$myUrl' })


final StorageReference storageRef = FirebaseStorage.instance.ref();

  Future<String> uploadImage(imageFile) async {
    StorageUploadTask uploadTask =
        storageRef.child("myPath&Name.jpg").putFile(imageFile);
    StorageTaskSnapshot storageSnap = await uploadTask.onComplete;
    String downloadURL = await storageSnap.ref.getDownloadURL();
    return downloadURL;
  }