Skip to content

Instantly share code, notes, and snippets.

@vishhmakasana
Created April 28, 2023 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishhmakasana/9632be2b4988195e45777fa6b2b3e57f to your computer and use it in GitHub Desktop.
Save vishhmakasana/9632be2b4988195e45777fa6b2b3e57f to your computer and use it in GitHub Desktop.
How to communicate with native code from flutter?
/// iOS Swift Code
import Flutter
let CHANNEL = "com.example.native_calls"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let methodChannel = FlutterMethodChannel(name: CHANNEL, binaryMessenger: self.binaryMessenger)
methodChannel.setMethodCallHandler({ [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
guard call.method == "getNativeString" else {
result(FlutterMethodNotImplemented)
return
}
let nativeString = "Hello from native code!"
result(nativeString)
})
}
}
/// Flutter Code
import 'package:flutter/services.dart';
final platform = MethodChannel('com.example.native_calls');
Future<String> getNativeString() async {
String result = await platform.invokeMethod('getNativeString');
return result;
}
/// Android Code
class MainActivity: FlutterActivity() {
private val CHANNEL = "com.example.native_calls"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
if (call.method == "getNativeString") {
val nativeString = "Hello from native code!"
result.success(nativeString)
} else {
result.notImplemented()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment