Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在每次使用Flatter/Firebase按下上载按钮时创建唯一的图像ID?_Firebase_Flutter_Dart_Google Cloud Firestore_Unique Id - Fatal编程技术网

如何在每次使用Flatter/Firebase按下上载按钮时创建唯一的图像ID?

如何在每次使用Flatter/Firebase按下上载按钮时创建唯一的图像ID?,firebase,flutter,dart,google-cloud-firestore,unique-id,Firebase,Flutter,Dart,Google Cloud Firestore,Unique Id,我正在尝试制作一个图像上传按钮并将其链接到Firebase,这样每次按下按钮时,图像都会发送到Firebase存储。以下是我的代码的相关片段: // Files, and references File _imageFile; StorageReference _reference = FirebaseStorage.instance.ref().child('myimage.jpg'); Future uploadImage() async { // up

我正在尝试制作一个图像上传按钮并将其链接到Firebase,这样每次按下按钮时,图像都会发送到Firebase存储。以下是我的代码的相关片段:

  // Files, and references
  File _imageFile;
  StorageReference _reference =
      FirebaseStorage.instance.ref().child('myimage.jpg');

  Future uploadImage() async {
    // upload the image to firebase storage
    StorageUploadTask uploadTask = _reference.putFile(_imageFile);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;

    // update the uploaded state to true after uploading the image to firebase
    setState(() {
      _uploaded = true;
    });
  }
  // if no image file exists, then a blank container shows - else, it will upload 
  //the image upon press
  _imageFile == null
                ? Container()
                : RaisedButton(
                    color: Colors.orange[800],
                    child: Text("Upload to Firebase Storage"),
                    onPressed: () {uploadImage();}),
但是,每次我按下这个按钮,图像都会用相同的名称覆盖先前存在的图像,我想知道是否有办法使它在每次我按下按钮时,图像的名称都会改变,因此原始图像不会被覆盖。我非常感谢能得到的任何帮助,因为我对弗利特和Firebase非常陌生


谢谢大家!

基本上,当你打电话时:

FirebaseStorage.instance.ref().child('myimage.jpg');
您每次都以相同的名称上载文件:

myimage.jpg

为了解决您的问题,您只需要为图像生成一个随机密钥。有几种方法可以做到这一点:

如果您使用Firestore(Firebase提供的数据库)进行了设置,那么您可以将图像的名称推送到数据库中,并让它返回DocumentID,Firestore将为您创建一个未使用的随机ID

您还可以使用当前日期/时间:

DateTime.now().toString()

当然,您也可以根据正在上载的文件名编写自己的哈希函数,您可以通过以下操作获得该函数:

_imageFile.toString();
然后,一旦您获得文件的随机名称,您应该像这样上传它:

FirebaseStorage.instance.ref().child(myImageName).putFile(_imageFile);

我想你在找UUID发生器

幸运的是,有一个包装:

现在,您可以使用postID作为文件名

注意上载文件时,您可能希望生成新的uuid以避免使用旧的uuid:)


还有一件事:请不要使用DateTime.now()

打印(DateTime.now().toString());可能是可能的解决方案。是的,那是可能的。非常感谢。我会记住这一点;我也一直在看UUID。非常感谢。
FirebaseStorage.instance.ref().child(myImageName).putFile(_imageFile);
String fileID = Uuid().v4(); // Generate uuid and store it.