【问题标题】:Unhandled Exception: type 'Null' is not a subtype of type 'Future<Never>'未处理的异常:“Null”类型不是“Future<Never>”类型的子类型
【发布时间】:2021-08-26 01:15:21
【问题描述】:

我已尝试将 Future 变为可为空的以及字符串,但出现问题需要帮助吗?

floatingActionButton: FloatingActionButton(
    onPressed: () {
      getName().then((value) {
        print(value);
        throw("error!!!!!");
      }).catchError((error) => print(error.toString()));
    },
    child: Icon(Icons.add),
),

在我班级某处的构建方法之外

Future<String> getName() async =>'Some String';

【问题讨论】:

  • 我只是想处理 .catch 中 then () 中的错误,为什么它告诉我
  • 如果您告诉我们问题出在哪一行,将会有所帮助。复制您问题中的整个错误消息。
  • 我的问题是为什么catchError不能处理我的异常

标签: flutter dart dart-null-safety


【解决方案1】:

所以这修复了我的代码

floatingActionButton: FloatingActionButton(
        onPressed: () => getName().then((value){
          //  the return type of an error handler is not acceptable
          // as the value of future.
          // after lambda expression is executed it gone so
          // we wouldn't know where the error came from
          // because also the return type is dynamic so we 
          //can't get to a datatype interface so it may be null since it's dynamic 
          if(value is FutureOr) {
            throw("error");
          }
        }).catchError((error) =>  print(error.toString()) ) ,

【讨论】:

    【解决方案2】:

    你可以试试这个

    getName().then((value) {
                    print(value);
                    throw ("error!!!!");
                  }).catchError((error) {
                    print("catch error :: " + error.toString());
                  });
    

    该代码打印catch error :: error!!!!。这是你想要的吗?

    【讨论】:

    • 我想在 .catchError() 中捕获 then() 异常,这就是我在 then 回调中抛出异常的原因
    • 对我不起作用,除非我有条件检查值 FutureOr
    猜你喜欢
    • 2020-07-08
    • 2021-01-12
    • 2020-11-19
    • 2019-11-10
    • 2021-12-28
    • 2022-11-29
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多