调用函数并将参数从 Kotlin 传递到 Flutter

Calling a function and passing arguments from Kotlin to Flutter

我正在处理 PlatformChannels 试图从 KotlinFlutter 的通信。实际尝试按照 flutter 平台频道的文档中的说明进行操作,但方向相反:

flutter platfor channels docs

想法是从 MainActivity.kt class 上的 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:',
            ),
          ],
        ),
      ),
    );
  }
}

Kotlin 方面,我只是尝试在 MainActivity.kt:[=16 上调用 flutter 回调方法=]

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)

        val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "myTestChannel")

        channel.invokeMethod("myTestChannel","the argument from Android")
}

但是当我 运行 代码时,Flutter 端没有打印任何内容。也没有崩溃或异常。

这最终对我有用。如果你想在 android 生命周期回调中调用你的方法,试试这样的方法

const val CHANNEL = "yourTestChannel"

class MainActivity : FlutterActivity() {

  override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine);
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    var flutterEngine = FlutterEngine(this)

    flutterEngine
      .dartExecutor
      .executeDartEntrypoint(
        DartExecutor.DartEntrypoint.createDefault()
      )

    var channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)

    channel.invokeMethod("yourMethod", "yourArguments")
    }
  }
}

您应该按照以下方式实施

飞镖代码

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

home_page.dart

class _HomePageState extends State<HomePage> {

  @override
  void initState() {
    super.initState();
    AmazonFileUpload.streamData.listen((event) {
      print("========$callbackFromKotlinToDart--------");
    });
    AmazonFileUpload().uploadFile();



  @override
  Widget build(BuildContext context) {

}

Android代码

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



            }
        }

    }