Cathing exception is getting error in flutter. The argument type 'Object' can't be assigned to the parameter type 'Exception'

Viewed 371

I am new on flutter. The Flutter version is 2.5.0

I have a class that name is SubmissionFailed.

class SubmissionFailed extends FormSubmissionStatus {
  final Exception exception;

  SubmissionFailed(this.exception);
}

When I try to call this class in a try/catch block it gives an error.

Error is : The argument type 'Object' can't be assigned to the parameter type 'Exception'

Here is the try/catch block:

enter image description here

I do not understand what is wrong?

2 Answers

It's because the argument exception doesn't have a type in the catch block declaration, so Flutter keeps it safe by considering it to be of type Object. Why? Just like in Java, if no extended class is defined, all classes in Dart automatically extend the class Object. Basically, every single class in Dart inherits (directly or indirectly) from Object.

The SubmissionFailed constructor has one parameter of type Exception, which means you can't pass an Object or any other type, it has to be of Exception type.

To fix this, just cast it like this:

try {
  // code
} catch (exception) {
  yield state.copyWith(formStatus: SubmissionFailed(exception as Exception));
}

You can cast your object as Exception for using it

Related