Reputation: 61
I'm trying to fetch images out of firebase storage with url and Image.network()
.
But somehow I stuck.
I use this example from firebase storage documentation:
Future downloadURLExample() async {
String downloadURL = await firebase_storage.FirebaseStorage.instance
.ref('users/123/avatar.jpg')
.getDownloadURL();
// Within your widgets:
// Image.network(downloadURL);
return downloadURL;
}
But I dont know how do I get this String downloadURL into my container and Image.network.
I try to do it like this:
Container(
width: 200,
height: 200,
child: Image.network(downloadURL),
),
But it doesnt work. What am I missing?
Upvotes: 0
Views: 205
Reputation: 7716
The issue is that you're trying to get downloadURL
which is not in the scope of the build method. You need to get the download URL from the downloadURLExample
method.
Here is an example using FutureBuilder.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Future<String> _downloadURLFuture;
@override
void initState() {
super.initState();
_downloadURLFuture = downloadURLExample();
}
Future<String> downloadURLExample() async {
String downloadURL = await firebase_storage.FirebaseStorage.instance.ref('users/123/avatar.jpg').getDownloadURL();
return downloadURL;
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _downloadURLFuture,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
final String downloadURL = snapshot.data;
return Image.network(
downloadURL,
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent loadingProgress) {
return Center(
child: CircularProgressIndicator(),
);
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
}
Upvotes: 0
Reputation: 265
// use firebase package as fb
import 'package:firebase/firebase.dart' as fb;
import 'package:flutter/material.dart';
class Example extends StatefulWidget {
const Example({Key key}) : super(key: key);
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
//variable for the called photo uri
Uri img;
//
downloadURLExample() {
fb
.storage()
.refFromURL(
'gs://******.appspot.com/users/123/avatar.jpg')
.getDownloadURL()
.then((value) => setState(() => img = value));
}
@override
void initState() {
//initialize method
downloadURLExample();
super.initState();
}
@override
Widget build(BuildContext context) {
return img == null
? CircularProgressIndicator()
: Container(
width: 200,
height: 200,
child: Image.network(img.toString()),
);
}
}
Upvotes: 0