Skip to content

Instantly share code, notes, and snippets.

@VivekGoswami
Created August 3, 2023 13:41
Show Gist options
  • Save VivekGoswami/98ab90f0ea43ade626732827dde97703 to your computer and use it in GitHub Desktop.
Save VivekGoswami/98ab90f0ea43ade626732827dde97703 to your computer and use it in GitHub Desktop.
Communicate Between Flutter and Native iOS Code Using Platform Channel
// iOS Native
import Flutter
import UIKit
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
registerMethodChannel()
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
// MARK: - Flutter way to call native iOS function
private func registerMethodChannel() {
let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
let methodChannel = FlutterMethodChannel(name: "flutter_call",
binaryMessenger: controller.binaryMessenger)
methodChannel.setMethodCallHandler {
[weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in
if let weakSelf = self {
weakSelf.handle(call, result: result)
}
}
}
private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "getDeviceModel" {
result("iPhone 14")
} else {
result(FlutterMethodNotImplemented)
}
}
}
// Flutter
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _deviceModel = 'Unknown Model.';
static const platformChannel = MethodChannel('flutter_call');
Future<void> _getDeviceModel() async {
String model;
try {
final String result =
await platformChannel.invokeMethod('getDeviceModel');
model = result;
} catch (e) {
model = "Can't fetch the method: '$e'.";
}
setState(() {
_deviceModel = model;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_deviceModel,
),
ElevatedButton(
onPressed: _getDeviceModel,
child: const Text('Get Device Model'),
)
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment