Search code examples
javaandroidflutterdartsdk

error: pattern matching in instanceof is not supported in -source 8, in Flutter


I am encountering an error while running my Flutter application. The error message I receive is:

C:\Users\Intel\AppData\Local\Pub\Cache\hosted\pub.dev\firebase_core-2.32.0\android\src\main\java\io\flutter\plugins\firebase\core\GeneratedAndroidFirebaseCore.java:45:

error: pattern matching in instanceof is not supported in -source 8
    if (exception instanceof FlutterError error) {
                                          ^
  (use -source 16 or higher to enable pattern matching in instanceof)
1 error


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':firebase_core:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

I am using Java 16, which should support pattern matching with instanceof. The error points to a line in GeneratedAndroidFirebaseCore.java:

  protected static ArrayList<Object> wrapError(@NonNull Throwable exception) {
    ArrayList<Object> errorList = new ArrayList<Object>(3);
    if (exception instanceof FlutterError error) {
        errorList.add(error.code);
      errorList.add(error.getMessage());
      errorList.add(error.details);
    } else {
      errorList.add(exception.toString());
      errorList.add(exception.getClass().getSimpleName());
      errorList.add(
          "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception));
    }
    return errorList;
  }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

Solution

  • You are running Java 16 but there are compileOptions and they are defined with setting 1_8, that makes the compiler Java 8 compatible. All these inconsistencies should be resolved at the project level, compiler level, and build configuration level.

    compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
    }
    

    Change it to :

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }
    

    Note : This will changes what version of the Java language you can use to create your project.

    Reference links