{"id":2111,"date":"2022-04-07T19:30:32","date_gmt":"2022-04-07T19:30:32","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=2111"},"modified":"2022-04-07T19:30:32","modified_gmt":"2022-04-07T19:30:32","slug":"flutter-creating-android-platform-specific-code","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/04\/07\/flutter-creating-android-platform-specific-code\/","title":{"rendered":"Flutter Creating Android Platform-Specific Code"},"content":{"rendered":"\n<p>In this section, we are going to see how we can write custom platform-specific code in Flutter. Flutter is an excellent framework, which provides a mechanism to handle\/access platform-specific features. This feature allows the developer to extend the functionality of the Flutter framework. Some of the essential platform-specific functionality that can be accessed easily through the framework are camera, battery level, browser, etc.<\/p>\n\n\n\n<p>Flutter uses a flexible system to call platform-specific API either available on Android in Java or Kotlin code, or in Objective-C or Swift code on iOS. The general idea of accessing the platform-specific code in Flutter is through the&nbsp;<strong>messaging protocol.<\/strong>&nbsp;The messages are passed between the&nbsp;<strong>client<\/strong>&nbsp;(UI) and&nbsp;<strong>Host<\/strong>&nbsp;(Platform) using the common message channel. It means the clients sends a message to the Host by using this message channel. Next, the Host listens on that message channel, receives the message, does the appropriate functionality, and finally returns the result to the client.<\/p>\n\n\n\n<p>The following block diagram shows the appropriate platform-specific code architecture.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/static.javatpoint.com\/tutorial\/flutter\/images\/flutter-creating-android-platform-specific-code.png\" alt=\"Flutter Creating Android Platform-Specific Code\"\/><\/figure>\n\n\n\n<p>The messaging channel uses a standard message&nbsp;<strong>codec<\/strong>&nbsp;(StandardMessageCodec class), which supports efficient binary serialization of JSON like values, such as string, Boolean, numbers, byte buffers, and List and Maps, etc. The serialization and deserialization of these values work automatically between clients and hosts when you send and receive values.<\/p>\n\n\n\n<p>The following table shows how dart values are received on Android and iOS platform and vice-versa:<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table><tbody><tr><th>Dart<\/th><th>Android<\/th><th>iOS<\/th><\/tr><tr><td>null<\/td><td>null<\/td><td>nil (NSNull when nested)<\/td><\/tr><tr><td>bool<\/td><td>java.lang.Boolean<\/td><td>NSNumber numberWithBool:<\/td><\/tr><tr><td>int<\/td><td>java.lang.Integer<\/td><td>NSNumber numberWithInt:<\/td><\/tr><tr><td>double<\/td><td>java.lang.Double<\/td><td>NSNumber numberWithDouble:<\/td><\/tr><tr><td>String<\/td><td>java.lang.String<\/td><td>NSString:<\/td><\/tr><tr><td>Uint8List<\/td><td>byte[]<\/td><td>FlutterStandardTypedData typedDataWithBytes:<\/td><\/tr><tr><td>Int32List<\/td><td>int[]<\/td><td>FlutterStandardTypedData typedDataWithInt32:<\/td><\/tr><tr><td>Int64List<\/td><td>long[]<\/td><td>FlutterStandardTypedData typedDataWithInt64:<\/td><\/tr><tr><td>Float64List<\/td><td>double[]<\/td><td>FlutterStandardTypedData typedDataWithFloat64:<\/td><\/tr><tr><td>List<\/td><td>java.util.ArrayList<\/td><td>NSArray<\/td><\/tr><tr><td>Map<\/td><td>java.util.HashMAp<\/td><td>NSDictionary<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Let us create a simple application to demonstrate how to call a platform-specific API to open a browser. To do this, we need to create a Flutter project in Android Studio and insert the following code in the&nbsp;<strong>main.dart<\/strong>&nbsp;file.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter\/material.dart';  \nimport 'dart:async';  \nimport 'package:flutter\/services.dart';  \n  \nvoid main() => runApp(MyApp());  \nclass MyApp extends StatelessWidget {  \n  @override  \n  Widget build(BuildContext context) {  \n    return MaterialApp(  \n      title: 'Flutter DemoApplication',  \n      theme: ThemeData(  \n        primarySwatch: Colors.green,  \n      ),  \n      home: MyHomePage(  \n          title: 'Flutter Platform Specific Page'  \n      ),  \n    );  \n  }  \n}  \nclass MyHomePage extends StatelessWidget {  \n  MyHomePage({Key key, this.title}) : super(key: key);  \n  final String title;  \n  static const platform = const MethodChannel('flutterplugins.smartstart.institute.com\/browser');  \n  Future&lt;void> _openBrowser() async {  \n    try {  \n      final int result = await platform.invokeMethod('openBrowser', &lt;String, String>{  \n        'url': \"https:\/\/http:\/\/smartstart.institute.com\"  \n      });  \n    }  \n    on PlatformException catch (e) {  \n      \/\/ Unable to open the browser  \n      print(e);  \n    }  \n  }  \n  @override  \n  Widget build(BuildContext context) {  \n    return Scaffold(  \n      appBar: AppBar(  \n        title: Text(this.title),  \n      ),  \n      body: Center(  \n        child: RaisedButton(  \n          child: Text('Click Here'),  \n          onPressed: _openBrowser,  \n        ),  \n      ),  \n    );  \n  }  \n} <\/code><\/pre>\n\n\n\n<p>In the above file, we have imported a&nbsp;<strong>service.dart<\/strong>&nbsp;file, which includes the functionality to invoke the platform-specific code. In the&nbsp;<strong>MyHomePage<\/strong>&nbsp;widget, we have created a message channel and write a method _<strong>openBrowser<\/strong>&nbsp;to invoke the platform-specific code.<a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void> _openBrowser() async {  \n  try {  \n    final int result = await platform.invokeMethod('openBrowser', &lt;String, String>{  \n      'url': \"http:\/\/smartstart.institute.com\"  \n    });  \n  }  \n  on PlatformException catch (e) {  \n    \/\/ Unable to open the browser   \n print(e);  \n  }  \n}  <\/code><\/pre>\n\n\n\n<p>Finally, we have created a button to open the browser.<\/p>\n\n\n\n<p>Now, we need to provide the custom platform-specific implementation. To do this, navigate to the&nbsp;<strong>Android folder<\/strong>&nbsp;of your Flutter project and select the Java or Kotlin file and insert the following code into the&nbsp;<strong>MainActivity<\/strong>&nbsp;file. This code might change according to the Java or Kotlin language.<a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.smartstart.intitute.flutterplugins.flutter_demoapplication  \n  \nimport android.app.Activity  \nimport android.content.Intent  \nimport android.net.Uri  \nimport android.os.Bundle  \nimport io.flutter.app.FlutterActivity  \nimport io.flutter.plugin.common.MethodCall  \nimport io.flutter.plugin.common.MethodChannel  \nimport io.flutter.plugin.common.MethodChannel.MethodCallHandler  \nimport io.flutter.plugin.common.MethodChannel.Result  \nimport io.flutter.plugins.GeneratedPluginRegistrant  \n  \n class MainActivity:FlutterActivity() {  \n    override fun onCreate(savedInstanceState:Bundle?) {  \n        super.onCreate(savedInstanceState)  \n        GeneratedPluginRegistrant.registerWith(this)  \n        MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->  \n        val url = call.argument&lt;String>(\"url\")  \n        if (call.method == \"openBrowser\") {  \n            openBrowser(call, result, url)  \n        } else {  \n            result.notImplemented()  \n        }  \n    }  \n }  \n private fun openBrowser(call:MethodCall, result:Result, url:String?) {  \n    val activity = this  \n    if (activity == null)  \n    {  \n        result.error(\"UNAVAILABLE\", \"It cannot open the browser without foreground activity\", null)  \n        return  \n    }  \n    val intent = Intent(Intent.ACTION_VIEW)  \n    intent.data = Uri.parse(url)  \n    activity!!.startActivity(intent)  \n    result.success(true as Any)  \n }  \n  \n companion object {  \n    private val CHANNEL = \"flutterplugins.smartstart.institute.com\/browser\"  \n }  \n}  <\/code><\/pre>\n\n\n\n<p>In the&nbsp;<strong>MainActivity.kt<\/strong>&nbsp;file, we have created a method&nbsp;<strong>openBrowser()<\/strong>&nbsp;to open the browser.<a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-creating-android-platform-specific-code#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>private fun openBrowser(call:MethodCall, result:Result, url:String?) {  \n    val activity = this  \n    if (activity == null)  \n    {  \n        result.error(\"UNAVAILABLE\", \"It cannot open the browser without foreground activity\", null)  \n        return  \n    }  \n    val intent = Intent(Intent.ACTION_VIEW)  \n    intent.data = Uri.parse(url)  \n    activity!!.startActivity(intent)  \n    result.success(true as Any)  \n }  <\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<p>Now, run the app in your android studio, you will get the following output. When you click on the button&nbsp;<strong>Click Here,<\/strong>&nbsp;you can see that the browser home page screen is launched.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/static.javatpoint.com\/tutorial\/flutter\/images\/flutter-creating-android-platform-specific-code2.png\" alt=\"Flutter Creating Android Platform-Specific Code\"\/><\/figure>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this section, we are going to see how we can write custom platform-specific code in Flutter. Flutter is an excellent framework, which provides a mechanism to handle\/access platform-specific features. This feature allows the developer to extend the functionality of the Flutter framework. Some of the essential platform-specific functionality that can be accessed easily through [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[599],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/2111"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=2111"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/2111\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=2111"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=2111"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=2111"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}