Home > Net >  How to get value of variable from function?
How to get value of variable from function?

Time:06-20

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 Images/dCP6WEESxfYNDIMqtt57n2BsxYf1?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.

CodePudding user response:

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

CodePudding user response:

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