Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 为什么可以';t用“捕获异常”;“捕捉错误”;用飞镖?_Dart_Future - Fatal编程技术网

Dart 为什么可以';t用“捕获异常”;“捕捉错误”;用飞镖?

Dart 为什么可以';t用“捕获异常”;“捕捉错误”;用飞镖?,dart,future,Dart,Future,测试: void testAs()异步{ 试一试{ 字符串b=等待测试(); 印刷品(b); }捕获(e){ 打印(“1等待错误”); } test().then((值)=>print(值)).catchError(){ 打印(“2则错误”); }); } 未来测试(){ 列表bb=[“2222”]; 返回未来价值(bb[1]); } 1等待错误 RangeError(索引):无效值:只有有效值为0:1 为什么无效? 如果我想通过“then”来处理“future”,我应该如何捕获异常而不让它抛

测试:

void testAs()异步{
试一试{
字符串b=等待测试();
印刷品(b);
}捕获(e){
打印(“1等待错误”);
}
test().then((值)=>print(值)).catchError(){
打印(“2则错误”);
});
}
未来测试(){
列表bb=[“2222”];
返回未来价值(bb[1]);
}
1等待错误
RangeError(索引):无效值:只有有效值为0:1
为什么无效?
如果我想通过“then”来处理“future”,我应该如何捕获异常而不让它抛出。

谢谢朋友们,最后一个问题已经解决了,可以通过在
test()
方法中添加
async
wait
标志来解决这个问题

但是有一个新问题,现在我使用正确的代码,发现它只能打印一次。为什么它不能打印“然后成功”,然后程序结束 ,修改如下:

void testAs() async {
  try {
    String b = await test();
    print(b);
  } catch (e) {
    print("1 await error");
  }
  test().then((value) => print(value)).catchError(() {
    print("2 then  error");
  });
}

Future<String> test() {
  List<String> bb = ["2222"];
  return Future.value(bb[1]);
}





 1 await error
 RangeError (index): Invalid value: Only valid value is 0: 1
void testAs()异步{
试一试{
等待测试();
打印(“等待成功”);
}捕获(e){
打印(“等待错误”);
}
test().then((值)=>print(“then success”).catchError((e){
打印(“然后出错”);
});
}
Future test()异步{
列表bb=[“2222”];
返回等待未来。值(bb[0]);
}

print:wait success

,因为在本例中是catch by catch语句。你需要折射你的溶液。调用
test()
时,甚至在调用
之前,会同步抛出该错误。只需使用
async
/
wait
并让它在您使用
try
/
catch
时为您完成所有工作。只需将
test
函数的返回语句设置为
return bb[0]。这是一样的,只是效率更高。我明白你的意思,但现在我不明白为什么“那么成功”没有打印出来?它们之间只能打印其中一个。我想打印两个“成功”?如果您等待由
test()创建的未来,那么(……)
,那么您的
testAs
函数在打印“then success”之前不会返回。我猜事情就是这样。我明白,谢谢~
void testAs() async {
  try {
    await test();
    print("await success");
  } catch (e) {
    print("await error");
  }

  test().then((value) => print("then success")).catchError((e) {
    print("then  error");

  });
}

Future<String> test() async{
  List<String> bb = ["2222"];
 
  return await Future.value(bb[0]);

}