【问题标题】:A value of type 'Null' can't be returned by the 'onError' handler“onError”处理程序无法返回“Null”类型的值
【发布时间】:2021-08-28 05:03:32
【问题描述】:

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

使用try catch

 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?

【问题讨论】:

  • someFuture 的类型需要能够返回null,因为catchError 只是获得与someFuture 相同的返回类型。
  • 使 someFuture 能够返回 null 在运行时会产生相同的错误,而之前它会在编译时发出警告。

标签: flutter dart asynchronous


【解决方案1】:

这个例子适用于我让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
}

【讨论】:

    【解决方案2】:

    你应该指定 someFuture() 签名,它可能返回Future&lt;bool&gt;

    Future<bool> someFuture() async
    

    方法catchError 必须返回调用它的相同未来类型。您可以通过将值转发到 then 并将其转换为 Future&lt;bool?&gt; 来克服这个问题:

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

    }

    【讨论】:

      猜你喜欢
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      相关资源
      最近更新 更多