Calling iOS Native Code in Flutter

In this tutorial, we create a small Flutter feature that calls the native Swift code of the iOS to read the battery level value.

Flutter uses a flexible system to invoke platform-specific APIs, either in Kotlin or Java code on Android or Swift, or in Objective-C code on iOS.

The built-in support of the Flutter API does not depend on code generation, but on a flexible message style.

Basically, the Flutter part of the application sends messages to the iOS or Android part of the application via a platform channel. The host listens to the platform’s channel, receives the message and calls up the platform API using its own programming language, and then sends the response back to the client (the floating part of the application).

For this to work, we have to do the following:

  1. Create a new Flutter project,
  2. Create a MethodChannel object,
  3. Set a function that recalls the original code of the iOS,
  4. Prepare the user interface to display the result,
  5. Introduce a new feature in Swift that allows you to read the battery level.

Floating

Named channel for communication with platform plug-ins using asynchronousmethodcalls. Method calls are binary encoded before they are sent, and the resulting binary results are decoded into Dart values. The used MethodCodec must be compatible with the plugin of the platform.

1. Creating a new Flutter project

First we need to create a new Flutter project in Android Studio (or any other IDE you use). If you don’t know how to create a project, you can consult the tutorial https://www.appsdeveloperblog.com/hello-world-app-in-flutter/.

2. Creation of a method channel

Then we’ll build a canal. We will use a MethodChannel method with a platform that returns the level of the host battery by declaring the following constant:

static const platform = const MethodChannel (‘samples.flutter.dev/battery’) ;

Next we name the method on the string by entering the string ID.

static const platform = const MethodChannel (‘samples.flutter.dev/battery’) ;

end result int = wait for platform.invokeMethod(‘getBatteryLevel’) ;

3. Create a Flutter function that calls the native iOS code.

Here is an example of a short code that uses the MethodChannel and shows how to write a function to get the battery level of the device.

static const platform = const MethodChannel (‘samples.flutter.dev/battery’) ;
String _batteryLevel = ‘Battery Level’ ;

Future _getBatteryLevel() async {
String batteryLevel ;
try {
final int result = wait platform.invokeMethod(‘getBatteryLevel’)) ;
batteryLevel = ‘Battery level in $result % . } on PlatformException catch (e) {batteryLevel = Failed to get battery level : ‘${e.message}’ ;} } on PlatformException catch (e) {batteryLevel = Failed to get battery level : ‘${e.message}’ ;}.

setState(() {
_battery level = battery level;
});
})

As you can see in the code, we have created a Future function called _getBatteryLevel() that waits for platform.invokeMethod(‘getBatteryLevel’), which we will discuss later in the section on iOS functions. The Flutter application first checks the platform. As soon as the platform is confirmed, the application listens to the platform channel and checks the called function.

4. Piston interface for displaying results

As you can see, we have declared a string variable _battery level and assigned the value of the battery level. Next, we explained the future empty function _getBattery level(), which is asynchronous. In the vacuum we declare an empty battery. If the method fails, we break off the conversation with the report of the attempted capture. In the test part of the rack, we test the original battery test method and perform it as a chain at battery level, after which we detect any faults. After the test statement, we simply set the _battery level status to the battery level value.

Centre (
Child : Column(
mainAxisAlignment : MainAxisAlignment.spacePotentially,
Children :
High button(

The baby: Text (Get Battery Level),
onPress: (_getBatteryLevel,
),
Text(_batteryLevel),
],
),

Full beat code

Below you will find a complete code example in the Flutter section. But we’re not done yet. We still need to work on the native iOS code to make it work.

import ‘dart:async’ ; import
‘pakket:flutter/materiaal.dart’ ; import
‘pakket:flutter/services.dart’ ; import
‘pakket:flutter/cupertino.dart’ ;

void main() {
runApp(MyApp());
}

The MyApp class extends the StatelessWidget {
@override
Widget build(BuildContext context) {
gives MaterialApp(
home : MyHomePage(),
);
}
}.

The MyHomePage class extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}.

