在Flutter中的异步函数中捕获PlatformException

时间:2020-07-26 01:57:05

标签: android flutter dart google-cloud-firestore

背景

我正在尝试通过 for (){if (abb.iscurrentlyy() || abb.islately()) { if (reqFiles != null) { for (int i = 0; i < reqFiles.length; i++) { Future<ExecResult> lcukv = executor.submit(worker); executionFutureException.add(lcukv); } } } else { // do if condition is false. } } 的{​​{1}}方法内的Firestore获取预订文件。 这也是我第一次使用flutter / dart,所以如果我犯了一个非常菜鸟的错误,就此道歉。

问题

当我运行initState()方法和返回State的{​​{1}}函数时,将引发错误。我正在尝试捕获并处理此错误。该错误是我打算得到的“权限不足”错误。

我的代码

get()

结果

从未输入async块,并且在进行Future<DocumentSnapshot>调用时应用总是崩溃。

enter image description here

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

不使用try-catch时,无法捕获await块的错误。

要以调用此Future函数的方式捕获错误,请使用Future类的catchError方法。 例如。

_futureBooking = firestoreInstance
  .collection('bookings')
  .document('1Twgjq5YTe3Oa12wwbs1')
  .get()
  .catchError(
    (err) {
      print("error fetching from firestore: $err");
    }
  );

或者,您仍然可以使用try-catchawait并保持功能。例如。

Future<DocumentSnapshot> wrapperFunction() async {
  try {
    return await firestoreInstance
      .collection('bookings')
      .document('1Twgjq5YTe3Oa12wwbs1')
      .get();
  } catch (err) {
    print("error fetching from firestore: $err");
  }
}

@override
void initState() {
  super.initState();
  _futureBooking = wrapperFunction();
}