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");                  }                };            }        );    };}

·