Flutter get data from firebase correctly - firebase

Hey In my app you can edit your profile for example select a picture from your gallery for your profile picture. All work fine when I'm in the app. But when I close the app and open it again the profile picture is gone. When I select a picture from the gallery the url is stored in cloud firebase. In my code I retrieve the url from cloud firebase and want that this Constants.URL_Profil_Picture = value.docs[0].data()['url']; is work. But it doesnt work. Does anyone know why?
final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
getData() async {
return await _fireStore.collection("SerX").get();
}
Future uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(
fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
var downUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
_URL = downUrl.toString();
setState(() async {
print('Profile Picture uploaded');
var firebaseUser = await FirebaseAuth.instance.currentUser;
FirebaseFirestore.instance.collection("SerX").doc(firebaseUser.uid).update({"url" : downUrl});
getData().then((value){
if(value.docs.length > 0){
Constants.URL_Profil_Picture = value.docs[0].data()['url'];
print(value.docs[0].data()['url']);
}
});
print(Constants.URL_Profil_Picture);
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Profile Picture Uploaded')));
});
}

Related

How to get the url from Firebase Storage file?

I want to retrieve the URL of a Uint8List image from firebase storage. But I am not able to do that. It prints a snapshot, not the url. Please help.
my code:
void _storeSignature() async {
try {
final Uint8List? signature = await exportSignature();
final FirebaseStorage? storage = FirebaseStorage.instance;
final String? pictureUrl =
"signature/${DateTime.now().millisecondsSinceEpoch.toString()}.png";
final ref = storage!.ref().child(pictureUrl!);
final uploadTask = ref.putData(signature!);
final downurl = await uploadTask.whenComplete(() {
return ref.getDownloadURL();
});
final url = downurl.toString();
print(url);
} catch (e) {
rethrow;
}
}
You have to await for the URL when calling ref.getDownloadURL()
change
return ref.getDownloadURL();
into
return await ref.getDownloadURL();
The UploadTask class extends Future, so you can also use await there already:
await ref.putData(signature!);
final downurl = await ref.getDownloadURL();
final url = downurl.toString();

How can I add a photoUrl to the current user?

In my app I choose an image with the image picker dart package (pub.dev link). Then I upload this image to Cloud Storage. I also can get the url from the database, but how can I add this url to the current user as photoUrl? How can I update the firebase user?
image picker code:
getImage(BuildContext context) async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
if (image != null) {
cropImage(image);
_showDialog(context);
}
setState(() {
_image = image;
print("Image Path $_image");
});
}
upload code:
uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child("profilbilder/" + fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
// Photo URL
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
String url = dowurl;
setState(() {
print("Profile Picture uploaded");
});
}
You can use the FirebaseUser object to store a user's profile photo's url.
Refer here: Manage users.
And Firebase getUrl

How to rebuild profile picture widget on changes to file in Firebase Storage (Flutter)

I am trying to build a profile picture widget in Flutter that allows the user to upload an image to Firebase storage and retrieve that image once it has been uploaded. My problem is that I call the _getImage() Function in initState() so anytime the user uploads a new photo the widget isn't rebuilt with the new photo unless the app is restarted. Is there a 'stream' like method I can use to listen to changes in a Firebase Storage location and rebuild a widget accordingly?
I use ImagePicker to get my image from gallery.
_pickImage() async {
final selected = await ImagePicker().getImage(source: ImageSource.gallery);
setState(() {
_imageFile = File(selected.path);
});
_uploadFile(_imageFile);}
After the photo is chosen, it is uploaded to Firebase Storage.
_uploadFile(File _imageFile) async{
var user = await FirebaseAuth.instance.currentUser();
var storageRef = _storage.ref().child('user/profile/${user.uid}');
var uploadTask = storageRef.putFile(_imageFile);
}
Then to retrieve the image, I call the _getImage() function in initState().
void initState() {
super.initState();
_getImage();
}
the _getImage() funtion.
_getImage() async {
var user = await FirebaseAuth.instance.currentUser();
var photoReference = _storage.ref().child("user/profile/${user.uid}");
photoReference.getData(1000000000).then((data){
this.setState(() {
imageFile = data;
});
}).catchError((onError){
print('error');
}); }
here is a example
final image = await ImagePicker()
.pickImage(source: ImageSource.gallery);
if (image == null) return;
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage.ref().child("images/${DateTime.now()}");
UploadTask uploadTask = ref.putFile(File(image.path));
uploadTask.then((res) async {
String fileurl = await (await uploadTask).ref.getDownloadURL();
return fileurl;
You have to upload image on firebase then retrieve the image url
then you can call it on user profile

How to get the download URL from firebase with flutter?

I would like to retrieve the Download URL of a private image in firbase storage.
Hi have tried many of the suggestions on the site, but all of them end up in the same result.
I have tried the following code:
getImageNow() async {
StorageReference ref =
FirebaseStorage.instance.ref().child("/1.jpg");
String url = (await ref.getDownloadURL()).toString();
return url;
}
It works when i print the url inside the function, but when i try to call print(getImageNow())to get the url, i just get "Instance of 'Future<dynamic>'"
UPDATE*************
In the end i am trying to get somthing like this:
return Image.network(
getImageNow(),
);
But i can not get it to work with async.
Since getImageNow() is asynchronous (as indicated by the async keyword), you will need to use await to make the calling code wait for the result:
print(await getImageNow())
What await does here is that it essentially unwraps the Future and is equivalent to:
getImageNow().then((value) => print(value));
this is how i upload and get the download url
this part is how i get image from picker
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
print('Image Path $_image');
});
}
then i upload it
Future uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');
}
hope it will help someone

How to Load Image to Firebase Storage and get downloadUrl (Flutter/Firebase)

I want to implement sending files to Firebase Storage, as well as get a link to it. But for some reason it does not work ...
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
var fileUrl = ref.putFile(file).onComplete.then((file) =>
file.ref.getDownloadURL());
print(fileUrl);
_sendMessage(fileUrl: fileUrl.toString());
}
...
prefixIcon: IconButton(
icon: Icon(Icons.attach_file),
color: Colors.white,
onPressed: () => _pickFile()
)
Why do I get this instead of a link?
I/flutter (16610): Instance of 'Future'
I need a link in the String!
What is the problem?
Like the log say, fileUrl is a Future who is not resolved yet. You should make sure it's resolve to make use of the string give.
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
String fileUrl = await (await ref.putFile(file).onComplete).ref.getDownloadURL();
print(fileUrl);
_sendMessage(fileUrl: fileUrl.toString());
}
You need use await for Future functions
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
final StorageUploadTask uploadTask = ref.putFile(file);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
_sendMessage(fileUrl: downloadUrl);
}
It would look like this without using await
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
ref.putFile(file).onComplete.then((file){
var fileUrl = file.ref.getDownloadURL());
_sendMessage(fileUrl: fileUrl.toString());
});
}
here is my solution to upload and get the uploaded image url
first i get image with image picker
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
print('Image Path $_image');
});
}
then i upload to firebase
Future uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');
setState(() {
print("Profile Picture uploaded");
print("....................$url");
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Profile Picture Uploaded')));
});
}
this is the part i get the downloadUrl of currently uploaded image
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');

Resources