How to get value of variable from function? - flutter

I am trying to get value from a function and store it in a variable but I am getting null.
String imgUrl='';
getUrlSP() async {
SharedPreference preferences
=await SharedPreferences.getInstance();
String Url =
preferences.getString('imageUrl').toString();
setState(() {
imgUrl=Url;
});
print('Printing Image Url inside function:${imgUrl}');
}
outside function
print('Image Url :${imgUrl}');
The results I got in the terminal are
I/flutter (32164): Image Url :
I/flutter (32164): Image Url Stored in Prefs
is:https://firebasestorage.googleapis.com/v0/b/veeluser.appspot.com/o/User%20Images%2FdCP6WEESxfYNDIMqtt57n2BsxYf1?alt=media&token=d864a502-209f-4262-9860-b9d4d3222091
_As from the above results that I got in terminal I am not getting the value of imageUrl outside the function._As I am new to flutter so if there is an error or there is any other solution please share it.

That is expected. since your getUrlSP function is declared as async, you'll need to use await when calling it to ensure it completes (and sets imgUrl) before the rest of your code runs.
So:
await getUrlSP();
print('Image Url :${imgUrl}');
I recommend taking the Flutter codelab Asynchronous programming: futures, async, await

should be used setString() to add a string value to the shared preferences .
Example :
String imgUrl='';
getUrlSP() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('imageUrl', imgUrl);
print('==> ${imgUrl} <==');
}

Related

remove data inside the key in SharedPreferences

im using flutter 2.8.1 and shared_preferences: ^2.0.13
i build a todoapp with sharedpreferences all works fine from storing data to localstorage and load the data in initState but now i want to delete spesific item/selected item in the localstorage but when i use prefs.remove('key'); all the item is removed, i only want to remove the selected item only.
let me know if you need more information with the code.
the key contain this, for example i want to remove item with id: 64, not the key
I/flutter ( 9643): [{"id":64,"set_name":"asd"},{"id":55,"set_name":"asdasdwqe"}]
remove function code
Future deleteData() async {
final SharedPreferences prefs = await _prefs;
prefs.remove('sets');
setState(() {});
}
save function code
Future saveData() async {
final SharedPreferences prefs = await _prefs;
List items = c.setList.map((item) => item.toJson()).toList();
prefs.setString('sets', jsonEncode(items));
}
There isn't easy way but to overwrite new values over old value. This is one of the drawbacks of using SharedPreferences over traditional databases.
You will have to read the data from sharedPrefs, remove the concerned value and save it back to sharedPrefs.

Flutter shared_preferences not persistent?

I have been using shared_preferences in flutter, was working fine until now. Suddenly it stopped working, both in iOS and Android. I debugged it step by step and it stores data to pref and while app is on, data still persists, but after hot restart _preferencecache always is empty. How can I solve this? (version is 0.5.12)
When user logs in I save the user_id:
final prefs = await SharedPreferences.getInstance();
final userData = json.encode(
{
'user_id': userID,
},
);
prefs.setString('userData', userData);
Later, when user restarts again:
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('userData')) {
// print("no user data in shared preference");
return false;
}
But the abpve function returns false, that's the issue, I checked the previous version of shared_preferences as well, but no solution.
you have do it like this
final prefs = await SharedPreferences.getInstance();
final data = prefs.getString("userData");
if(data != null){
final userData = json.dncode(userData);
}
I realized I was clearing my shared preferences some where in my app and I had forgotten about it. Please check every where in your code for sharedPreferences.clear(). You never know.
I assume that somewhere in your code, you faced this error and as a quick solution, you had added SharedPreferences.setMockInitialValues({}); in your code, which should be the reason (other than sharedPreferences.clear()).
The SharedPreferences.setMockInitialValues({}); is the thing that is preventing data to persist between sessions.
A quick getaway is to add a try-catch block to your code. Somethink like the following:
try {
prefs.getInt(YOUR_KEY_HERE);
} catch (e) {
SharedPreferences.setMockInitialValues({});
}
But this isn't a conventional fix to this problem, I recommend checking out this answer by Siddharth Agrawal.

getting image from firebase storage not working

i am new to flutter and i am trying to make an app which take data from user and make a widget out of it (Classified ads), so far everything is working. but the images from firebase storage is not loading, i have the image url in database ,
for the name its working
Text(snapshot.data.documents[index]['item Name'],),
but for images it gives error
index == null
? Image.asset('assets/afghan.png')
: Image.network(snapshot.data.documents[index]['image 1 Url'],),
the ERROR
Invalid argument(s): No host specified in URI file:///data/user/0/com.example.thisOne/cache/image_picker1382407617041908118.jpg
Change this:
Image.network(snapshot.data.documents[index]['image 1 Url'],)
into this:
Image.file(snapshot.data.documents[index]['image 1 Url'],)
The image url is not valid, this is how you have to save the image in the database:
StorageTaskSnapshot snapshot = await storage
.ref()
.child("images/$imageName")
.putFile(file)
.onComplete;
if (snapshot.error == null) {
final String downloadUrl =
await snapshot.ref.getDownloadURL();
await Firestore.instance
.collection("images")
.add({"url": downloadUrl, "name": imageName});
setState(() {
isLoading = false;
});
You are not saving it correctly to the database, you need to get the downloadUrl from firebase storage which will contain a valid url (https://...) and add it to Firestore. Then you can use Image.network

Flutter SharedPreferences resetting the data

I have this code in flutter using SharedPreferences to store data:
Future<bool> setUserStatus(String userStatus) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('userStatus', 'active');
return true;
}
Is it possible to use this same setUserStatus in another file, which will get this main.dart imported to it, and change the SharedPreferences data to something else based on the actions taken in the other file
Do this,
await setUserStatus( status );
if you don't want to wait for the future to complete just remove await from the begining.
Calling prefs.clear()will erase all the preferences set on the device. so I would suggest not to use that here. If you want to clear a particular preference just use
prefs.remove(key) or prefs.setString(key,null)

How to update value inside shared preferences in flutter

actually when saving data inside shared preferences.. I am using this code
add() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('data', "ok");
}
but, is there a way to update the value of data for example I want to change ok into fine
because when I try to re-save my data using that code... and call it using prefs.getString('data'); it always shows the old data not the update one
Just reassign it again
prefs.setString('data', "fine");
//shared-preferences
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('profileImg', data1['imagePath']);
prefs.setString('un', data1['username']);