Preface
This article mainly introduces to you the relevant content about Flutter calling native code of Android and iOS. It is shared for your reference and learning. I won’t say much below. Let’s take a look at the detailed introduction together.
3 major steps:
1. Call native methods in flutter
2. Implement the called method in Android
3. Implement the called method in iOS
Calling native methods in flutter
Scenario, here you want to call a native method to tell you a bool value. You can determine the meaning of this value at will. The meaning expressed here is whether it is a Chinese user.
You can design the method name to be called in flutter, here it is called
isChinese
Please note:
To call native code in flutter, you need to pass messages through the channel, and on the flutter side is MethodChannel.
So what we do here is to create a channel named by yourself on the flutter side:
const platform = const MethodChannel("/name");
You can get the name /name here at will.
Let me explain:
You may have a question, how can we tell Android and iOS how to call the channels we created on the flutter side by ourselves?
You asked this question very well. Let me tell you first. We will create channels with the same name as this channel at both ends later.
Knocked the blackboard:
You know now that we need to have one channel at the three ends, and these three channels have the same name, so we can connect it.
However, here we should first write the flutter side code, and then we will set the android and iOS side codes respectively. go!
Our code in flutter is as follows:
Future<bool> isEuropeUser() async { // Native channel const platform = const MethodChannel("/name"); //Analysis 1 bool result = false; try { result = await ("isChinese"); //Analysis 2 } on PlatformException catch (e) { print(()); } return result; }
Let's analyze it:
Analysis 1: Create a channel we customize.
Analysis 2: Use channel to send a call message to the native end, the call method is: isChinese
OK, I believe you think it's very simple on the flutter side. Next, let's take a look at how to do the android side.
Implementing the called method in Android
I suggest you write Android side code in Android studio, because this will have good code prompts and header file introduction. But if you have a way to achieve the same effect, I don’t care about any IDE.
There is a file in the Android folder in the flutter project folder. Don't tell me that you can't find it.
Let me tell you first to register our Android plug-in in MainActivity later. Hehe, now let’s write our Android plug-in first.
I posted the code at once, but there are not many anyway.
public class FlutterNativePlugin implements { public static String CHANNEL = "/name"; // Analysis 1 static MethodChannel channel; private Activity activity; private FlutterNativePlugin(Activity activity) { = activity; } public static void registerWith( registrar) { channel = new MethodChannel((), CHANNEL); FlutterNativePlugin instance = new FlutterNativePlugin(()); (instance); } @Override public void onMethodCall(MethodCall methodCall, result) { // Analysis 2 if (("isChinese")) { boolean isChinese = true; (isEuropean); // Analysis 3 } else { (); } } }
analyze:
Analysis 1: Note that the plugin name here should be the same as in flutter
Analysis 2: The onMethodCall method is a callback of the plug-in. Here we judge the called method based on the method name isChinese, and then implement our operations.
Analysis 3: This is directly returned true, because this is just an example, and you should change it to your own logic.
Our plug-in is written and we go back to register.
Look at the code:
public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); (this); registerCustomPlugin(this); } private void registerCustomPlugin(PluginRegistry registrar) { (()); } }
Congratulations, the Android side is completed.
//////////////////////////////////////////////////////////////////////////////////////////////////////////
Next, let’s do some iOS:
Implementing the called method in iOS
In iOS, I suggest you write code in xcode. Because this will have good tips.
Let me tell you first what files you want to change:
After opening the iOS project with xcode, there is an AppDelegate file in the Runner folder.
We will register our plug-in here later.
Then let's write our plugin code first:
\#import <Foundation/> #import <Flutter/> NS_ASSUME_NONNULL_BEGIN @interface FlutterNativePlugin : NSObject <FlutterPlugin> @end NS_ASSUME_NONNULL_END
#import "" #import "" @implementation FlutterNativePlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar { FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"/name" binaryMessenger:[registrar messenger]]; FlutterNativePlugin* instance = [[FlutterNativePlugin alloc] init]; [registrar addMethodCallDelegate:instance channel:channel]; } - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { if ([@"isEuropeUser" isEqualToString:]) { result([NSNumber numberWithBool:YES]); } else { result(FlutterMethodNotImplemented); } } @end
analyze:
This is also the same virtue as Android, which is divided into two parts: registration and method callback. But you may have found that the channel here is FlutterMethodChannel. There is no need to make a fuss about this. flutter also uses different classes of the MethodChannel on Android to distinguish these two platforms. It's just that the names are different.
It's time to register on iOS:
Just add code to the following method of the class:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; [FlutterNativePlugin registerWithRegistrar: [self registrarForPlugin:@"FlutterNativePlugin"]]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; }
///////////////////////////////////////////////////////////////////////////////////
Congratulations, the iOS side has also been set up.
Run your application to see if it can be called successfully. I wish you success.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.