Flutter系列 — Flutter与原生进行通信
项目git地址: demo地址
flutter无法直接调用系统相机、麦克风、定位、手机版本信息等,此时就需要与原生方法进行交互了。
需求
目前我们已经有了一个flutter项目(工程名称flutter_app
), 但是我们要获取系统版本信息
方案
我们需要定义一个flutter插件获取系统信息。
这里开发工具使用Android Studio 点击 File --> New --> New Flutter Project
- 选择 Flutter Plugin
点击Finish会自动创建完成.
找到deviceInfo中的lib/deviceinfo.dart,
定义方法渠道, 渠道名为deviceinfo, (渠道名必须和原生定义的一模一样)
import 'dart:async';
import 'package:flutter/services.dart';
class Deviceinfo {
static const MethodChannel _channel =
const MethodChannel('deviceinfo');
static Future<String> get systemVersion async {
final String version = await _channel.invokeMethod('getSystemVersion');
return version;
}
}
MethodChannel是和原生建立的方法通道, 通过MethodChannel和原生相互通信, invokeMethod
编辑iOS代码
找到以下路径代码
.../flutter_app/plugin/device_info/ios/Classes/DeviceinfoPlugin.m
判断flutter传过来的方法名, 回调给flutter层
#import "DeviceinfoPlugin.h"
@implementation DeviceinfoPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"deviceinfo"
binaryMessenger:[registrar messenger]];
DeviceinfoPlugin* instance = [[DeviceinfoPlugin alloc] init];
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([@"getSystemVersion" isEqualToString:call.method]) {
result([[UIDevice currentDevice] systemVersion]);
} else {
result(FlutterMethodNotImplemented);
}
}
@end
编辑Android代码
找到以下路径代码
.../flutter_app/plugin/device_info/android/src/main/java/com/example/deviceinfo/DeviceinfoPlugin.java
package com.example.deviceinfo;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
public class DeviceinfoPlugin implements FlutterPlugin, MethodCallHandler {
private MethodChannel channel;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "deviceinfo");
channel.setMethodCallHandler(this);
}
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "deviceinfo");
channel.setMethodCallHandler(new DeviceinfoPlugin());
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if (call.method.equals("getSystemVersion")) {
result.success(android.os.Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
}
使用device_info插件
找到项目中的pubspec.yaml, 引入deviceinfo, 并在终端执行
$ flutter pub get
dependencies:
flutter:
sdk: flutter
deviceinfo:
path: plugin/device_info
在flutter项目中使用
- 导入: import ‘package:deviceinfo/deviceinfo.dart’;
- 调用: String version = await Deviceinfo.systemVersion;
import 'package:flutter/material.dart';
import 'package:deviceinfo/deviceinfo.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _systemVersion = '';
@override
void initState() {
initSysVersion();
super.initState();
}
initSysVersion() async {
String version = await Deviceinfo.systemVersion;
setState(() {
_systemVersion = version;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text('系统版本: $_systemVersion'),
),
);
}
}
iOS效果:
安卓效果
喜欢就给个star吧
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)