flutter 判断字符创_Flutter 解决 与 原生 语言调用

1e25caa2160b001e6a2c9bd503bfd891.png

解决有方案以下 :

1.FLutter 与 原生 调用


一 . 使用 FLutter_Android 插件,里面 包含了 一些 系统 API,

adress: https://pub.dev/packages/flutter_android

优点: 体积小 ,很方便。

缺点: 有很多没有的 系统的API 。

二 .使用 MethodChannel 的方法: (推介)

Flutter UI:

class PlatformTestBody extends StatefulWidget {
  @override
  PlatformTestBodyState createState() {
    return new PlatformTestBodyState();
  }
}

class PlatformTestBodyState extends State<PlatformTestBody> { 
@override
  Widget build(BuildContext context) {
    return new Container(
      color: Colors.pinkAccent,
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          new Padding(
            padding: const EdgeInsets.only(left: 18.0, top: 200.0),
            child: new Text(
              'Tap the button to change your life!',
              style: new TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  fontSize: 23.0),
            ),
          ),
          new Padding(
            padding: const EdgeInsets.only(left: 8.0, right: 8.0, top: 102.0),
            child: new RaisedButton(
              child: new Text('Click Me'),
              onPressed: () => doNativeSuff(),
            ),
          ),
          new Padding(
            padding: const EdgeInsets.only(left: 8.0, right: 8.0, top: 102.0),
            child: new Text(
              nativeMessage,
              style: new TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  fontSize: 23.0),
            ),
          )
        ],
      ),
    );
  }}

FLutter MethodChanenl:

1.使用 Methodchannel方法 参数(随便字符),

2.在异步方法中调用.

 // 1. 调用, 和 java 端 一样的代码
  static const platformMethodChannel = const MethodChannel('com.test/test');
//  2.异步方法 ,
  Future<Null> doNativeSuff() async {
    String _message; // 1
    try {
//      2.1 调用 频道本地的方法,返回的为字符串
      final String result =
      await platformMethodChannel.invokeMethod('changeLife');// 2
//      2.2把 返回的值 返回给 message.
      _message = result;
      print(result);
    } on PlatformException catch (e) {
      _message = "Sadly I can not change your life: ${e.message}.";
    }
//    2.3 动态设置
    setState(() {
      nativeMessage = _message; // 3
    });

  }

Java MethodChanenl:

1.导包

2,MethodChannel() 方法,

参数:getflutterView,字符串(同flutter),

设置方法呼叫处理者,参数 新 方法呼叫处理者.

3.新 方法呼叫处理者 中 的onMethodCall 方法中 判断 ,methodCall(从flutter 发送过来的参数,result 返回去的结果)

4.methodCall 付出 这个就执行方法,result 返回 成功,参数 字符串

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; 

//  1.标记一模一样的 代码
    private static final String CHANNEL = "com.test/test";


@Override
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//    2.参证 未这个Flutter 的代码
        GeneratedPluginRegistrant.registerWith(this);

//    3. 方法响应,拿flutterView,名字,设置方法呼叫 处理者
        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
//            3.1 喂新的 handler ,有一个 默认启动的方法
                new MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall methodCall, Result result) {
//             3.2 methodcall 请求的信息result 发送的信息
                        if (methodCall.method.equals("changeLife")) {
                            String message = "Life Changed";
// 返回 结果
                            result.success(message);
                        }

                    }
                }
        );// 重点
    }

二. 从 原生 Language 发送到 Flutter

EventChannel

Flutter
// 1. 事件频道,p 字符串
  static const EventChannel eventChannel = EventChannel('samples.flutter.io/charging');
//    2.开始事件接收,p 数据,错误
    eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
//  p data
  void _onEvent(Object event) {
    setState(() {
      _chargingStatus =
      "Battery status: ${event == 'charging' ? '' : 'dis'}charging.";
    });
  }
// p error
  void _onError(Object error) {
    setState(() {
//      返回的为频道的 错误
 PlatformException exception = error;
      _chargingStatus = exception?.message ?? 'Battery status: unknown.';
    });
  }
Java

(registerReceiver(null,newIntentFilter(Intent.ACTION_BATTERY_CHANGED));)

后面的是标记,只有电池该的时候才使用

//  1.字符串(same futter)
    private static final String CHARGING_CHANNEL = "samples.flutter.io/charging";
  //2. 事件频道 参数,getFlutterView,字符串,
//        2.1设置 流处理者
        new EventChannel(getFlutterView(), CHARGING_CHANNEL).setStreamHandler(
//             2.2   事件处理者
                new EventChannel.StreamHandler() {
//                    2.3 广播接收者
                    private BroadcastReceiver chargingStateChangeReceiver;
                    @Override
//                    2.4 在接收的时候
                    public void onListen(Object arguments, EventChannel.EventSink events) {
//                        2.5 创建 广播接收者,参数 返回的事件
                        chargingStateChangeReceiver = createChargingStateChangeReceiver(events);
//                        3.把 做好的 事件 注册,过滤改变
                        registerReceiver(
                                chargingStateChangeReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                    }

                    @Override
                    public void onCancel(Object arguments) {
//                        外卖调用取消的时候 把广播注销
                        unregisterReceiver(chargingStateChangeReceiver);
//                        并设置为 空
                        chargingStateChangeReceiver = null;
                    }
                }
        );
//         2.6 创建 广播接收者,参数 返回的事件  TODO ,主要做 逻辑 判断
    private BroadcastReceiver createChargingStateChangeReceiver(final EventChannel.EventSink events) {
        return new BroadcastReceiver() {
//            2.7 在接收的时候
            @Override
            public void onReceive(Context context, Intent intent) {
//                2.8 意图,特别的 包裹,那现在的 电池值
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//2.9 如果 等于 等于不知道 返回信息, 错误
                if (status == BatteryManager.BATTERY_STATUS_UNKNOWN) {
                    events.error("UNAVAILABLE", "Charging status unavailable", null);
                } else {
//                    3. 不是返回成功
                    boolean isCharging =
                            status == BatteryManager.BATTERY_STATUS_CHARGING ||
                            status == BatteryManager.BATTERY_STATUS_FULL;
                    events.success(isCharging ? "charging" : "discharging");
                }
            }
        };
    }

**************************************未完,待续********************************

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值