The _MyHomePageState class extends the state {
static const platform = const MethodChannel (‘samples.flutter.dev/battery’) ;
String _batteryLevel =
‘Battery level’ ;

Future _getBatteryLevel() async {
String batteryLevel ;
try {
final int result = wait platform.invokeMethod(‘getBatteryLevel’)) ;
batteryLevel = ‘Battery level in $result % . } on PlatformException catch (e) {batteryLevel = Failed to get battery level : ‘${e.message}’ ;} } on PlatformException catch (e) {batteryLevel = Failed to get battery level : ‘${e.message}’ ;}.

setState(() {
_battery level = battery level;
});
})

@override
Widget build(BuildContext context) {
return material(
child) : Centre (
Child : Column(
mainAxisAlignment : MainAxisAlignment.spacePotentially,
Children :
High button(

The baby: Text (‘Get Battery Level’), onPress: _getBatteryLevel,),Text(_batteryLevel,],), }}.

The code beat is ready. Let’s see what the native iOS code will look like.

iOS Swift. Creating a flutter channelChannelMethod

In the AppDelegate.fast file, overwrite the application:didFinishLaunchingWithOptions function and create a FlutterMethodChannel associated with the channel name samples.flutter.dev/battery. To find the file AppDelegate.fast, open the ios folder in your Flutter project, open the Runner folder with the file AppDelegate.fast in the root folder. Look at the screenshot below:

@UIApplicationMain
@objc class AppDelegate : FlutterAppDelegate {
override application function(
_ application : UIApplication,
didFinishLaunchingWithOptions launchOptions : [UIApplication.LaunchOptionsKey : Any] ?). -> Bool {

Checking the starter : FlutterViewController = window ?.rootViewController as! FlutterViewController
let batteryChannel = FlutterMethodChannel (name: samples.flutter.dev/battery,
binaryMessenger: controller.binaryMessenger)

batteryChannel.setMethodCallHandler({
[weak self-control] (call: FlutterMethodCall, result: FlutterResult) -> Empty in

// Message: This method is called in the user interface thread.
guard.method == getBatteryLevel else {
result(FlutterMethodNotImplemented)
gives
}.

self ?.receiveBattery level (Result: Result)
}))

ProducedPluginRegistrant.register (with: self)

super.application return(application, didFinishLaunchingWithOptions: launchOptions)
}
}

iOS Swift. ReceiveBatteryLevel() function

We are now ready to create a Swift ReceiverBatteryLevel() function that reads and returns the value of the oil level on the device.  For this we use the native API of the iOS battery. Add the following function to the end of AppDelegate.fast.

private function receiveBatteryLevel(result: FlutterResult) {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryState == UIDevice.BatteryState.unknown {
result(code: UNAVAILABLE,
message: BatteryInfo available,
details: nil))
} else {
result(Int(device.batteryLevel * 100)))
}.
}

You can then see the result in your application after running it.

Pay attention: If you use an emulator, you are likely to get battery information.

I hope you found this lesson about Flutter useful. If you want to know more about Flutter, see the other Flutter tutorials on this page. Some of them contain video tutorials.

Have fun developing mobile applications with Flutter!

Related Tags:

configure php with apache linux,configure apache for php 7,apache, php windows,deploy php application on apache linux,apache-php docker,httpd.conf php,lamp server download,ubuntu 16.04 install lamp,ubuntu 18.04 install apache php mariadb,mamp,install php ubuntu 20,install php 7.4 ubuntu,error: module php does not exist!,unable to locate package php,apache run php ubuntu,xampp 5.6 download,xampp full form,xampp vs wamp,xampp tutorial,how to install xampp in ubuntu,xampp default files,que es xampp,advantages of xampp,features of wamp server,wampserver review,amp stack windows,php mysql apache book,install apache, mysql phpmyadmin,apache installation for windows 10,windows 10 install httpd,install web server on windows 10,software requirements of php,enable php in apache,php 7.4 windows binary,apachelounge/download,how to start apache server in windows,how to install php,wamp,php download,mysql download,uninstall apache windows 10,apache lounge,install apache on windows 10,bitnami wamp stack,apachephp-mysql ubuntu,xampp,apache-php, mysql docker,lamp stack,xampp download,xampp mysql