类型"Future< String>"在flutter中类型转换中不是'String'类型的子类型 [英] type 'Future<String>' is not a subtype of type 'String' in type cast in flutter

查看:1305
本文介绍了类型"Future< String>"在flutter中类型转换中不是'String'类型的子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下功能从Web服务获取用户ID

I used following function to get user Id from web service

Future<String> getUserid() async {
  final storage = new FlutterSecureStorage();
  // Read value
  String userID = await storage.read(key: 'userid');
  return userID;
}

使用此功能时发生错误

类型'Future'不是类型转换类型'字符串'的子类型

type 'Future' is not a subtype of type 'String' in type cast

这是我尝试过的

otherFunction() async {

  final String userID = await getUserid();
 return userID;
}

Future<String> getUserid() async {
  final storage = new FlutterSecureStorage();
  // Read value
  String userID = await storage.read(key: 'userid');
  return userID;
}

print(otherFunction());

静止错误消息显示为

I/flutter(18036):未来"的实例

I/flutter (18036): Instance of 'Future'

推荐答案

您将需要等待.如果您完全不了解 Dart 中的Future,则应通读

You will need to await your function. If you are totally unaware of Future's in Dart, you should read through this comprehensive article.

Flutter 中,现在有两种方法可以处理这种情况.您要么想在其他常规函数中调用函数.在这种情况下,您可以将该功能标记为async或使用getUserid().then((String userID) {...}).如果要使用async,则还需要使用await:

In Flutter, there are now two ways to handle this case. Either you want to call your function in a regular other function. In that case, you would either mark that function as async or use getUserid().then((String userID) {...}). If you were to use async, you would need to use await as well:

otherFunction() async {
  ...
  final String userID = await getUserid();
  ...
}

但是,在Flutter中的 中,您很有可能希望在小部件的 build方法中使用您的值.在这种情况下,您应该使用 FutureBuilder :

However, in Flutter it is very likely that you want to use your value in the build method of your widget. In that case, you should use a FutureBuilder:

@override
Widget build(BuildContext context) {
  return FutureBuilder(future: getUserid(),
                       builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                         if (!snapshot.hasData) return Container(); // still loading
                         // alternatively use snapshot.connectionState != ConnectionState.done
                         final String userID = snapshot.data;
                         ...
                         // return a widget here (you have to return a widget to the builder)
                       });
}

这篇关于类型"Future&lt; String&gt;"在flutter中类型转换中不是'String'类型的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