如何从函数中获取变量值?
我正在尝试从函数中获取值并将其存储在变量中,但我的效果为无效。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是预期的。由于您的
geturlsp
函数被声明为async
,因此您需要在调用它时使用等待
确保其完成(并设置SETS
imgurl
)在您的其余代码运行之前。因此:
我建议您服用颤动的codeLab asynchronous编程:期货,期货,异步,等待
That is expected. since your
getUrlSP
function is declared asasync
, you'll need to useawait
when calling it to ensure it completes (and setsimgUrl
) before the rest of your code runs.So:
I recommend taking the Flutter codelab Asynchronous programming: futures, async, await
应使用
setstring()
将字符串值添加到共享首选项中。例子 :
should be used
setString()
to add a string value to the shared preferences .Example :