I am using Flutter with image_picker
and firebase_storage
to store an image and then download the link to place in a firestore
database. Here is my current code:
final picker = ImagePicker();
final file = await picker.pickImage(source: ImageSource.gallery);
final fileBytes = await file!.readAsBytes();
var reference = FirebaseStorage.instance.ref().child(file.name);
await reference.putData(fileBytes);
String url = await reference.getDownloadURL();
FirebaseFirestore.instance.collection('Images').add({
'imageUrl': url,
'timeStamp': Timestamp.now(),
});
The variable url
has a value like https://firebasestorage.googleapis.com/v0/b/myproject.appspot.com/o/example.png?alt=media&token=image-token
.
I want to display the images using a StreamBuilder
:
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Images')
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
final image = snapshot.data!.docs[index];
return Image.network(image["imageUrl"]);
}
);
} else if (snapshot.hasError) {
return Center(
child: Text('Error: ${snapshot.error}'),
);
}
return const Center(
child: CircularProgressIndicator(),
);
}
)
But I am getting the error
ImageCodecException: Failed to load network image.
Image URL:https://firebasestorage.googleapis.com/v0/b/myproject.appspot.com/o/example.png?alt=media&token=image-token
Server response code: 400
for every image.
2
Answers
After many hours of research, and screaming to my computer, I found the answer to my problem.
I have recreated your setup and got your desired result. It looks like you were not awaiting for this promise to be resolved hence it was not getting stored in the firestore document.
Hereโs the my recreated code :
Reference : Adding Documents