Created
April 28, 2023 06:30
-
-
Save vishhmakasana/9632be2b4988195e45777fa6b2b3e57f to your computer and use it in GitHub Desktop.
How to communicate with native code from flutter?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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) | |
}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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