Search code examples
androidflutterkotlinflutter-platform-channelflutter-engine

Kotlin (MainActivity.kt) - Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type FlutterEngine?


e: C:\flutter\POC\contacts\android\app\src\main\kotlin\com\example\contacts\MainActivity.kt: (98, 58): Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type FlutterEngine?

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':app:compileDebugKotlin'.

A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction Compilation error. See log for more details

  • Try:

Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

BUILD FAILED in 11s Exception: Gradle task assembleDebug failed with exit code 1


  • I'm trying to get the Contacts of a user using platform channels (not plugins) integrated with flutter.
  • i added the platform channel sources in MainActivity.kt .
  • i added the permission in AndroidManifest.xml.
  • I added the UI part in contacts.dart.
  • I attached the source images, i tried.

I want to access the contacts of the user using platform channels. This is my Ui code file. This is my MainActivity.kt file.


Solution

  • In Kotlin (and many other languages) there's the notion of nullable and not null types. In your code you have flutterEngine being declared as nullable, but you use it as a not null type, hence the compile error.

    You need to describe exactly what should happen when the object flutterEngine is null and also when it isn't null. One way would be to use the let scope function:

    flutterEngine?.let { notNullFlutterEngine ->
        // Use notNullFlutterEngine as you previously did.
        val channel = MethodChannel(notNullFlutterEngine.dartExecutor.binaryMessenger, "com.example.contacts")
        channel.invokeMethod("getContacts", contacts)
    } 
    

    I highly recommend reading the previously linked pages in the documentation.