Flutter Load Image from Firebase Storage

前端 未结 3 556
盖世英雄少女心
盖世英雄少女心 2020-12-05 18:29

I see there are a lot of examples on how to upload an image using flutter to firebase storage but nothing on actually downloading/reading/displaying one that\'s already bee

相关标签:
3条回答
  • 2020-12-05 19:11

    Here's an example of a stateful widget that loads an image from Firebase Storage object and builds an Image object:

    class _MyHomePageState extends State<MyHomePage> {
    
      final FirebaseStorage storage = FirebaseStorage(
          app: Firestore.instance.app,
          storageBucket: 'gs://my-project.appspot.com');
    
      Uint8List imageBytes;
      String errorMsg;
    
      _MyHomePageState() {
          storage.ref().child('selfies/me2.jpg').getData(10000000).then((data) =>
                    setState(() {
                      imageBytes = data;
                    })
            ).catchError((e) =>
                    setState(() {
                      errorMsg = e.error;
                    })
            );
      }
    
      @override
      Widget build(BuildContext context) {
        var img = imageBytes != null ? Image.memory(
            imageBytes,
            fit: BoxFit.cover,
          ) : Text(errorMsg != null ? errorMsg : "Loading...");
    
        return new Scaffold(
            appBar: new AppBar(
              title: new Text(widget.title),
            ),
            body: new ListView(
              children: <Widget>[
                img,
              ],
            ));
      }
    }
    

    Note that FirebaseApp initialization is handled by the Firestore class, so no further initialization code is necessary.

    0 讨论(0)
  • 2020-12-05 19:21

    To view the images inside your storage, what you need is the name of the file in the storage. Once you've the file name for the specific image you need. In my case if i want the testimage to be loaded,

    final ref = FirebaseStorage.instance.ref().child('testimage');
    // no need of the file extension, the name will do fine.
    var url = await ref.getDownloadURL();
    print(url);
    

    Once you've the url,

    Image.network(url);
    

    That's all :)

    0 讨论(0)
  • 2020-12-05 19:27

    update

    In newer versions use

    await ref.getDownloadURL();
    

    See How to get full downloadUrl from UploadTaskSnapshot in Flutter?

    original

    someMethod() async {
      var data = await FirebaseStorage.instance.ref().child("foo$rand.txt").getData();
      var text = new String.fromCharCodes(data);
      print(data);
    }
    

    see Download an image from Firebase to Flutter

    or

    final uploadTask = imageStore.putFile(imageFile);
    final url = (await uploadTask.future).downloadUrl;
    

    In the later case you'd need to store the downloadUrl somewhere and then use NetworkImage or similar to get it rendered.

    0 讨论(0)
提交回复
热议问题