3

我正在处理PlatformChannels尝试从Kotlin到进行通信Flutter。尝试实际执行来自flutter平台频道的文档中解释的内容,但方向相反:

颤振平台频道文档

想法是从 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:',
            ),
          ],
        ),
      ),
    );
  }
}

Kotlin 方面,我只是尝试在MainActivity.kt上调用颤振回调方法:

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

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

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

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

4

2 回答 2

5

您应该按照以下方式实施

飞镖代码

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

}

安卓代码

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



            }
        }

    }
于 2020-05-20T05:08:25.693 回答
3

这最终对我有用。如果你想在 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")
    }
  }
}
于 2020-05-19T23:55:04.360 回答