Directory portal:A Guide to The Quick Start to Flutter
By reading hybrid Development (I) and Hybrid Development (II), you are sure to have a native + Flutetr hybrid application running.
Congratulations 🎉🎉🎉!
Now you may have a problem with the Flutter code and native code not being able to call each other before.
Because Flutter is a development framework independent of native Android, it certainly can’t call each other directly and happily exchange information.
Now, take a look at how Flutter solves these problems.
1.Platform Channels
A Flutter uses the Platform Channels architecture to communicate between a Flutter and its native.
The diagram above shows the architecture of a MethodChannel, through which a Flutter sends and receives information asynchronously.
MethodChannel is an encapsulated and convenient way to communicate. The Flutter example is also implemented with MethodChannel.
Platform Channels allow only the following data types to be used in communication:
Dart | Android | iOS |
---|---|---|
null | null | nil (NSNull when nested) |
bool | java.lang.Boolean | NSNumber numberWithBool |
int | java.lang.Integer | NSNumber numberWithInt |
int, if 32 bits not enough | java.lang.Long | NSNumber numberWithLong |
double | java.lang.Double | NSNumber numberWithDouble |
String | java.lang.String | NSString |
Uint8List | byte[] | FlutterStandardTypedData typedDataWithBytes |
Int32List | int[] | FlutterStandardTypedData typedDataWithInt32 |
Int64List | long[] | FlutterStandardTypedData typedDataWithInt64 |
Float64List | double[] | FlutterStandardTypedData typedDataWithFloat64 |
List | java.util.ArrayList | NSArray |
Map | java.util.HashMap | NSDictionary |
2. How to use MethodChannel
Methodchannels establish a communication bridge between a Flutter and a Native using specific channels.
Of course, we need to define the same channel on both ends of Flutter and Native.
2.1 Step 1: Define communication channels
-
The Flutter end:
Leading into the import ‘package: flutter/services. The dart’; Package and then create a MethodChannel.
const channel = MethodChannel('foo'); Copy the code
-
Native Android terminal:
MethodChannel channel = new MethodChannel(flutterView, "foo");Copy the code
-
Native iOS:
let channel = FlutterMethodChannel( name: "foo", binaryMessenger: flutterView) Copy the code
Setting up a communication channel is as simple as creating a MethodChannel with the same name (such as “foo” in the example above).
In a large project. You may need to set up many communication channels, so it is recommended to manage them uniformly.
2.2 Flutter to Native
Establish a communication channel to see how to make Flutter actively communicate with Native.
-
The Flutter end:
final String greeting = await channel.invokeMethod('bar'.'world'); print(greeting);Copy the code
The invokeMethod(< identity >, < data >) function can initiate a communication with Native and get a response. The allowed data types are the data types listed in the previous table.
Of course, in order not to block the UI, you need to do it asynchronously.
-
Native Android terminal:
channel.setMethodCallHandler((methodCall, result) -> { if (methodCall.method.equals("bar")) { result.success("success, "+ methodCall.arguments); }});Copy the code
On the Native side, you set up a handler for the MethodChannel, MethodCallHandler.
A Flutter can call back to the handler’s onMethodCall() function when it initiates a communication to Native.
In this callback, you can get information from the Flutter via MethodCall and send response results to the Flutter via methodChannel. Result.
-
Native iOS:
channel.setMethodCallHandler { (call: FlutterMethodCall, result: FlutterResult) -> Void in switch (call.method) { case "bar": result("Hello, \(call.arguments as! String)") default: result(FlutterMethodNotImplemented) } } Copy the code
2.3 Native to Flutter
-
The Flutter end:
Set up the processor to receive Native information:
channel.setMethodCallHandler((MethodCall call) async { switch (call.method) { case 'bar': return 'Hello, ${call.arguments}'; case 'baz': throw PlatformException(code: '400', message: 'This is bad'); default: throw MissingPluginException(); }})Copy the code
Set a Future< Dynamic > handler(MethodCall Call) function with the setMethodCallHandler function.
This function is called when it receives the Native message, and you get the data sent by Native from the MethodCall.
The final return link can return data to Native.
-
Native Android terminal:
channel.invokeMethod("bar"."message". New methodChannel. result@override public void success(@nullable Object o) Error (String s, @nullable String s1, @nullable // Callback if sending fails} @override public voidnotImplemented() {// If this channel is not implemented at the Flutter end, it will be called back here}});Copy the code
The first parameter is the label obtained by call.method on the Flutter end.
The second parameter is the data to send.
The third parameter listens for the completed state of the communication.
-
Native iOS:
channel.invokeMethod(name, arguments: value) { (result: Any?) -> Void in if let error = result as? FlutterError { os_log("%@ failed: %@".type: .error, name, error.message!) } else if FlutterMethodNotImplemented.isEqual(result) { os_log("%@ not implemented".type: .error, name) } else { os_log("% @".type: .info, result as! NSObject) } }Copy the code
Directory Portals: A Guide to The Quick Start To Flutter
How can I be found?
Portal:CoorChice homepage
Portal:Lot of CoorChice