-
系列文章
flutter与原生交互传值OC/java版(一)
flutter与原生交互传值OC/java版(二)
四步实现flutter显示iOS原生组件OC/java版(三)
四步实现flutter显示安卓原生组件OC/java版(三)
本demo的github地址:https://github.com/iBinbro/flutterstudy
说在前头:flutter虽然很牛掰,但是目前很多功能或者插件的实现其实还是需要通过原生来实现,然后通过flutter和原生的交互传值实现数据的交换。
-本篇是flutter调用原生方法,然后原生执行完毕后返值给flutter
-由原生主动传值给flutter请看flutter plugin之路:flutter与原生交互传值OC/java版(二)
实现目标,flutter进行页面布局,画一个按钮,点击按钮调用原生平台的方法返回内容再用按钮小部件显示
一、flutter端的实现
1.创建TwoCommunicate类(statefulwidget),
2._nativeCallBackValue是存放flutter和native相互通信的结果
3.创建通道标识,实现flutter调用native的方法
_communicateFunction
4.build方法实现布局,并添加点击事件来调用_communicateFunction方法
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
class TwoCommunicate extends StatefulWidget {
@override
_TwoCommunicateState createState() => _TwoCommunicateState();
}
class _TwoCommunicateState extends State<TwoCommunicate> {
String _nativeCallBackValue = '等待原生传值';
//交互的通道名称,flutter和native是通过这个标识符进行相互间的通信
static const communicateChannel = MethodChannel('https://www.jianshu.com/u/ee3db73e5459');
//异步执行调用原生方法,保持页面不卡住,因为调用原生的方法可能没实现会抛出异常,所以trycatch包住
Future<void> _communicateFunction(flutterPara) async {
try {
//原生方法名为callNativeMethond,flutterPara为flutter调用原生方法传入的参数,await等待方法执行
final result = await communicateChannel.invokeMethod('callNativeMethond', flutterPara);
//如果原生方法执行回调传值给flutter,那下面的代码才会被执行
_nativeCallBackValue = result;
} on PlatformException catch (e) {//抛出异常
//flutter: PlatformException(001, 进入异常处理, 进入flutter的trycatch方法的catch方法)
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('text'),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
MaterialButton(
color: Colors.blue,
child: Text(_nativeCallBackValue),
onPressed: () {
_communicateFunction('flutter传值');
setState(() {});
},
),
],
),
),
),
);
}
}
二、原生端iOS OC的实现,
先运行下工程,避免打开ios工程缺少文件,然后在工程目录进入ios文件夹,打开Runner.xcworkspace,使用xcode进行原生代码的编写
1.创建通道并实现通道的回调方法
2、在回调方法里获取flutter调取原生的方法名和传入的参数
3、利用回调方法里的result实现原生对flutter的传值
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
__weak __typeof(self) weakself = self;
FlutterViewController *controller = (FlutterViewController *)self.window.rootViewController;
//通道标识,要和flutter端的保持一致
FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"https://www.jianshu.com/u/ee3db73e5459" binaryMessenger:controller];
//flutter端通过通道调用原生方法时会进入以下回调
[channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
//call的属性method是flutter调用原生方法的方法名,我们进行字符串判断然后写入不同的逻辑
if ([call.method isEqualToString:@"callNativeMethond"]) {
//flutter传给原生的参数
id para = call.arguments;
NSLog(@"flutter传给原生的参数:%@", para);
//获取一个字符串
NSString *nativeFinalStr = [weakself getString];
if (nativeFinalStr!=nil) {
//把获取到的字符串传值给flutter
result(nativeFinalStr);
}else{
//异常(比如改方法是调用原生的getString获取一个字符串,但是返回的是nil(空值),这显然是不对的,就可以向flutter抛出异常 进入catch处理)
result([FlutterError errorWithCode:@"001" message:[NSString stringWithFormat:@"进入异常处理"] details:@"进入flutter的trycatch方法的catch方法"]);
}
}else{
//调用的方法原生没有对应的处理 抛出未实现的异常
result(FlutterMethodNotImplemented);
}
}];
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
//返回一个字符串
- (NSString *)getString{
// return nil;//返回nil进入异常的情景
return @"原生传给flutter的值";
}
@end
附表:互相传值 不同平台间值类型的对应关系
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 |