【问题标题】:Flutter/Dart return Future<String?>Flutter/Dart 返回 Future<String?>
【发布时间】:2021-10-18 19:34:29
【问题描述】:

我有一个函数,我想返回一个字符串的 Future 或 null。为简单起见,如果延迟1秒成功,该函数将返回null,否则返回“失败”;

但是;我得到了

  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.
    });
  }

【问题讨论】:

  • return Future.value("failed"); 呢?
  • 使用async/await。它更简单。

标签: flutter dart dart-null-safety


【解决方案1】:

尝试使用onError作为then方法的参数:

Future<String?> fcn(String str) {
  return Future.delayed(const Duration(seconds: 1)).then((value) {
    return null;
  }, onError: (error, stackTrace) {
    return "failed";
  });
}

或者方法catchError:

Future<String?> fcn(String str) {
  return Future.delayed(const Duration(seconds: 1)).then((value) {
    return null;
  }).catchError((error, stackTrace) {
    return "failed";
  });
}

【讨论】:

猜你喜欢
  • 2020-01-05
  • 2019-05-18
  • 1970-01-01
  • 2021-02-06
  • 2021-03-04
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多