类型"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)
});
}