【Flutter × Swift】The simplest way to use Method Channel.

Overview

I'm going to write about the simplest way to use Flutter Method Channel to call Swift code from Flutter.

Just 2 files that we need to use.

  • ios_method_channel.dart
  • AppDelegate.swift

Completed files

I show 2 completed files at first.

ios_method_channel.dart


import 'package:flutter/services.dart';

class IosMethodChannel {
  void execute() {
    MethodChannel('package.hoge/ios').invokeMethod("hogeFunction");
  }
}

AppDelegate.swift

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      // register method channel
      let _controller = window?.rootViewController as! FlutterViewController
      let _channel = FlutterMethodChannel(
          name: "package.hoge/ios",
          binaryMessenger: _controller.binaryMessenger)

      _channel.setMethodCallHandler({
          (call: FlutterMethodCall, result: FlutterResult) -> Void in
          switch(call.method) {
          case "hogeFunction":
              print("called!!!")
          default:
              result("No Method")
              return
          }
      })
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Description

ios_method_channel.dart

We can use MethodChannel#invokeMethod to call Swift code.

The argument of MethodChannel constructor is the name of channel.
The argument of MethodChannel#invokeMethod is the name of function which want to call.

So, This time I set "package.hoge/ios" and "hogeFunction" for each.

"package.hoge/iOS" is constructed like "package.${your application name}/ios".

This application name which these example codes are written is "hoge".

That's why I set hoge in front of "/ios".

MethodChannel('package.hoge/ios').invokeMethod("hogeFunction");

AppDelegate.swift

We need to register method channel in this file.

      let _controller = window?.rootViewController as! FlutterViewController
      let _channel = FlutterMethodChannel(
          name: "package.hoge/ios",
          binaryMessenger: _controller.binaryMessenger)

And, the function which we want to call need to be set like following.

_channel.setMethodCallHandler({
          (call: FlutterMethodCall, result: FlutterResult) -> Void in
          switch(call.method) {
          case "hogeFunction":
              print("called!!!")
          default:
              result("No Method")
              return
          }

Shion Maruko

A mobile engineer from Japan.
I've just been studying English.
So, I'm pleased if you let me know my mistakes which I made in articles.