乐趣区

关于SegmentFault:flutter与native交互

flutter 与 native 交互

一、dart

  1. 引入包 import ‘package:flutter/services.dart’;
  2. 定义通道名并通过 MethodChannel 连贯
  3. 调用 native 办法 platform.invokeMethod(“call_native_method”)

`

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'dart:async';
// 与原生交互
import 'package:flutter/services.dart';
class MinePage extends StatefulWidget {
  @override
 _MinePageState createState() => _MinePageState();
}
class _MinePageState extends State<MinePage> {
  static const CHANNEL_NAME = "samples.flutter.study/call_native";
  static const platform = MethodChannel(CHANNEL_NAME);
  String _res = "111";
  @override
 Widget build(BuildContext context) {
    return Column(
      children: [
        RaisedButton(onPressed: () async{String res = await platform.invokeMethod("call_native_method");
              setState(() {_res = res;});
            },
            child:Text("调用 native")
        ),
        Text(_res),
      ],
    );
  }
}

`

二、native(安卓)

  1. 援用相干 flutter 包
  2. 继承 FlutterActivity 类,通过 MethodChannel 连贯雷同的通道名称
  3. 写交互的办法

·

package com.example.flutter_app;
import android.content.Context;
import android.os.BatteryManager;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
    String CHANNEL_NAME = "samples.flutter.study/call_native";
    @Override
 protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        new MethodChannel(getFlutterView(),CHANNEL_NAME).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
                @Override
 public void onMethodCall(MethodCall methodCall,MethodChannel.Result result){if(methodCall.method.equals("call_native_method")){result.success("native 返回值 aaa");
                  } else {result.success("I don not know what you said");
                  }
                };
            }
        );
    };
}

·

退出移动版