How to create unique image ID each time upload is pressed using Flutter/Firebase?

I think you're looking for a UUID generator.

Fortunately there is a packege for that : uuid

String fileID = Uuid().v4(); // Generate uuid and store it.

Now you can use postID as name for your file.

NOTE When you upload your file you may want to generate new uuid to avoid using the old one :)

One more thing: PLEASE dont use DateTime.now() think about if two users uploaded an image at the same time !!


Basically, when you call:

FirebaseStorage.instance.ref().child('myimage.jpg');

You're uploading the file with the same name everytime:

myimage.jpg

In order to fix your problem, you just need to generate a random key for the image. There are a couple ways you could do this:

Ideally, you would use the Uuid package which is specifically for use-cases like this.

If you are set up with Firestore (the database that Firebase offers) then you can push the name of the image to the database, and have it return the DocumentID which Firestore will create a random ID for you that isn't used.

You could also use the current Date/Time (which would be considered a bad practice for major applications, but for a personal project it will serve you just fine):

DateTime.now().toString()

or

DateTime.now().toIso8601String();

Or of course, you can always write your own hashing function, based on the name of the file that you are uploading, which you would get by doing:

_imageFile.toString();

Then once you get the random name of the file, you should upload it like this:

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