Flutter — Communicate with Android activity or iOS ViewController through method channel

import 'dart:async';
import 'package:flutter/services.dart';
static const platform = const MethodChannel("test_activity");
_getNewActivity() async {
try {
await platform.invokeMethod('startNewActivity');
} on PlatformException catch (e) {
print(e.message);
}
}
new MaterialButton(
child: const Text('Open Screen'),
elevation: 5.0,
height: 48.0,
minWidth: 250.0,
color: Colors.blue,
textColor: Colors.white,
onPressed: () {
_getNewActivity();
})
class HomeActivity : FlutterActivity() {
private val CHANNEL = "test_activity"

override fun
onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler(
object : MethodCallHandler {
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if(call.method.equals("startNewActivity")) {
startNewActivity()
}
}
})
}

private fun startNewActivity() {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
}
let flutterChannel = FlutterMethodChannel.init(name: "test_activity", binaryMessenger: flutterViewController);
flutterChannel.setMethodCallHandler { (flutterMethodCall, flutterResult) in
if flutterMethodCall.method == "startNewActivity" {
UIView.animate(withDuration: 0.5, animations: {
self.window?.rootViewController = nil

let viewToPush = SecondViewController()

let navigationController = UINavigationController(rootViewController: flutterViewController)

self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.makeKeyAndVisible()
self.window.rootViewController = navigationController
navigationController.isNavigationBarHidden = true
navigationController.pushViewController(viewToPush, animated: true)
})
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store