如何从函数中获取变量值?

发布于 2025-02-08 21:56:17 字数 901 浏览 2 评论 0原文

我正在尝试从函数中获取值并将其存储在变量中,但我的效果为无效。

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}');
}

户外函数

print('Image Url :${imgUrl}');

我在终端中获得的结果是

i/flutter(32164) ):图像URL:

i/flutter(32164):存储在prefs中的图像URL IS: https://firebasestorage.googleapis.com/v0/b/veeluser.appspot.com/o/user%20images2fdcp6weesxfyxfyxfyndimqtt57n2bbsxyf1bbsxyf1? B9D4D3222091

_从我在终端获得的上述结果中我没有在功能之外获得ImageUrl的值。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

过气美图社 2025-02-15 21:56:17

那是预期的。由于您的geturlsp函数被声明为async,因此您需要在调用它时使用等待确保其完成(并设置SETS imgurl)在您的其余代码运行之前。

因此:

await getUrlSP();
print('Image Url :${imgUrl}');

我建议您服用颤动的codeLab asynchronous编程:期货,期货,异步,等待

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

沩ん囻菔务 2025-02-15 21:56:17

应使用setstring()将字符串值添加到共享首选项中。

例子 :

String imgUrl='';
getUrlSP() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('imageUrl', imgUrl);
print('==> ${imgUrl} <==');
}

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} <==');
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文