Search code examples
flutterflutter-platform-channel

Flutter Platform Channels - Dealing with support of only one platform


I am writing a Flutter app which will run on Android and iOS devices. In this app I use Platform Channels for various purposes, including whether the user has confirmed a dialog, which is only displayed on iOS. So I get true or false back and on Android I can just continue to run my code without having to make this query.

I wonder what is the right way to deal with this platform method implementation that is only needed on one platform. Currently I have three possibilities in my head, which I suggest and would like to hear opinions about, but maybe there is also a completely different possibility.

Option 1:

Implement the platform method on Android and return a default value.

MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "CHANNEL").setMethodCallHandler { call, result ->
            if (call.method == "methodName") {
                result.success(true)
            }
        }

Option 2:

Do not execute platform method if it is the wrong platform with a query in the Dart code.

if (Platform.isAndroid) return true;
try {
  final bool permission = await platform.invokeMethod("methodName", {});
  return permission;
}

Option 3:

Do no implementation at all and return a default value via catching the PlatformException.

try {
  final bool permission = await platform.invokeMethod("methodName", {});
  return permission;
} on PlatformException catch (_) {
  return true;
}

Solution

  • There is one more option which I like most. Catch the platform exception in Flutter side of plugin and return default value in case platform is not supported.

    This makes client side code more readable. In case you would want to add support for specific platform, you can easily do it without making any change on the flutter side. Your clients won't have to do any refactoring in that case.