直接上代码:
dart:
class StreamView extends StatefulWidget {
@override
_StreamViewState createState() => _StreamViewState();
}
class _StreamViewState extends State<StreamView> {
var getData;
void sendChannel()async{
final chanel = MethodChannel('example.send');
var data = await chanel.invokeMethod('get',['who are you',123]);
getData = data.toString();
setState(() {});
}
@override
Widget build(BuildContext context) {
print('build');
return Scaffold(
body: Center(child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(getData??''),
FlatButton(onPressed: ()=>sendChannel(), child: Text('send'))
],
),),
);
}
}
android >>>>MainActivity.java
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
//getFlutterView()已经被删除 ,使用flutterEngine.getDartExecutor().getBinaryMessenger()替换
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(),
"example.send").setMethodCallHandler(new MyChannel());
}
}
class MyChannel implements MethodChannel.MethodCallHandler{
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if(call.method.equals("get")){
result.success("Native Answer");
}
if(call.arguments!=null){
if(call.arguments instanceof ArrayList){
ArrayList list= (ArrayList) call.arguments;
String a= (String) list.get(0);
int b= (int) list.get(1);
System.out.println(a); // who are you
System.out.println(b); // 123
}
}
}
}
ios>>> Runner > appdelegate.swift
没学过swift,仅供参考
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
//start
let controller = window?.rootViewController as! FlutterViewController;
let channel = FlutterMethodChannel(name: "example.send", binaryMessenger: controller.binaryMessenger);
channel.setMethodCallHandler { (call, result) in
if(call.method=="get"){
result("Native Answer");
}
}
//end
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
参考文档:Flutter官方 https://flutter.dev/docs/development/platform-integration/platform-channels
]