'Future<String>' 类型不是 Flutter 中类型转换中的 'String' 类型的子类型

sam*_*ath 8 dart flutter

我使用以下函数从 Web 服务获取用户 ID

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

使用此功能时发生错误

类型“未来”不是类型转换中“字符串”类型的子类型

这是我试过的

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());
Run Code Online (Sandbox Code Playgroud)

仍然错误消息显示为

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

cre*_*not 12

您将需要等待您的功能。如果您完全不知道Dart 中Future's ,您应该通读这篇综合文章

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

otherFunction() async {
  ...
  final String userID = await getUserid();
  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,在 Flutter 中,您很可能希望在小部件的build方法中使用您的值。在这种情况下,您应该使用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)
                       });
}
Run Code Online (Sandbox Code Playgroud)

  • 我只想返回值而不创建小部件。我怎样才能做到这一点 ? (2认同)