firebase Flutter 火力基地:使用图像url更新字段

wbgh16ku  于 2023-03-13  发布在  Flutter
关注(0)|答案(1)|浏览(99)

如何使用图像url更新集合中的字段?我可以使用其他字符串更新,但图像url似乎不起作用。我首先将此图像imageUrl上载到名为“Documents”的不同子集合中。它起作用了。我想使用同一imageUrl更新其名为“users”的父集合,其中包含字段“Document”。但它不起作用。有帮助吗?

File? image;
  String? imageUrl = "";
  String uid = FirebaseAuth.instance.currentUser!.uid;
  Future<File> customCompressed(
      {required File imagePathToCompress,
      quality = 100,
      percentage = 10}) async {
    var path = await FlutterNativeImage.compressImage(
        imagePathToCompress.absolute.path,
        quality: 100,
        percentage: 80);
    return path;
  }

  Future<File?> pickImages() async {
    File? image;
    try {
      final pickedImage =
          await ImagePicker().pickImage(source: ImageSource.camera);
      if (pickedImage != null) {
        image = File(pickedImage.path);
        File compressedImage =
            await customCompressed(imagePathToCompress: image);
        setState(() {
          image = compressedImage;
        });
      }
    } catch (e) {
      showSnackBar(context, e.toString());
    }
    return image;
  }

  upload() async {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);

    String uid = FirebaseAuth.instance.currentUser!.uid;

    var imageFile = File(image!.path);

    FirebaseStorage storage = FirebaseStorage.instance;
    Reference ref = storage.ref().child("Document").child(uid);

    UploadTask uploadTask = ref.putFile(imageFile);
    await uploadTask.whenComplete(() async {
      var url = await ref.getDownloadURL();
      imageUrl = url.toString();
    }).catchError((onError) {
      return onError;
    });

    Map<String, dynamic> getdata = {
      "document": imageUrl,
      "Full name": authProvider.userModel.fullName,
      "Email": authProvider.userModel.email,
      
    };
    CollectionReference collectionReference = FirebaseFirestore.instance
        .collection('users')
        .doc(uid)
        .collection('Documants');

    collectionReference.add(getdata);
  }

  // for selecting image
  void selectImage() async {
    image = await pickImages();
  }

  CollectionReference ref = FirebaseFirestore.instance.collection('users');

TextButton(onPressed: () { upload();
ref.doc(uid).update({'Status': 'Pending verification'});
ref.doc(uid).update({'Document': imageUrl});
 },
 child: const Text('Upload document',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),))
hzbexzde

hzbexzde1#

要更新单据,您必须先创建单据。然后,如果要更新值,您必须再次执行相同的操作。
下面是经过一些修改的代码。重要的是,如果你想更新一个现有的文档,而不是创建一个新的文档,你需要传递一个带有“update”操作的枚举。在函数中,我检索以前的文档ID,并使用update函数修改它。
希望对你有帮助。问候。顺便说一句,如果我的英语不是最好的,很抱歉。

Future<void> upload({required OperationType operationType}) async {
  final authProvider = Provider.of<AuthProvider>(context, listen: false);

  final String uid = FirebaseAuth.instance.currentUser!.uid;

  final imageFile = File(image!.path);
  String? imageUrl;

  final FirebaseStorage storage = FirebaseStorage.instance;
  final Reference ref = storage.ref().child("Document").child(uid);
  final UploadTask uploadTask = ref.putFile(imageFile);
  await uploadTask.whenComplete(() async {
    final url = await ref.getDownloadURL();
    imageUrl = url;
  }).catchError((onError) {
    return onError;
  });

  final Map<String, dynamic> getdata = {
    "user_id": uid,
    "document": imageUrl,
    "full_name": authProvider.userModel.fullName,
    "email": authProvider.userModel.email,
  };
  final CollectionReference collectionReference = FirebaseFirestore.instance
      .collection('users')
      .doc(uid)
      .collection('Documants');
  if (operationType == OperationType.create) {
    await collectionReference.add(getdata);
  } else {
//Update
//Here, you need to retrieve the previously created file in order to update it.
//If you already have the value, you can pass it as an argument to the function, such as "String? docId".
    final documents = await collectionReference
        .where("user_id", isEqualTo: uid)
        .limit(1)
        .get();
    if (documents.docs.isNotEmpty) {
      final previousDocId = documents.docs[0].id;
      await collectionReference.doc(previousDocId).update(getdata);
    } else {
      // Throws Some exception because didnt find previous value
      throw Exception();
    }
  }
}

相关问题