[英]Flutter/Dart return Future<String?>
I have a function, which I want to return a Future of String or null.我有一个函数,我想返回一个 Future of String 或 null。 For simplicity, the function will return null if delay for 1 second is success, or else it will return "failed";
为简单起见,如果延迟1秒成功,该函数将返回null,否则将返回“失败”;
However;然而; I got the
我拿到
Future<String?> fcn(String str) {
return Future.delayed(const Duration(seconds: 1)).then((value) {
return null;
}).onError((error, stackTrace) {
return "failed"; // The return type 'String' isn't a 'FutureOr<Null>', as required by the closure's context.
});
}
Try to use onError
as parameter of then
method:尝试使用
onError
作为then
方法的参数:
Future<String?> fcn(String str) {
return Future.delayed(const Duration(seconds: 1)).then((value) {
return null;
}, onError: (error, stackTrace) {
return "failed";
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.