【Flutter 混合开发】嵌入原生View-Android
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064503082-1012068586.png"></p><blockquote>
<p>Flutter 混合开发系列 包含如下:</p>
<ul>
<li><strong>嵌入原生View-Android</strong></li>
<li>嵌入原生View-IOS</li>
<li>与原生通信-MethodChannel</li>
<li>与原生通信-BasicMessageChannel</li>
<li>与原生通信-EventChannel</li>
<li>添加 Flutter 到 Android Activity</li>
<li>添加 Flutter 到 Android Fragment</li>
<li>添加 Flutter 到 iOS</li>
</ul>
<p>每个工作日分享一篇,欢迎关注、点赞及转发。</p>
</blockquote>
<h3 id="androidview">AndroidView</h3>
<p>建议使用 Android Studio 进行开发,在 Android Studio 左侧 project tab下选中 android 目录下任意一个文件,右上角会出现 <strong>Open for Editing in Android Studio</strong> ,</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064503598-1819671722.png"></p>
<p>点击即可打开,打开后 project tab 并不是一个 Android 项目,而是项目中所有 Android 项目,包含第三方:</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064503971-1209369879.png"></p>
<p>app 目录是当前项目的 android 目录,其他则是第三方的 android 目录。</p>
<p>在<strong>App</strong> 项目的 <strong>java/包名</strong> 目录下创建嵌入 Flutter 中的 Android View,此 View 继承 <strong>PlatformView</strong> :</p>
<pre><code class="language-dart">class MyFlutterView(context: Context) : PlatformView {
override fun getView(): View {
TODO("Not yet implemented")
}
override fun dispose() {
TODO("Not yet implemented")
}
}
</code></pre>
<ul>
<li><strong>getView</strong> :返回要嵌入 Flutter 层次结构的Android View</li>
<li><strong>dispose</strong>:释放此View时调用,此方法调用后 View 不可用,此方法需要清除所有对象引用,否则会造成内存泄漏。</li>
</ul>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064504166-315236155.png"></p>
<p>返回一个简单的 <strong>TextView</strong> :</p>
<pre><code class="language-dart">class MyFlutterView(context: Context, messenger: BinaryMessenger, viewId: Int, args: Map<String, Any>?) : PlatformView {
val textView: TextView = TextView(context)
init {
textView.text = "我是Android View"
}
override fun getView(): View {
return textView
}
override fun dispose() {
TODO("Not yet implemented")
}
}
</code></pre>
<ul>
<li><strong>messenger</strong>:用于消息传递,后面介绍 Flutter 与 原生通信时用到此参数。</li>
<li><strong>viewId</strong>:View 生成时会分配一个唯一 ID。</li>
<li><strong>args</strong>:Flutter 传递的初始化参数。</li>
</ul>
<h3 id="注册platformview">注册PlatformView</h3>
<p>创建PlatformViewFactory:</p>
<pre><code class="language-dart">class MyFlutterViewFactory(val messenger: BinaryMessenger) : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
val flutterView = MyFlutterView(context, messenger, viewId, args as Map<String, Any>?)
return flutterView
}
}
</code></pre>
<p>创建 <strong>MyPlugin</strong> :</p>
<pre><code class="language-dart">class MyPlugin : FlutterPlugin {
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
val messenger: BinaryMessenger = binding.binaryMessenger
binding
.platformViewRegistry
.registerViewFactory(
"plugins.flutter.io/custom_platform_view", MyFlutterViewFactory(messenger))
}
companion object {
@JvmStatic
fun registerWith(registrar: PluginRegistry.Registrar) {
registrar
.platformViewRegistry()
.registerViewFactory(
"plugins.flutter.io/custom_platform_view",
MyFlutterViewFactory(registrar.messenger()))
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
}
}
</code></pre>
<p>记住 <strong>plugins.flutter.io/custom_platform_view</strong> ,这个字符串在 Flutter 中需要与其保持一致。</p>
<p>在 <strong>App 中 MainActivity</strong> 中注册:</p>
<pre><code class="language-dart">class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine.plugins.add(MyPlugin())
}
}
</code></pre>
<p>如果是 Flutter Plugin,没有<strong>MainActivity</strong>,则在对应的 <strong>Plugin onAttachedToEngine 和 registerWith</strong> 方法修改如下:</p>
<pre><code class="language-dart">public class CustomPlatformViewPlugin : FlutterPlugin,MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel: MethodChannel
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "custom_platform_view")
channel.setMethodCallHandler(this)
val messenger: BinaryMessenger = flutterPluginBinding.binaryMessenger
flutterPluginBinding
.platformViewRegistry
.registerViewFactory(
"plugins.flutter.io/custom_platform_view", MyFlutterViewFactory(messenger))
}
// This static function is optional and equivalent to onAttachedToEngine. It supports the old
// pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
// plugin registration via this function while apps migrate to use the new Android APIs
// post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
//
// It is encouraged to share logic between onAttachedToEngine and registerWith to keep
// them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
// depending on the user's project. onAttachedToEngine or registerWith must both be defined
// in the same class.
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "custom_platform_view")
channel.setMethodCallHandler(CustomPlatformViewPlugin())
registrar
.platformViewRegistry()
.registerViewFactory(
"plugins.flutter.io/custom_platform_view",
MyFlutterViewFactory(registrar.messenger()))
}
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
</code></pre>
<h3 id="嵌入flutter">嵌入Flutter</h3>
<p>在 Flutter 中调用</p>
<pre><code class="language-dart">class PlatformViewDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
Widget platformView(){
if(defaultTargetPlatform == TargetPlatform.android){
return AndroidView(
viewType: 'plugins.flutter.io/custom_platform_view',
);
}
}
return Scaffold(
appBar: AppBar(),
body: Center(
child: platformView(),
),
);
}
}
</code></pre>
<p>上面嵌入的是 Android View,因此通过 <strong>defaultTargetPlatform == TargetPlatform.android</strong> 判断当前平台加载,在 Android 上运行效果:</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064504379-1988154117.jpg"></p>
<h3 id="设置初始化参数">设置初始化参数</h3>
<p>Flutter 端修改如下:</p>
<pre><code class="language-dart">AndroidView(
viewType: 'plugins.flutter.io/custom_platform_view',
creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
)
</code></pre>
<ul>
<li><strong>creationParams</strong> :传递的参数,插件可以将此参数传递给 AndroidView 的构造函数。</li>
<li><strong>creationParamsCodec</strong> :将 creationParams 编码后再发送给平台侧,它应该与传递给构造函数的编解码器匹配。值的范围:
<ul>
<li>StandardMessageCodec</li>
<li>JSONMessageCodec</li>
<li>StringCodec</li>
<li>BinaryCodec</li>
</ul>
</li>
</ul>
<p>修改 MyFlutterView :</p>
<pre><code class="language-dart">class MyFlutterView(context: Context, messenger: BinaryMessenger, viewId: Int, args: Map<String, Any>?) : PlatformView {
val textView: TextView = TextView(context)
init {
args?.also {
textView.text = it["text"] as String
}
}
override fun getView(): View {
return textView
}
override fun dispose() {
TODO("Not yet implemented")
}
}
</code></pre>
<p>最终效果:</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064504633-847313301.jpg"></p>
<h3 id="flutter-向-android-view-发送消息">Flutter 向 Android View 发送消息</h3>
<p>修改 Flutter 端,创建 <strong>MethodChannel</strong> 用于通信:</p>
<pre><code class="language-dart">class PlatformViewDemo extends StatefulWidget {
@override
_PlatformViewDemoState createState() => _PlatformViewDemoState();
}
class _PlatformViewDemoState extends State<PlatformViewDemo> {
static const platform =
const MethodChannel('com.flutter.guide.MyFlutterView');
@override
Widget build(BuildContext context) {
Widget platformView() {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidView(
viewType: 'plugins.flutter.io/custom_platform_view',
creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
);
}
}
return Scaffold(
appBar: AppBar(),
body: Column(children: [
RaisedButton(
child: Text('传递参数给原生View'),
onPressed: () {
platform.invokeMethod('setText', {'name': 'laomeng', 'age': 18});
},
),
Expanded(child: platformView()),
]),
);
}
}
</code></pre>
<p>在 原生View 中也创建一个 <strong>MethodChannel</strong> 用于通信:</p>
<pre><code class="language-dart">class MyFlutterView(context: Context, messenger: BinaryMessenger, viewId: Int, args: Map<String, Any>?) : PlatformView, MethodChannel.MethodCallHandler {
val textView: TextView = TextView(context)
private var methodChannel: MethodChannel
init {
args?.also {
textView.text = it["text"] as String
}
methodChannel = MethodChannel(messenger, "com.flutter.guide.MyFlutterView")
methodChannel.setMethodCallHandler(this)
}
override fun getView(): View {
return textView
}
override fun dispose() {
methodChannel.setMethodCallHandler(null)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method == "setText") {
val name = call.argument("name") as String?
val age = call.argument("age") as Int?
textView.text = "hello,$name,年龄:$age"
} else {
result.notImplemented()
}
}
}
</code></pre>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064504862-1663917239.gif"></p>
<h3 id="flutter-向-android-view-获取消息">Flutter 向 Android View 获取消息</h3>
<p>与上面发送信息不同的是,Flutter 向原生请求数据,原生返回数据到 Flutter 端,修改 <strong>MyFlutterView onMethodCall</strong>:</p>
<pre><code class="language-dart">override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method == "setText") {
val name = call.argument("name") as String?
val age = call.argument("age") as Int?
textView.text = "hello,$name,年龄:$age"
} else if (call.method == "getData") {
val name = call.argument("name") as String?
val age = call.argument("age") as Int?
var map = mapOf("name" to "hello,$name",
"age" to "$age"
)
result.success(map)
} else {
result.notImplemented()
}
}
</code></pre>
<p><strong>result.success(map)</strong> 是返回的数据。</p>
<p>Flutter 端接收数据:</p>
<pre><code class="language-dart">var _data = '获取数据';
RaisedButton(
child: Text('$_data'),
onPressed: () async {
var result = await platform
.invokeMethod('getData', {'name': 'laomeng', 'age': 18});
setState(() {
_data = '${result['name']},${result['age']}';
});
},
),
</code></pre>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064505036-1577375267.gif"></p>
<h3 id="解决多个原生view通信冲突问题">解决多个原生View通信冲突问题</h3>
<p>当然页面有3个原生View,</p>
<pre><code class="language-dart">class PlatformViewDemo extends StatefulWidget {
@override
_PlatformViewDemoState createState() => _PlatformViewDemoState();
}
class _PlatformViewDemoState extends State<PlatformViewDemo> {
static const platform =
const MethodChannel('com.flutter.guide.MyFlutterView');
var _data = '获取数据';
@override
Widget build(BuildContext context) {
Widget platformView() {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidView(
viewType: 'plugins.flutter.io/custom_platform_view',
creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
);
}
}
return Scaffold(
appBar: AppBar(),
body: Column(children: [
Row(
children: [
RaisedButton(
child: Text('传递参数给原生View'),
onPressed: () {
platform
.invokeMethod('setText', {'name': 'laomeng', 'age': 18});
},
),
RaisedButton(
child: Text('$_data'),
onPressed: () async {
var result = await platform
.invokeMethod('getData', {'name': 'laomeng', 'age': 18});
setState(() {
_data = '${result['name']},${result['age']}';
});
},
),
],
),
Expanded(child: Container(color: Colors.red, child: platformView())),
Expanded(child: Container(color: Colors.blue, child: platformView())),
Expanded(child: Container(color: Colors.yellow, child: platformView())),
]),
);
}
}
</code></pre>
<p>此时点击 <strong>传递参数给原生View</strong> 按钮哪个View会改变内容,实际上只有最后一个会改变。</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064505180-1602548502.gif"></p>
<p>如何改变指定View的内容?重点是 <strong>MethodChannel</strong>,只需修改上面3个通道的名称不相同即可:</p>
<ul>
<li><strong>第一种方法</strong>:将一个唯一 id 通过初始化参数传递给原生 View,原生 View使用这个id 构建不同名称的 <strong>MethodChannel</strong>。</li>
<li><strong>第二种方法(推荐)</strong>:原生 View 生成时,系统会为其生成唯一id:viewId,使用 viewId 构建不同名称的 <strong>MethodChannel</strong>。</li>
</ul>
<p>原生 View 使用 viewId 构建不同名称的 <strong>MethodChannel</strong>:</p>
<pre><code class="language-dart">class MyFlutterView(context: Context, messenger: BinaryMessenger, viewId: Int, args: Map<String, Any>?) : PlatformView, MethodChannel.MethodCallHandler {
val textView: TextView = TextView(context)
private var methodChannel: MethodChannel
init {
args?.also {
textView.text = it["text"] as String
}
methodChannel = MethodChannel(messenger, "com.flutter.guide.MyFlutterView_$viewId")
methodChannel.setMethodCallHandler(this)
}
...
}
</code></pre>
<p>Flutter 端为每一个原生 View 创建不同的<strong>MethodChannel</strong>:</p>
<pre><code class="language-dart">var platforms = [];
AndroidView(
viewType: 'plugins.flutter.io/custom_platform_view',
onPlatformViewCreated: (viewId) {
print('viewId:$viewId');
platforms
.add(MethodChannel('com.flutter.guide.MyFlutterView_$viewId'));
},
creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
)
</code></pre>
<p>给第一个发送消息:</p>
<pre><code class="language-dart">platforms
.invokeMethod('setText', {'name': 'laomeng', 'age': 18});
</code></pre>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064505324-1400359542.gif"></p>
<h2 id="交流">交流</h2>
<p>老孟Flutter博客(330个控件用法+实战入门系列文章):http://laomengit.com</p>
<p>欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】:</p>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064506609-1877459387.png"></td>
<td><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201014064507027-1155517800.png"></td>
</tr>
</tbody>
</table><br><br>
来源:https://www.cnblogs.com/mengqd/p/13812639.html
頁:
[1]