Flutter之Flutter布局中加入原生View

  在先前的两篇文章中,介绍了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然后做出文本的改变。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容