skip to Main Content

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


  1. Chosen as BEST ANSWER

    After many hours of research, and screaming to my computer, I found the answer to my problem.


  2. 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.

    await FirebaseFirestore.instance.collection('Images').add({ // โ‡ ๐Ÿ‘ˆ
      'imageUrl': url,
      'timeStamp': Timestamp.now(),
    });
    

    Hereโ€™s the my recreated code :

    class _TestPageState extends State<TestPage> {
      final Stream<QuerySnapshot> imageStreams =
          FirebaseFirestore.instance.collection('images').snapshots();
    
      @override
      Widget build(BuildContext context) {
        void pickImage() async {
          final ImagePicker picker = ImagePicker();
          final image = await picker.pickImage(source: ImageSource.gallery);
          if (image != null) {
            //Upload to Firebase
            final fileBytes = await image.readAsBytes();
            Reference reference = FirebaseStorage.instance.ref().child(image.name);
            final snapshot = await reference.putData(fileBytes);
            String downloadUrl = await snapshot.ref.getDownloadURL();
            await FirebaseFirestore.instance.collection('images').add({
              'imageUrl': downloadUrl,
              'timeStamp': Timestamp.now(),
            });
          } else {
            print('No Image Path Received');
          }
        }
    
        return Scaffold(
          appBar: AppBar(
            title: const Text('Flutter Demo'),
          ),
          body: StreamBuilder<QuerySnapshot>(
            stream: imageStreams,
            builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (snapshot.hasError) {
                return const Text('Something went wrong');
              }
    
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Text("Loading");
              }
    
              return ListView.builder(
                  itemCount: snapshot.data!.docs.length,
                  itemBuilder: (context, index) {
                    final image = snapshot.data!.docs[index];
                    return Image.network(image["imageUrl"]);
                  });
            },
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: pickImage,
            tooltip: 'Upload Image',
            child: const Icon(Icons.image),
          ),
        );
      }
    }
    

    Reference : Adding Documents

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search