\n
class _MyHomePageState extends State<MyHomePage> {\n static const platform = const MethodChannel('flutter.native\/helper');\n<\/code><\/pre>\n<\/div>\n<\/div>\nInvoke a method on the method channel, specifying the concrete method to call via the String identifier. In the code below, it is helloFromNativeCode<\/p>\n
\n
\n
String response = \"\";\n try {\n final String result = await platform.invokeMethod('helloFromNativeCode');\n response = result;\n } on PlatformException catch (e) {\n response = \"Failed to Invoke: '${e.message}'.\";\n }\n<\/code><\/pre>\n<\/div>\n<\/div>\nUse the returned response to update the user interface state inside setState.<\/p>\n
\n
\n
setState(() {\n _responseFromNativeCode = response;\n});\n<\/code><\/pre>\n<\/div>\n<\/div>\nStep 4: Create method implementation in Android using java<\/h3>\n In Android Studio open Flutter app and select the android folder inside it. Open the file MainActivity.java<\/p>\n
Now we have to create a MethodChannel with the same name that we have created in Flutter App.<\/p>\n
\n
\n
public class MainActivity extends FlutterActivity {\n private static final String CHANNEL = \"flutter.native\/helper\";\n .....\n}\n<\/code><\/pre>\n<\/div>\n<\/div>\nWe have to create a MethodCallHandler in onCreate method<\/p>\n
\n
\n
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(\n new MethodChannel.MethodCallHandler() {\n @Override\n public void onMethodCall(MethodCall call, MethodChannel.Result result) {\n if (call.method.equals(\"helloFromNativeCode\")) {\n String greetings = helloFromNativeCode();\n result.success(greetings);\n }\n}});\n<\/code><\/pre>\n<\/div>\n<\/div>\nStep 4: Create method implementation in iOS using Objective C<\/h3>\n Open the file AppDelegate.m of your Flutter app in Xcode. Now we have to create a FlutterMethodChannel with the same name that we have created in Flutter App.<\/p>\n
\n
\n
FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;\n FlutterMethodChannel* nativeChannel = [FlutterMethodChannel\n methodChannelWithName:@\"flutter.native\/helper\"\n binaryMessenger:controller];\n<\/code><\/pre>\n<\/div>\n<\/div>\nCreate method call handler<\/p>\n
\n
\n
[nativeChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {\n if ([@\"helloFromNativeCode\" isEqualToString:call.method]) {\n NSString *strNative = [weakSelf helloFromNativeCode];\n result(strNative);\n } else {\n result(FlutterMethodNotImplemented);\n }\n }];\n<\/code><\/pre>\n<\/div>\n<\/div>\nComplete Code<\/h2>\nComplete Android Native code<\/h3>\n\n
\n
import android.os.Bundle;\nimport io.flutter.app.FlutterActivity;\nimport io.flutter.plugin.common.MethodCall;\nimport io.flutter.plugin.common.MethodChannel;\nimport io.flutter.plugins.GeneratedPluginRegistrant;\npublic class MainActivity extends FlutterActivity {\n private static final String CHANNEL = \"flutter.native\/helper\";\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n GeneratedPluginRegistrant.registerWith(this);\n new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(\n new MethodChannel.MethodCallHandler() {\n @Override\n public void onMethodCall(MethodCall call, MethodChannel.Result result) {\n if (call.method.equals(\"helloFromNativeCode\")) {\n String greetings = helloFromNativeCode();\n result.success(greetings);\n }\n }});\n }\n private String helloFromNativeCode() {\n return \"Hello from Native Android Code\";\n }\n<\/code><\/pre>\n<\/div>\n<\/div>\n}<\/p>\n
Complete IOS native code<\/h3>\n\n
\n
#include \"AppDelegate.h\"\n<\/span> #include \"GeneratedPluginRegistrant.h\"\n<\/span>\n@implementation<\/span> AppDelegate<\/span>\n\n -<\/span> (<\/span>BOOL<\/span>)<\/span>application<\/span>:(<\/span>UIApplication<\/span> *<\/span>)<\/span>application<\/span>\n didFinishLaunchingWithOptions<\/span>:(<\/span>NSDictionary<\/span> *<\/span>)<\/span>launchOptions<\/span> {<\/span>\n\n FlutterViewController<\/span>*<\/span> controller<\/span> =<\/span> (<\/span>FlutterViewController<\/span>*<\/span>)<\/span>self<\/span>.<\/span>window<\/span>.<\/span>rootViewController<\/span>;<\/span>\n FlutterMethodChannel<\/span>*<\/span> nativeChannel<\/span> =<\/span> [<\/span>FlutterMethodChannel<\/span>\n methodChannelWithName<\/span>:<\/span>@\"flutter.native\/helper\"<\/span>\n binaryMessenger<\/span>:<\/span>controller<\/span>];<\/span>\n __weak<\/span> typeof<\/span>(<\/span>self<\/span>)<\/span> weakSelf<\/span> =<\/span> self<\/span>;<\/span>\n [<\/span>nativeChannel<\/span> setMethodCallHandler<\/span>:<\/span>^<\/span>(<\/span>FlutterMethodCall<\/span>*<\/span> call<\/span>,<\/span> FlutterResult<\/span> result<\/span>)<\/span> {<\/span>\n if<\/span> ([<\/span>@\"helloFromNativeCode\"<\/span> isEqualToString<\/span>:<\/span>call<\/span>.<\/span>method<\/span>])<\/span> {<\/span>\n NSString<\/span> *<\/span>strNative<\/span> =<\/span> [<\/span>weakSelf<\/span> helloFromNativeCode<\/span>];<\/span>\n result<\/span>(<\/span>strNative<\/span>);<\/span>\n }<\/span> else<\/span> {<\/span>\n result<\/span>(<\/span>FlutterMethodNotImplemented<\/span>);<\/span>\n }<\/span>\n }];<\/span>\n\n [<\/span>GeneratedPluginRegistrant<\/span> registerWithRegistry<\/span>:<\/span>self<\/span>];<\/span>\n return<\/span> [<\/span>super<\/span> application<\/span>:<\/span>application<\/span> didFinishLaunchingWithOptions<\/span>:<\/span>launchOptions<\/span>];<\/span>\n }<\/span>\n -<\/span> (<\/span>NSString<\/span> *<\/span>)<\/span>helloFromNativeCode<\/span> {<\/span>\n return<\/span> @\"Hello From Native IOS Code\"<\/span>;<\/span>\n }<\/span>\n\n@end<\/span>\n<\/code><\/pre>\n<\/div>\n<\/div>\nComplete Flutter code<\/h3>\n\n
\n
import 'package:flutter\/material.dart';\nimport 'dart:async';\nimport 'package:flutter\/services.dart';\n\nvoid main() => runApp(new MyApp());\n\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return new MaterialApp(\n home: new HomePage(),\n );\n }\n}\n\nclass HomePage extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return new Scaffold(\n appBar: new AppBar(\n title: const Text('Native Code from Dart'),\n ),\n body: new MyHomePage(),\n );\n }\n}\n\nclass MyHomePage extends StatefulWidget {\n MyHomePage({Key key, this.title}) : super(key: key);\n\n final String title;\n\n @override\n _MyHomePageState createState() => new _MyHomePageState();\n}\n\nclass _MyHomePageState extends State<MyHomePage> {\n static const platform = const MethodChannel('flutter.native\/helper');\n String _responseFromNativeCode = 'Waiting for Response...';\n\n Future<void> responseFromNativeCode() async {\n String response = \"\";\n try {\n final String result = await platform.invokeMethod('helloFromNativeCode');\n response = result;\n } on PlatformException catch (e) {\n response = \"Failed to Invoke: '${e.message}'.\";\n }\n\n setState(() {\n _responseFromNativeCode = response;\n });\n }\n\n @override\n Widget build(BuildContext context) {\n return Material(\n child: Center(\n child: Column(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly,\n children: [\n RaisedButton(\n child: Text('Call Native Method'),\n onPressed: responseFromNativeCode,\n ),\n Text(_responseFromNativeCode),\n ],\n ),\n ),\n );\n }\n\n}\n<\/code><\/pre>\n<\/div>\n<\/div>\nResult<\/h3>\n Run the code on Android and iOS devices. Click on the Button \u201cCall Native Method”<\/p>\nResult<\/figcaption><\/figure>\n","protected":false},"excerpt":{"rendered":"Flutter allows us to call platform-specific APIs available in Java or Kotlin code on Android, or in ObjectiveC or Swift code on iOS. Flutter\u2019s platform-specific API works with message passing. From Flutter app we have to send messages to a host on iOS or Android parts of the app over a platform channel. The host listens on the platform channel, and receives the message. It then uses any platform-specific APIs using the native programming language and sends back a response to the Flutter portion of app. Architectural overview Messages are passed between the Flutter Code(UI) and host (platform) using platform channels. Messages and responses are passed asynchronously and the user interface remains responsive. On Dart side using MethodChannel(API) we sends a message which is corresponding to a method call. On the Android side MethodChannel Android (API) and on the iOS side FlutterMessageChannel (API) is used for receiving method calls and sending back result. These classes allow us to develop a platform plugin with a very simple code. If require, method calls can also be sent in the reverse direction, with the Android\/IOS platform acting as client and method implemented in Dart. Data types supported by Platform Channel The standard platform channel uses standard message codec that supports efficient binary serialization of simple JSON-like values of types boolean, number, String, byte buffer, list and map. The serialization and deserialization of these values to and from messages happens automatically when we send and receive values. Creating flutter app that calls iOS and Android code Now we will create a flutter app with a method call that will be implemented in Android (java) and iOS (Objective C) respectively. Step 1: Create a new app project In a terminal run: flutter create flutter_to_native By default, Flutter supports writing Android code in Java and iOS code in Objective C. If you want to use Kotlin and Swift, create project with the following command. flutter create -i swift -a kotlin flutter_to_native Step 2: Create a platform Channel The client and host sides of the channel are connected through the channel name passed in the channel constructor. All channel names used in a single app must be unique. In our example we are creating the channel name flutter.native\/helper class _MyHomePageState extends State<MyHomePage> { static const platform = const MethodChannel(‘flutter.native\/helper’); Step 3:Invoke method on platform Channel Invoke a method on the method channel, specifying the concrete method to call via the String identifier. In the code below, it is helloFromNativeCode String response = “”; try { final String result = await platform.invokeMethod(‘helloFromNativeCode’); response = result; } on PlatformException catch (e) { response = “Failed to Invoke: ‘${e.message}’.”; } Use the returned response to update the user interface state inside setState. setState(() { _responseFromNativeCode = response; }); Step 4: Create method implementation in Android using java In Android Studio open Flutter app and select the android folder inside it. Open the file MainActivity.java Now we have to create a MethodChannel with the same name that we have created in Flutter App. public class MainActivity extends FlutterActivity { private static final String CHANNEL = “flutter.native\/helper”; ….. } We have to create a MethodCallHandler in onCreate method new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { if (call.method.equals(“helloFromNativeCode”)) { String greetings = helloFromNativeCode(); result.success(greetings); } }}); Step 4: Create method implementation in iOS using Objective C Open the file AppDelegate.m of your Flutter app in Xcode. Now we have to create a FlutterMethodChannel with the same name that we have created in Flutter App. FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController; FlutterMethodChannel* nativeChannel = [FlutterMethodChannel methodChannelWithName:@”flutter.native\/helper” binaryMessenger:controller]; Create method call handler [nativeChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { if ([@”helloFromNativeCode” isEqualToString:call.method]) { NSString *strNative = [weakSelf helloFromNativeCode]; result(strNative); } else { result(FlutterMethodNotImplemented); } }]; Complete Code Complete Android Native code import android.os.Bundle; import io.flutter.app.FlutterActivity; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { private static final String CHANNEL = “flutter.native\/helper”; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { if (call.method.equals(“helloFromNativeCode”)) { String greetings = helloFromNativeCode(); result.success(greetings); } }}); } private String helloFromNativeCode() { return “Hello from Native Android Code”; } } Complete IOS native code #include “AppDelegate.h” #include “GeneratedPluginRegistrant.h” @implementation AppDelegate – (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController; FlutterMethodChannel* nativeChannel = [FlutterMethodChannel methodChannelWithName:@”flutter.native\/helper” binaryMessenger:controller]; __weak typeof(self) weakSelf = self; [nativeChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { if ([@”helloFromNativeCode” isEqualToString:call.method]) { NSString *strNative = [weakSelf helloFromNativeCode]; result(strNative); } else { result(FlutterMethodNotImplemented); } }]; [GeneratedPluginRegistrant registerWithRegistry:self]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } – (NSString *)helloFromNativeCode { return @”Hello From Native IOS Code”; } @end Complete Flutter code import ‘package:flutter\/material.dart’; import ‘dart:async’; import ‘package:flutter\/services.dart’; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: const Text(‘Native Code from Dart’), ), body: new MyHomePage(), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { static const platform = const MethodChannel(‘flutter.native\/helper’); String _responseFromNativeCode = ‘Waiting for Response…’; Future<void> responseFromNativeCode() async { String response = “”; try { final String result = await platform.invokeMethod(‘helloFromNativeCode’); response = result; } on PlatformException catch (e) { response = “Failed to Invoke: ‘${e.message}’.”; } setState(() { _responseFromNativeCode = response; }); } @override Widget build(BuildContext context) { return Material( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ RaisedButton( child: Text(‘Call Native Method’), onPressed: responseFromNativeCode, ), Text(_responseFromNativeCode), ], ), ), ); } } Result Run the code on Android and iOS devices. Click on the Button \u201cCall Native Method”<\/p>\n","protected":false},"author":1,"featured_media":9995,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"template-default.php","format":"standard","meta":{"_acf_changed":false,"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[5],"tags":[30,69,71,72,32,34,74,35],"class_list":["post-10084","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-android","tag-bridge","tag-communication","tag-dart","tag-flutter","tag-ios","tag-java","tag-native","entry","has-media"],"acf":{"upload_file":""},"yoast_head":"\n
How to Develop a Bridge in Flutter Between Dart & Native Code | Blog | 47Billion<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n \n \n \n \n \n\t \n\t \n\t \n