原生于 Flutter 数据交换:Flutter 似乎没有从 MethodChannel 接收数据

Native to Flutter data exchange: Flutter seems not receiving data from MethodChannel

提问人:SpaceXS 提问时间:11/7/2023 更新时间:11/7/2023 访问量:35

问:

我正在构建一个播放视频的应用程序,我可以从 Flutter 打开数据(链接视频)并将其传递给 Native,但我需要在 VideoActivity 末尾传递播放器的位置

其实我有这个代码

主要活动

class MainActivity: FlutterActivity() {
    private val CHANNEL = "ankit.flutter.dev/video"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GeneratedPluginRegister.registerGeneratedPlugins(FlutterEngine(this))
        flutterEngine?.dartExecutor?.let {
            MethodChannel(it, CHANNEL).setMethodCallHandler { call, result ->
                if (call.method == "playVideo") {
                    goToVideoActivity()
                    result.success(null)
                } else if (call.method == "updateVideoPosition") {
                    val position = call.arguments as Int
                    result.success(position)
                }
            }
        }

    }

视频活动

private lateinit var flutterEngine: FlutterEngine

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = VideoLayoutBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        // Inizializza il FlutterEngine all'avvio dell'app
        flutterEngine = FlutterEngine(this)
        flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())
        FlutterEngineCache.getInstance().put("1", flutterEngine)
}

    override fun onDestroy() {
        super.onDestroy()
        releasePlayer()
        val methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "ankit.flutter.dev/video")
        Log.d("posizione 1", "$currentPosition")
        methodChannel.invokeMethod("updateVideoPosition", currentPosition)
    }


$currentPosition使用正在工作的另一部分代码正确更新(末尾的日志显示正确的值)

在颤振方面,我有这个

  @override
  void initState() {
    super.initState();
    MethodChannel platform = MethodChannel("ankit.flutter.dev/video");
    platform.setMethodCallHandler((call) async {
      print("Metodo ricevuto: ${call.method} argomenti: ${call.arguments}");
      if (call.method == 'updateVideoPosition') {
        final position = call.arguments as int;
        print('Current video position: $position milliseconds');
      }
    });
  }

Flutter 似乎没有从原生活动中获得任何价值,我无法弄清楚原因(我不擅长 kotlin,我正在使用许多教程/GPT 来弄清楚我需要什么

谢谢大家的帮助

原生 flutter-method-channel

评论

0赞 pskink 11/7/2023
尝试调用,只是为了测试,不是从而是从其他地方进行测试,当您的本机代码处于活动状态并且不在销毁过程中时?methodChannel.invokeMethodonDestroy
0赞 SpaceXS 11/7/2023
是的,以前我曾尝试在相同的代码中调用该方法,该方法每秒更新位置,但没有运气(我更改了位置只是因为我需要最后一个已知位置,并且每次更新都是浪费资源我担心的是:如果 test.dart 页面不在视图中,flutter 是否有可能无法接收数据?

答: 暂无答案