I currently have a working code for storing the local images, uploading it in firestore storage and writing it on cloud firestore. It's all working now. However I am working with the UI for indicators. I want the user to see how many of their images have been uploaded for example "uploaded 1 out of 10 of images". I can't see a similar logic or maybe i do not have any clue on how to do it, any ideas are greatly appreciated.
Future uploadImage() async {
String catchUrls;
// loop, reiterate the files stored in List<XFile> imageFileList
for (var image in imageFileList!) {
// create new file name
String uniqueFileName = DateTime.now().microsecondsSinceEpoch.toString();
// get current file name
String currentFileName = image.path;
// replace with new file na,e
String newFileName =
currentFileName.replaceAll(currentFileName, uniqueFileName);
// reference the location of file.
Reference reference =
FirebaseStorage.instance.ref().child("images").child(newFileName);
// upload file
await reference.putFile(File(image.path));
// get the download urls
catchUrls = await reference.getDownloadURL();
// store the download urls to the List<String>getDownloadUrls.
getDownloadUrls.add(catchUrls);
print(getDownloadUrls);
}
}
You can use StreamController
like following:
StreamController<int> streamController = StreamController();
Future uploadImage() async {
String catchUrls;
// loop, reiterate the files stored in List<XFile> imageFileList
for (var image in imageFileList!) {
// create new file name
String uniqueFileName = DateTime.now().microsecondsSinceEpoch.toString();
// get current file name
String currentFileName = image.path;
// replace with new file na,e
String newFileName =
currentFileName.replaceAll(currentFileName, uniqueFileName);
// reference the location of file.
Reference reference =
FirebaseStorage.instance.ref().child("images").child(newFileName);
// upload file
await reference.putFile(File(image.path));
// get the download urls
catchUrls = await reference.getDownloadURL();
// store the download urls to the List<String>getDownloadUrls.
getDownloadUrls.add(catchUrls);
streamController.add(getDownloadUrl.length);
print(getDownloadUrls);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Hello'),
),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () async {
await uploadImage();
},
child: const Text('Upload Images'),
),
StreamBuilder<int>(
stream: streamController.stream,
initialData: 0,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
'uploaded ${snapshot.data} out of ${imagesFileList.length} of images');
}
return Text('Waiting...');
},
),
],
),
),
);
}
Here at every iteration of adding image to FirebaseStorage you are adding length of getDownloadedUrl
to the stream. And in StreamBuilder
you are getting that length.