Flutter Creating Android Platform-Specific Code

 

Flutter Creating Android Platform-Specific Code

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.

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 messaging protocol. The messages are passed between the client (UI) and Host (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.

The following block diagram shows the appropriate platform-specific code architecture.

Flutter Creating Android Platform-Specific Code

The messaging channel uses a standard message codec (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.

The following table shows how dart values are received on Android and iOS platform and vice-versa:

DartAndroidiOS
nullnullnil (NSNull when nested)
booljava.lang.BooleanNSNumber numberWithBool:
intjava.lang.IntegerNSNumber numberWithInt:
doublejava.lang.DoubleNSNumber numberWithDouble:
Stringjava.lang.StringNSString:
Uint8Listbyte[]FlutterStandardTypedData typedDataWithBytes:
Int32Listint[]FlutterStandardTypedData typedDataWithInt32:
Int64Listlong[]FlutterStandardTypedData typedDataWithInt64:
Float64Listdouble[]FlutterStandardTypedData typedDataWithFloat64:
Listjava.util.ArrayListNSArray
Mapjava.util.HashMApNSDictionary

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 main.dart file.

  1. import 'package:flutter/material.dart';  
  2. import 'dart:async';  
  3. import 'package:flutter/services.dart';  
  4.   
  5. void main() => runApp(MyApp());  
  6. class MyApp extends StatelessWidget {  
  7.   @override  
  8.   Widget build(BuildContext context) {  
  9.     return MaterialApp(  
  10.       title: 'Flutter DemoApplication',  
  11.       theme: ThemeData(  
  12.         primarySwatch: Colors.green,  
  13.       ),  
  14.       home: MyHomePage(  
  15.           title: 'Flutter Platform Specific Page'  
  16.       ),  
  17.     );  
  18.   }  
  19. }  
  20. class MyHomePage extends StatelessWidget {  
  21.   MyHomePage({Key key, this.title}) : super(key: key);  
  22.   final String title;  
  23.   static const platform = const MethodChannel('flutterplugins.javatpoint.com/browser');  
  24.   Future<void> _openBrowser() async {  
  25.     try {  
  26.       final int result = await platform.invokeMethod('openBrowser', <String, String>{  
  27.         'url'"https://www.javatpoint.com"  
  28.       });  
  29.     }  
  30.     on PlatformException catch (e) {  
  31.       // Unable to open the browser  
  32.       print(e);  
  33.     }  
  34.   }  
  35.   @override  
  36.   Widget build(BuildContext context) {  
  37.     return Scaffold(  
  38.       appBar: AppBar(  
  39.         title: Text(this.title),  
  40.       ),  
  41.       body: Center(  
  42.         child: RaisedButton(  
  43.           child: Text('Click Here'),  
  44.           onPressed: _openBrowser,  
  45.         ),  
  46.       ),  
  47.     );  
  48.   }  
  49. }  

In the above file, we have imported a service.dart file, which includes the functionality to invoke the platform-specific code. In the MyHomePage widget, we have created a message channel and write a method _openBrowser to invoke the platform-specific code.

  1. Future<void> _openBrowser() async {  
  2.   try {  
  3.     final int result = await platform.invokeMethod('openBrowser', <String, String>{  
  4.       'url'"https://www.javatpoint.com"  
  5.     });  
  6.   }  
  7.   on PlatformException catch (e) {  
  8.     // Unable to open the browser   
  9.  print(e);  
  10.   }  
  11. }  

Finally, we have created a button to open the browser.

Now, we need to provide the custom platform-specific implementation. To do this, navigate to the Android folder of your Flutter project and select the Java or Kotlin file and insert the following code into the MainActivity file. This code might change according to the Java or Kotlin language.

  1. package com.javatpoint.flutterplugins.flutter_demoapplication  
  2.   
  3. import android.app.Activity  
  4. import android.content.Intent  
  5. import android.net.Uri  
  6. import android.os.Bundle  
  7. import io.flutter.app.FlutterActivity  
  8. import io.flutter.plugin.common.MethodCall  
  9. import io.flutter.plugin.common.MethodChannel  
  10. import io.flutter.plugin.common.MethodChannel.MethodCallHandler  
  11. import io.flutter.plugin.common.MethodChannel.Result  
  12. import io.flutter.plugins.GeneratedPluginRegistrant  
  13.   
  14.  class MainActivity:FlutterActivity() {  
  15.     override fun onCreate(savedInstanceState:Bundle?) {  
  16.         super.onCreate(savedInstanceState)  
  17.         GeneratedPluginRegistrant.registerWith(this)  
  18.         MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->  
  19.         val url = call.argument<String>("url")  
  20.         if (call.method == "openBrowser") {  
  21.             openBrowser(call, result, url)  
  22.         } else {  
  23.             result.notImplemented()  
  24.         }  
  25.     }  
  26.  }  
  27.  private fun openBrowser(call:MethodCall, result:Result, url:String?) {  
  28.     val activity = this  
  29.     if (activity == null)  
  30.     {  
  31.         result.error("UNAVAILABLE""It cannot open the browser without foreground activity"null)  
  32.         return  
  33.     }  
  34.     val intent = Intent(Intent.ACTION_VIEW)  
  35.     intent.data = Uri.parse(url)  
  36.     activity!!.startActivity(intent)  
  37.     result.success(true as Any)  
  38.  }  
  39.   
  40.  companion object {  
  41.     private val CHANNEL = "flutterplugins.javatpoint.com/browser"  
  42.  }  
  43. }  

In the MainActivity.kt file, we have created a method openBrowser() to open the browser.

  1. private fun openBrowser(call:MethodCall, result:Result, url:String?) {  
  2.     val activity = this  
  3.     if (activity == null)  
  4.     {  
  5.         result.error("UNAVAILABLE""It cannot open the browser without foreground activity"null)  
  6.         return  
  7.     }  
  8.     val intent = Intent(Intent.ACTION_VIEW)  
  9.     intent.data = Uri.parse(url)  
  10.     activity!!.startActivity(intent)  
  11.     result.success(true as Any)  
  12.  }  

Output

Now, run the app in your android studio, you will get the following output. When you click on the button Click Here, you can see that the browser home page screen is launched.

Flutter Creating Android Platform-Specific Code
Flutter Creating Android Platform-Specific Code


Post a Comment

Previous Post Next Post