Save the image even the application restart - firebase

I have a problem. Everytime when I search a image from my gallery for my profilepicture its work. even when I pressed the log out button and log in again there is still my profilpicture. But when I closed the app and I restart the app then the profilepicture is gone. Does anyone know how to save the URL correctly?
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();
Constants.URL_Profil_Picture = downUrl.toString();
setState(() {
print('Profile Picture uploaded');
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Profile Picture Uploaded')));
});
}
image: (_image != null) ? FileImage(
_image)
: NetworkImage(Constants.URL_Profil_Picture),

This seems the cause of the problem:
Constants.URL_Profil_Picture = downUrl.toString();
My guess it that when you restart the app, the Constants.URL_Profil_Picture is set to its hard-coded value again.
You'll need to store the URL somewhere that survives application restarts. The common approaches for that are:
Store the URL in shared preferences, or some other form of local storage. This makes the URL available only on the device where it was uploaded from.
Store the URL in a cloud database, such as Cloud Firestore or Realtime Database. This is the most common option, as it gives you the most flexibility.
Given that you're talking about user profiles: if you're using Firebase Authentication to sign in the user, and this image is their profile picture, you can also store it in the user profile.

Related

Firebase returns null photoUrl

I am building a mock social media app that allows users upload profile pictures to create their profiles. I am building this app in flutter.
Right now, here's my uploadPic method:
Future uploadPic(BuildContext context) async{
String fileName = basename(_image.path);
FirebaseStorage storage = FirebaseStorage.instance;
var photoUrl;
Reference ref = storage.ref().child(fileName);
var storedImage = File(_image.path);
UploadTask uploadTask = ref.putFile(storedImage);
uploadTask.then((res) {
photoUrl = res.ref.getDownloadURL();
});
print("photo url -- $photoUrl");
await widget.user?.updatePhotoURL(photoUrl);
await FirebaseAuth.instance.currentUser?.updatePhotoURL(photoUrl);
}
I have added the right permissions in my firebase console to allow read and write to the database. I know this because when I check firebase storage, I see the pictures have been uploaded successfully. However, when I try to print the returned photo url (after the upload task completes), I get a null value. This is a problem when I try to access the photo in other areas in the app, because the user photoUrl in firebase is null.
Is there anything I am doing wrong concerning the upload of the pic to firebase?
Also, my terminal returns this: No App Check token for request.. I'm wondering if this has anything to do with the issue?
Any help would be greatly appreciated!
your problem is simple, it's exactly from here:
var photoUrl;
uploadTask.then((res) {
photoUrl = res.ref.getDownloadURL();
});
print(photoUrl); // null
the problem is you are trying to print photoUrl variable without waiting for the future uploadTask to finish its work which results null.
the solution is to wait for uploadTask future before printing the photoUrl variable:
var photoUrl;
await uploadTask.then((res) async {
photoUrl = await res.ref.getDownloadURL();
});
print(photoUrl);
the solution on your code:
Future uploadPic(BuildContext context) async{
String fileName = basename(_image.path);
FirebaseStorage storage = FirebaseStorage.instance;
var photoUrl;
Reference ref = storage.ref().child(fileName);
var storedImage = File(_image.path);
UploadTask uploadTask = ref.putFile(storedImage);
await uploadTask.then((res) async {
photoUrl = await res.ref.getDownloadURL();
});
print("photo url -- $photoUrl");
await widget.user?.updatePhotoURL(photoUrl);
await FirebaseAuth.instance.currentUser?.updatePhotoURL(photoUrl);
}

How can i get Image URL from Firebase Storage to Firebase Database without uploading image from my app?

I upload one image from my computer to Firebase Storage and now I want that image to get in my Firebase database with his information and display it in my app. I can display information but cant display images. I google also but in every answer, they say first to upload the image to firebase storage from the app. then get his URL in the database and I don't want to upload from my app.
So if someone know then help.
You Can Get the download link for your image Like this
static final firebase_storage.FirebaseStorage storage =
firebase_storage.FirebaseStorage.instance;
String url = await storage
.ref('YourImagePath')
.getDownloadURL();
In addition to SARADAR21's excellent answer on how to get the data for a file at a known path, you can also list the files in Cloud Storage through the API, in case you don't know the path.
From that documentation:
final storageRef = FirebaseStorage.instance.ref();
final listResult = await storageRef.listAll();
for (var prefix in listResult.prefixes) {
// The prefixes under storageRef.
// You can call listAll() recursively on them.
}
for (var item in listResult.items) {
// The items under storageRef.
}
You can then use the references you get this way, and call getDownloadUrl() to get a download URL for each of them.
Future<QuerySnapshot?> getDataFromFirebase() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
FirebaseFirestore.instance
.collection('Images')
.get()
.then((QuerySnapshot? querySnapshot) {
querySnapshot!.docs.forEach((doc) {
List<dynamic> allImageData = doc["image_data"];
storeImageList = allImageData.map((i) => i.toString()).toList();
});
prefs.setStringList("imageList", storeImageList);
});
}

