cod*_*ler 4 android dart kotlin flutter flutter-platform-channel
我正在尝试从到PlatformChannels进行通信。实际上尝试按照 flutter 平台频道的文档中的说明进行操作,但方向相反:KotlinFlutter
这个想法是从 MainActivity.kt 类上的 configureFlutterEngine 函数调用 Flutter 函数。
为此,我在 Flutter 方面执行了 main.dart(Flutter 的默认示例):
class _MyHomePageState extends State<MyHomePage> {
static const platformChannel = const MethodChannel('myTestChannel');
@override
Widget build(BuildContext context) {
platformChannel.setMethodCallHandler((call){
print("Hello from ${call.method}");
return null;
});
//
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:',
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
从Kotlin 方面,我只是尝试在MainActivity.kt上调用 flutter 回调方法:
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "myTestChannel")
channel.invokeMethod("myTestChannel","the argument from Android")
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行代码时,Flutter 端没有打印任何内容。也没有崩溃或异常。
您应该按以下方式实施
飞镖代码
method_channel_helper.dart
class AmazonFileUpload {
static const platform = const MethodChannel('amazon');
static StreamController<String> _controller = StreamController.broadcast();
static Stream get streamData => _controller.stream;
Future<BaseResponse> uploadFile() async {
try {
platform.setMethodCallHandler((call) {
switch (call.method) {
case "callBack":
_controller.add("");
break;
}
});
final Map result = await platform.invokeMethod('s3_upload');
return BaseResponse(result["success"], result["error"], "");
} on PlatformException catch (e) {
return BaseResponse(false, e.message, "");
}
}
}
Run Code Online (Sandbox Code Playgroud)
主页.dart
class _HomePageState extends State<HomePage> {
@override
void initState() {
super.initState();
AmazonFileUpload.streamData.listen((event) {
print("========$callbackFromKotlinToDart--------");
});
AmazonFileUpload().uploadFile();
@override
Widget build(BuildContext context) {
}
Run Code Online (Sandbox Code Playgroud)
安卓代码
class MainActivity : FlutterActivity(), TransferListener {
private val CHANNEL = "amazon"
var methodResult: MethodChannel.Result? = null
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
channel.setMethodCallHandler { call, result ->
methodResult = result
if (call.method == "s3_upload") {
//Add you login here
channel.invokeMethod("callBack", "data1")
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8539 次 |
| 最近记录: |