2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > flutter methodchannel调用原生方法 实现原生插件

flutter methodchannel调用原生方法 实现原生插件

时间:2021-01-15 20:15:48

相关推荐

flutter methodchannel调用原生方法 实现原生插件

在获取手机电量,屏幕信息等,都需要flutter 调用原生实现,这部分flutter 官方已经帮我们实现好了,对于部分功能,需要自己实现, 步骤如下

# 创建一个 flutter 应用,使用 as 打开 android 目录, MainActivity 代码如下package com.example.flutter_app;import android.content.Intent;import .Uri;import android.os.Bundle;import java.util.Map;import io.flutter.app.FlutterActivity;import io.mon.MethodCall;import io.mon.MethodChannel;import io.flutter.plugins.GeneratedPluginRegistrant;public class MainActivity extends FlutterActivity {private static final String CHANNEL = "/info";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);GeneratedPluginRegistrant.registerWith(this);new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {@Overridepublic void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {final Map<String, Object> arguments = methodCall.arguments();if (methodCall.method.equals("getMessage")) {result.success("Android say hi."+ ((String) arguments.get("from")));}// openWebPage("");}});}public void openWebPage(String url) {Uri webpage = Uri.parse(url);Intent intent = new Intent(Intent.ACTION_VIEW, webpage);if (intent.resolveActivity(getPackageManager()) != null) {startActivity(intent);}}}

# ios 端 appDelegate.m#include "AppDelegate.h"#include "GeneratedPluginRegistrant.h"@implementation AppDelegate- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[GeneratedPluginRegistrant registerWithRegistry:self];// Override point for customization after application launch.FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;FlutterMethodChannel* channel = [FlutterMethodChannelmethodChannelWithName:@"/info"binaryMessenger:controller];[channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {NSString *from = call.arguments[@"from"];if([@"getMessage" isEqualToString:call.method]) {NSString *messgae = @"IOS says greetings";NSString *returnMessage = [messgae stringByAppendingString:from];result(returnMessage);}}];return [super application:application didFinishLaunchingWithOptions:launchOptions];}@end

# flutter 端 main.dart 编写如下代码static const platform = const MethodChannel('/info');String _message = 'No message yet...';Future<String> _getMessage() async {var sendMap = <String, dynamic> {'from' : 'boy',};String value;try {value = await platform.invokeMethod('getMessage', sendMap);} catch(e) {print(e);}return value;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。