在先前的两篇文章中,介绍了flutter 与原生android通信,以及在原有工程中加入flutter view或是flutter的新页面。
flutter功能很强大不仅仅有自己的ui库,也能像rn那样封装原生view来实现更好的ui,地图和webview和相机就是觉见的封装。
在这里先用textview文本组件举例,效果图如图一。
图一
在Android工程中编写并注册原生组件
- 添加原生组件的流程基本是这样的:
1.实现原生组件PlatformView提供原生view
2.创建PlatformViewFactory用于生成PlatformView
3.创建FlutterPlugin用于注册原生组件
实现原生组件PlatformView提供原生view
在这里我定义一个myview的类,实现PlatformView(flutter定义的接口类,如图二)。
图二
MyView.java
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;
public class MyView implements PlatformView , MethodChannel.MethodCallHandler{
private final TextView natvieTextView;
Context context;
public MyView(Context context, BinaryMessenger messenger, int id, Map<String, Object> params) {
this.context = context;
TextView myNativeView = new TextView(context);
myNativeView.setText("我是来自Android的原生TextView");
if (params.containsKey("myContent")) {
String myContent = (String) params.get("myContent");
myNativeView.setText(myContent);
}
this.natvieTextView = myNativeView;
MethodChannel methodChannel = new MethodChannel(messenger, "plugins.nightfarmer.top/myview_" + id);
methodChannel.setMethodCallHandler(this);
}
@Override
public View getView() {
return natvieTextView;
}
@Override
public void dispose() {
}
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if ("setText".equals(call.method)) {
String text = (String) call.arguments;
natvieTextView.setText(text);
result.success(null);
Intent intent = new Intent();
intent.setClass(context, LoginActivity.class);
context.startActivity(intent);
}
}
}
MyView中onMethodCall是用于处理flutter与原生view交互的,如果不需要交互的话可以不用实现MethodChannel.MethodCallHandler。
创建PlatformViewFactory用于生成PlatformView
package com.woshiku.flutter_rn.plugin;
import com.woshiku.flutter_rn.factory.MyViewFactory;
import io.flutter.plugin.common.PluginRegistry;
public class MyViewFlutterPlugin {
public static void registerWith(PluginRegistry registry) {
final String key = MyViewFlutterPlugin.class.getCanonicalName();
if (registry.hasPlugin(key)) return;
PluginRegistry.Registrar registrar = registry.registrarFor(key);
registrar.platformViewRegistry().registerViewFactory("plugins.woshiku.top/myview", new MyViewFactory(registrar.messenger()));
}
}
创建FlutterPlugin用于注册原生组件
package com.woshiku.flutter_rn.factory;
import android.content.Context;
import com.woshiku.flutter_rn.view.MyView;
import java.util.Map;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
public class MyViewFactory extends PlatformViewFactory {
private final BinaryMessenger messenger;
public MyViewFactory(BinaryMessenger messenger) {
super(StandardMessageCodec.INSTANCE);
this.messenger = messenger;
}
@SuppressWarnings("unchecked")
@Override
public PlatformView create(Context context, int id, Object args) {
Map<String, Object> params = (Map<String, Object>) args;
return new MyView(context, messenger, id, params);
}
}
上面代码中使用了plugins.woshiku.top/myview这样一个字符串,这是组件的注册名称,在Flutter调用时需要用到,你可以使用任意格式的字符串。
在MainActivity的onCreate方法中增加注册调用
package com.woshiku.flutter_rn;
import android.content.Intent;
import android.os.Bundle;
import com.woshiku.flutter_rn.plugin.MyViewFlutterPlugin;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
//channel的名称,由于app中可能会有多个channel,这个名称需要在app内是唯一的。
private static final String CHANNEL = "woshiku.flutter.io/launchApp";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
MyViewFlutterPlugin.registerWith(this);
}
}
在flutter文件中dart写法
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
static const platform = const MethodChannel('woshiku.flutter.io/launchApp');
Future<Null> launchLogin() async {
try {
final String result = await platform.invokeMethod('launchLogin');
print(result);
} on PlatformException catch (e) {
}
}
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
//setMyViewText('woshiku'+_counter.toString());
print(window.defaultRouteName);
//launchLogin();
});
}
MethodChannel _channel;
void onMyViewCreated(int id) {
_channel = new MethodChannel('plugins.woshiku.top/myview_$id');
}
Future<void> setMyViewText(String text) async {
assert(text != null);
return _channel.invokeMethod('setText', text);
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times lala:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
Container(
width: 200,
height: 100,
child: AndroidView(
viewType: 'plugins.woshiku.top/myview',
creationParams: {
"myContent": "通过参数传入的文本内容,I am 原生view",
},
creationParamsCodec: const StandardMessageCodec(),
onPlatformViewCreated: this.onMyViewCreated,
),
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
其中
Container(
width: 200,
height: 100,
child: AndroidView(
viewType: 'plugins.woshiku.top/myview',
creationParams: {
"myContent": "通过参数传入的文本内容,I am 原生view",
}
),
)
因为只是实现了Android平台,所以这里直接调用了AndroidView,如果你是双平台的实现,则可以通过引入package:flutter/foundation.dart包,并判断defaultTargetPlatform是TargetPlatform.android还是TargetPlatform.iOS来引入不同平台的实现。
给原生view增加参数
creationParams传入了一个map参数,并由原生组件接收,creationParamsCodec传入的是一个编码对象这是固定写法。对就原生view的写法,不过只个只可用于初始化,后面如果要改动参数,文本是无法改变,所以在这里要入通信功能。
public class MyView implements PlatformView {
private final TextView natvieTextView;
Context context;
public MyView(Context context, BinaryMessenger messenger, int id, Map<String, Object> params) {
this.context = context;
TextView myNativeView = new TextView(context);
myNativeView.setText("我是来自Android的原生TextView");
if (params.containsKey("myContent")) {
String myContent = (String) params.get("myContent");
myNativeView.setText(myContent);
}
this.natvieTextView = myNativeView;
}
@Override
public View getView() {
return natvieTextView;
}
@Override
public void dispose() {
}
}
}
通过MethodChannel与原生组件通讯
public class MyView implements PlatformView , MethodChannel.MethodCallHandler{
private final TextView natvieTextView;
Context context;
public MyView(Context context, BinaryMessenger messenger, int id, Map<String, Object> params) {
this.context = context;
TextView myNativeView = new TextView(context);
myNativeView.setText("我是来自Android的原生TextView");
if (params.containsKey("myContent")) {
String myContent = (String) params.get("myContent");
myNativeView.setText(myContent);
}
this.natvieTextView = myNativeView;
MethodChannel methodChannel = new MethodChannel(messenger, "plugins.nightfarmer.top/myview_" + id);
methodChannel.setMethodCallHandler(this);
}
@Override
public View getView() {
return natvieTextView;
}
@Override
public void dispose() {
}
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if ("setText".equals(call.method)) {
String text = (String) call.arguments;
natvieTextView.setText(text);
result.success(null);
//下面是只己的其它尝试,不用拷备
Intent intent = new Intent();
intent.setClass(context, LoginActivity.class);
context.startActivity(intent);
}
}
}
对应dart代码
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
MethodChannel _channel;
void onMyViewCreated(int id) {
_channel = new MethodChannel('plugins.woshiku.top/myview_$id');
}
Future<void> setMyViewText(String text) async {
assert(text != null);
return _channel.invokeMethod('setText', text);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times lala:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
Container(
width: 200,
height: 100,
child: AndroidView(
viewType: 'plugins.woshiku.top/myview',
creationParams: {
"myContent": "通过参数传入的文本内容,I am 原生view",
},
creationParamsCodec: const StandardMessageCodec(),
onPlatformViewCreated: this.onMyViewCreated,
),
)
],
),
)
);
}
}
如果要改变文字内容调用setMyViewText,由flutter回给给原生view然后做出文本的改变。
网友评论