Flutter Method Channel

Flutter Platform Channels

As all of us understand that the whole lot in Flutter is a Widget and the way it eases the manner of creating

Beautiful mobile, web, windows, Linux, mac os, or even embedded packages with ease.

And it does those UI’s in a superb manner that it makes it a laugh to apply the use of flutter

But you would possibly have requested approximately what in case you need extra than drawing pixels on a display screen device

As Dart does now no longer assemble to Android’s Dalvik bytecode, and additionally the identical element with Objective-C. This way that the Dart code is written and it doesn’t have a direct get right of entry to the platform-unique APIs of iOS Cocoa Touch and the Android SDK.

For the use of platform-unique APIs something like

  • Sensors
  • Specific digital digicam features
  • Geo-Location
  • Device information
  • Persisting data

And a great deal extra… however, flutter doesn’t go away you while not having a manner to get right of entry to those features

The Flutter group selected a one-of-a-kind method. It doesn’t do all that a great deal, however, it’s miles simple, versatile, and absolutely on your hands.

And right here comes the position of the Flutter Platform Channel or (Channel Methods)

As in step with the documentation:

Flutter makes use of a bendy device that permits you to name platform-unique APIs in a language that works at once with the one’s APIs:

  • Kotlin or Java on Android
  • Swift or Objective-C on iOS
  • C++ on Windows
  • Objective-C on macOS
  • C on Linux

Flutter’s integrated platform-unique API aid doesn’t depend upon code generation, however as a substitute for a bendy message-passing style.

So First of all, Flutter is hosted thru a way of the method of a near automaton or iOS app. The Flutter elements of the app are wrapped in massive platform-unique factors alongside the read-on automaton and UIViewController on iOS. as a consequence at a comparable time as Flutter invites you to install writing your app in Dart, you will be capable of doing as a respectable get or as little or no in Java/Kotlin or Objective-C/Swift as you please withinside the host app, strolling straight away on top of platform-unique APIs.

Second, platform channels deliver a smooth mechanism for speaking among your Dart code and consequently the platform-unique code of your host app. this way you will be cabin a position to expose a platform employer for your host app code and the function it invoked from the Dart side. Or vice versa.

And third, plugins make it manageable to shape a Dart API backed thru a way of the method of an automaton implementation written in Java or Kotlin and an iOS implementation written in Objective-C or Swift — and package deal that up as a Flutter/Android/iOS triple pasted alongside the usage of platform channels. In this way, you could reuse, share, and distribute your deal but Flutter needs to use a specific platform API.

Platform channels API

For maximum-use instances, you may probably rent method channels for platform communication. But because of the reality that lots of their houses are derived from the much less complex message channels and from the underlying binary messaging foundations, I’ll start there.

And right here we are able to display an instance of creating a platform-unique functionality

Using platform channels API:

Flutter lets us call platform-specific APIs available in Java or Kotlin code on Android and in Objective C or Swift code on iOS.

Flutter’s platform-specific API works with message passing.

From the Flutter app, we ought to deliver messages to some of the iOS or Android factors of the app over a platform channel. The host listens to the platform channel and receives the message. It then uses any platform-specific APIs using the nearby programming language and sends decreased returned responses to the Flutter a part of the app.

Architectural overview: platform channels(source: Writing custom platform-specific code | Flutter)

Messages are passed between the client (UI) and host (platform) using platform channels as illustrated in this diagram:

Messages are passed between the Flutter Code(UI) and host (platform) victimization platform channels. Messages and responses are passed asynchronously and therefore the program remains responsive.

On Dart’s aspect USAing MethodChannel(API) we have a tendency to send a message that is equivalent to a way call. On the automation side MethodChannel automaton (API) and on the iOS side FlutterMessageChannel (API) is employed for receiving method calls and causing back results. These categories enable us to develop a platform plugin with really easy code.

If required, method calls may also be sent in the reverse direction, with the Android/IOS platform acting as shopper and methodology enforced in Dart.

Data sorts supported by Platform Channel

the quality platform channel uses a typical message codec that supports economical binary serialization of straightforward JSON-like values of types boolean, number, String, computer memory unit buffer, list, and map. The serialization and deserialization of those values too and from messages happen mechanically after we send and receive values.

The following table shows how Dart values are received on the platform side and vice versa: (source: Writing custom platform-specific code | Flutter)

Let’s get started with practical applications!

Setting up a brand-new project

First of all, let’s begin by typing those instructions to create a brand new flutter software kind those instructions for your terminal:

flutter create flutter_platform

cd flutter_platform

After navigating to the listing of the software we simply created let’s kind the subsequent command withinside the terminal to make certain that the entirety is running as needed

flutter run

If the entirety is strolling effectively then we can pass to the following phase,

As we will see withinside the folders segment in our IDE

