异步函数的颤振未来返回类型问题



我有一个奇怪的错误与我的颤振代码涉及一个Future<T>返回类型。我有一段相当简单的代码,它向后端发出get请求,并使用.then子句处理返回。一切都很好,只要我添加onError来处理可能的回错误(即403/404错误),我就有一个关于返回类型的问题,引用Future<dynamic>不能在我期望Future<String?>时返回,尽管onError总是返回null

有什么办法可以解决这个问题吗?提前感谢!

代码:

Future<String?> getUserStatus(String id) async {
return requestManager.get("/users/$id/status")
.then((response) {
final dynamic userStatus =
(response as Map<String, dynamic>)["status"];
if (unsubStatus == null) {
return Future.value();
}
return Future.value(userStatus.toString());
}, onError: (error) {
print("An error occured when reading response : $error");
return null;
}).onError((error, stackTrace) => Future.value("NoStatus")); // I also tried to return null
}

错误:

A value of type 'Future<dynamic>' can't be returned from an async function with return type 'Future<String?>'.
- 'Future' is from 'dart:async'.
}).onError((error, stackTrace) => Future.value("NoStatus"));

我建议使用tryawait,而不是使用thenonError:

Future<String?> getUserStatus(String id) async {
try {
var response = await requestManager.get("/users/$id/status");
final dynamic unsubStatus = (response as Map<String, dynamic>)["status"];
if (unsubStatus == null) {
return null;
} else {
return unsubStatus.toString();
}
} catch (e) {
print("An error occured when reading response : $e");
return null;
}
}
Future<String?> getUserStatus(String id) async {
final result =await requestManager.get("/users/$id/status");
final dynamic userStatus = (response as Map<String, dynamic>)["status"];
if (unsubStatus == null) {
return Future.value();
}
return Future.value(userStatus.toString());
}

相关内容

  • 没有找到相关文章

最新更新