Catching PlatformException in async function in flutter

Viewed 682

Background

I am trying to fetch a booking document from Firestore inside the initState() method of my State. This is also my first time using flutter/dart, so apologies if I am making a very rookie mistake.

Problem

When I run the get() method, an async function that returns a Future<DocumentSnapshot>, an error is thrown. I am trying to catch and handle this error. The error is an 'insufficient permissions' error which I intend to get.

My code

class _MyHomePageState extends State<MyHomePage> {
  final firestoreInstance = Firestore.instance;
  Future<DocumentSnapshot> _futureBooking;

  @override
  void initState() {
    super.initState();

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

Results

The catch block is never entered, and the app always crashes when making the get() call.

enter image description here

Any help would be appreciated!

1 Answers

You can't catch errors with try-catch blocks when you're not using await.

To catch errors in the way that you want to call this future function, use the catchError method of the Future class. Ex.

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

Alternatively, you could still use try-catch and with await, while still maintaining your functionality. Ex.

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();
}
Related