You will see the folder referred to as Android which hosts the local android code

By default, the flutter create command generates kotlin primarily based total code

and you may discover the Android app’s Kotlin code in MainActivity.kt. You won’t see a lot of code there, however, but you will see that it implements the FlutterActivityclass, as part of the Flutter engine.

Now, we will begin playing with the MainActivity.kt class to create a way channel to attach it with the Dart code we have.

Calling Kotlin code from Dart

We realize that we will generate a random number inside Dart, however, let’s use Kotlin’s library random Function generator from the Dart Code to get commenced with MethodChannel.

First, we want to sign in a way name handler from the Kotlin side. Add the subsequent code for your MainActivity.kt:

Here, we override the configureFlutterEngine method from the FlutterActivity which is in MainActivity.kt class to register a method channel for building a connection with the Dart Code. The configureFlutterEngine method runs when the Flutter engine is first initialized and is coupled with a specific Android Activity, so Flutter recommends using it to register method channel handlers.

you can use one method channel to implement more than one native method. In this scenario, we implemented only one which is getRandom method just for demonstration purposes. When the particular method channel receives a call, we can identify the method name using a conditional statement:

if(call.method == “getRandom”) {

var randomNumber = Random.nextInt(50)

result.success(randomNumber)

}

Here, we use the result.success function to get the random number to the Dart Side. it’s always good to handle unknown method calls as follows:

else {

// to handle unknown method calls

result.notImplemented()

}

Now, the native functionality is ready to receive method calls from Dart. We’ll modify our Flutter app to display a random number that comes from Kotlin native code. After we press the floating button, we will see a random number.

Copy the following code so you can give it a try

import ‘package:flutter/services.dart’;
import ‘package:flutter/material.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(
primarySwatch: Colors.blue,),
home: const MyHomePage(title: ‘Flutter Demo Home Page’),);

}

}

class MyHomePage extends StatefulWidget {

const MyHomePage({super.key, required this.title});

final String title;

@override

State createState() => _MyHomePageState();

}

class _MyHomePageState extends State {

int _counter = 0;

static const platform = MethodChannel(‘example.com/channel’);

Future _createRandomNumberOnClick() async {

int random;

try {

random = await platform.invokeMethod(‘getRandom’);

} on PlatformException catch (e) {

random = 0;

}

setState(() {

_counter = random;

});

}

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text(widget.title),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

const Text(

‘Kotlin is returning the following random number:’,

),

Text(

‘$_counter’,

style: Theme.of(context).textTheme.headline4,

),

],

),

),

floatingActionButton: FloatingActionButton(

onPressed: _createRandomNumberOnClick,

tooltip: ‘get Random Number’,

child: const Icon(Icons.refresh),

),

);

}

}

Platform channels are easy enough, however, getting the entirety running out of your Flutter UI through a custom Dart API sponsored via way of means of a separate Java/Kotlin and Objective-C/Swift implementation does take a little care. And preserving the setup running as adjustments are made on your app will, in practice, require computerized checking out to protect in opposition to regressions. This can’t be achieved with unit checking out by myself due to the fact you want an actual app walking for platform channels to really communicate to the platform.

Flutter comes with the flutter_driver integration take a look at a framework that permits you to check Flutter packages walking on actual gadgets and emulators. But flutter_driver isn’t always presently incorporated with different frameworks to allow checking out throughout Flutter and platform components. I am assured that is one region in which Flutter will enhance withinside the future.

In a few situations, you may use flutter_driver as is to check your platform channel utilization. This calls for your Flutter person interface may be used to cause any platform interplay and that it’s miles then up to date with enough elements to permit you to take a look to check the final results of the interplay.

If you aren’t in that situation, or in case you are packaging up your platform channel utilization as a Flutter plugin that you need a module to take a look at, you may alternatively write an easy Flutter app for checking-out purposes. That app must have the traits above and may then be exercised with the use of flutter_driver. You’ll locate an instance withinside the Flutter GitHub repo.

Keep the platform aspect geared up for incoming synchronous calls

Platform channels are asynchronous only. But there are pretty some platform APIs obtainable that make synchronous calls into your host app components, soliciting for facts or assistance or presenting a window of opportunity. One instance is Activity Being a synchronous method the entirety needs to be carried out earlier than the incoming name returns. Now, you would possibly want to encompass facts from the Dart aspect in such processing, however, it’s miles too overdue to begin sending out asynchronous messages as soon as the synchronous name is already energetic on the principle UI thread.

The method utilized by Flutter, maximum considerably for semantics/accessibility facts, is to proactively ship up-to-date (or updates to) facts to the platform aspect every time the facts adjust at the Dart aspect. Then, when the synchronous name arrives, the facts from the Dart aspect are already gifted and are to be had to the platform aspect code.