首页 > 解决方案 > “onError”处理程序无法返回“Null”类型的值

问题描述

我无法从 dart Future 的 catchError 处理程序返回 null。我可以使用 try catch 来做到这一点,但我需要使用 then catchError。

使用尝试捕获

 Future<bool?> test() async {
    try {
      return await someFuture();
    } catch (e) {
      return null;
    }
  }

// Works without error

但是当使用 then catchError

  Future<bool?> test() {
    return someFuture().catchError((e) {
      return null;
    });
  }

// Error: A value of type 'Null' can't be returned by the 'onError' handler because it must be assignable to 'FutureOr<bool>'

如果使用 then 和 catchError 遇到一些错误,如何返回 null?

标签: flutterdartasynchronous

解决方案


这个例子适用于我someFuture返回的地方bool?

Future<bool?> someFuture() async {
  throw Exception('Error');
}

Future<bool?> test() {
  return someFuture().catchError((Object e) => null);
}

Future<void> main() async {
  print('Our value: ${await test()}'); // Our value: null
}

如果你不能改变someFuture方法的返回类型,我们也可以这样做,我们基于另一个未来创建一个新的未来,但我们指定我们的类型是可空的:

Future<bool> someFuture() async {
  throw Exception('Error');
}

Future<bool?> test() {
  return Future<bool?>(someFuture).catchError((Object e) => null);
}

Future<void> main() async {
  print('Our value: ${await test()}'); // Our value: null
}

推荐阅读