How to call a Dart method from Kotlin using the pigeon library in Flutter

51 views Asked by At

I'm working on a Flutter app that uses the pigeon library to interface with the native Spotify SDK. I have defined a SpotifyAPICallback interface in the pigeon file, which contains the onAuthCode and onAuthFailure methods that should be implemented on the Dart side.

Here's the relevant code:

Pigeon Declaration File (pigeons/spotify_api.dart):

import 'package:pigeon/pigeon.dart';

class SpotifyAuthCodeParams {
  late String clientId;
  late String redirectUri;
  late String scope;
}

@ConfigurePigeon(
  // ... pigeon configuration
)

@FlutterApi()
abstract class SpotifyAPICallback {
  void onAuthCode(String spotifyAuthCode);
  void onAuthFailure(String error);
}

@HostApi()
abstract class SpotifyAPI {
  void openSpotifyConsentView(SpotifyAuthCodeParams params);
}

Kotlin Implementation (SpotifyAPIImpl.kt):

class SpotifyAPIImpl(val engine: FlutterEngine) : SpotifyAPI {
    private var apiCallback: SpotifyAPICallback? = null
    // ...

    override fun openSpotifyConsentView(params: SpotifyAuthCodeParams) {
        // ... open Spotify consent view
    }

    private fun authFlow(resultCode: Int, data: Intent?) {
        // ...
        when (response.type) {
            AuthorizationResponse.Type.CODE -> {
                println("Going back to flutter...")
                apiCallback!!.onAuthCode(response.code) // This is not being called on the Dart side
            }
            else -> apiCallback!!.onAuthFailure(response.error) {}
        }
    }
}

Dart Implementation (SpotifyAPICallbackImpl.dart):

class SpotifyAPICallbackImpl implements SpotifyAPICallback {
  @override
  void onAuthCode(String spotifyAuthCode) {
    print("Auth code from flutter: $spotifyAuthCode");
  }

  @override
  void onAuthFailure(String error) {
    throw UnimplementedError();
  }
}

On the Kotlin side, I'm able to receive the Spotify auth code successfully. However, when I try to call the onAuthCode method from the Kotlin side, it's not being called on the Dart side.

I've tried adding a setCallbackInstance method to the SpotifyAPI interface to pass the SpotifyAPICallbackImpl instance, but pigeon doesn't allow using @FlutterApi classes in the @HostApi interface.

Can someone please guide me on how to properly set up the communication between the Dart and Kotlin layers using the pigeon library, so that I can call the onAuthCode method from the Kotlin side and have it executed on the Dart side?

Any help or suggestions would be greatly appreciated.

0

There are 0 answers