How to show the image downloaded fom the firebase storage always in a flutter application statically,can be opened and viewed on a click

How to show the image downloaded from the firebase storage always in a flutter application statically, can be opened and viewed on a click.
I have already uploaded an image from camera and gallery to firebase storage. Now I want to download the image from the firebase storage and make a provision that the images downloaded will be readily stay in the application without disappearing.
I mean when ever user visits that flutter application screen, the image or images downloaded should be shown.
Uploaded the image using using firebase storage:
final FirebaseStorage _storage =
FirebaseStorage(storageBucket: 'gs://flutter-imageupload-cb66a.appspot.com');
StorageUploadTask _uploadTask;
_startUpload() async {
String imagePath = 'DeviceImages/DeviceImage${DateTime.now()}.png';
final StorageReference storageReference = FirebaseStorage().ref().child(imagePath);
final StorageUploadTask uploadTask = storageReference.putFile(imageFile1);
await uploadTask.onComplete;
_addPathToDatabase(imagePath);
print("Image uploaded");
setState(() {
_uploadTask =
_storage.ref().child(imagePath).putFile(imageFile1);
});
}
used firebase_storage: ^3.1.6 and firebase_database:
used image_picker: ^0.6.7+17 for picking the image from camera and Gallery.
To download an image from firebase storage, try the following:
final StorageReference storageReference = FirebaseStorage().ref().child(imagePath);
final UploadTask uploadTask = storageReference.putFile(imageFile1);
uploadTask.then((res) {
res.ref.getDownloadURL();
});
UploadTask extends the Future class therefore you can use then() which registers a callback which will be called after the future returns a result. Then you will be able to get the url using the method getDownloadUrl().
Once you have the url you can use CachedNetworkImage class and do the following:
CachedNetworkImage(
imageUrl: imgUrl,
);
You need to download the package first:
https://pub.dev/packages/cached_network_image
Check the guide here on how to display images from the internet:
https://flutter.dev/docs/cookbook/images/network-image
https://flutter.dev/docs/cookbook/images/cached-images

How to download images from firebase storage to current user Cloud Firestore Flutter?

This is the code used to save a chosen image from image picker to firebase storage.
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;
setState(() {
print("Profile Picture uploaded");
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Profile Picture Uploaded')));
});
}
Upon choosing an image as an authenticated user (I took care of authentication already) how can I convert the image as a URL for the current user's cloud firestore from which that image can appear in different areas of the app?
I save user information via the current user's uid as such for further context:
Future<void> userSetup(String displayName) async {
int plastics = 0;
final CollectionReference users =
FirebaseFirestore.instance.collection('Users');
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
users.doc(uid).set({'displayName': displayName, 'uid': uid});
users.doc(uid).update({'plastics': plastics});
return;
}
Posting as Community Wiki, based in the comments.
You can use the below code - adapted for your needs, based in this answer here - to save an image into Firestore.
Future Build() async {
String fileName = basename(_image.path);
StorageReference reference = storage.ref().child('image');
StorageUploadTask uploadTask = reference.putFile(fileName);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
String url = await taskSnapshot.ref.getDownloadURL();
imageUrl1 = url;
return url;
}
With the function written this way, you should be able to save the image from a specific path into your database. In addition to that, bear in mind that this code should be a starting point for you, as changes might be needed, considering variable names and locations.

flutter: upload a video to firebase storage and get the link

I tried to upload the video using image picker to firebase storage and get the link but there's a problem!
At first, this is my upload video method:
Future<void> uploadVideo() async {
await ImagePicker.pickVideo(source: ImageSource.gallery).then((value) {
setState(() {
_video = value;
});
});
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('revisionVideos/${Path.basename(_video.path)}');
StorageUploadTask storageUploadTask = storageReference.putFile(
_video, StorageMetadata(contentType: 'video/mp4'));
await storageUploadTask.onComplete;
print('Video Uploaded');
storageReference.getDownloadURL().then((value) {
setState(() {
_videoUrl = value;
});
});
}
When I upload the video, there was a photo (there's an error when trying to preview it) not a video.
And in the run tab:
W/StorageUtil(17625): no auth token for request
W/NetworkRequest(17625): no auth token for request
W/StorageUtil(17625): no auth token for request
W/NetworkRequest(17625): no auth token for request
D/UploadTask(17625): Increasing chunk size to 1048576
Although I edited the rules in the storage and cloud firestore, too.
Add: I didn't add authentication page for this application and the firebase project is linked to 2 android apps.

Resources