Flutter与原生代码交互教程

Flutter与原生代码交互教程

3 回复

更多关于Flutter与原生代码交互教程的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


推荐官方文档:使用平台通道与原生代码交互。简单易懂,适合初学者。

Flutter与原生代码交互主要通过平台通道(Platform Channel)实现。Flutter提供了MethodChannelEventChannel两种方式来实现与原生代码的通信。

1. 使用MethodChannel进行双向通信

MethodChannel允许Flutter调用原生代码,并接收原生代码的返回值。

Flutter端代码

import 'package:flutter/services.dart';

class NativeBridge {
  static const platform = MethodChannel('com.example.app/native');

  Future<String> getNativeData() async {
    try {
      final String result = await platform.invokeMethod('getNativeData');
      return result;
    } on PlatformException catch (e) {
      return "Failed to get native data: '${e.message}'.";
    }
  }
}

Android端代码

MainActivity.kt中:

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.example.app/native"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "getNativeData") {
                result.success("Hello from Android")
            } else {
                result.notImplemented()
            }
        }
    }
}

iOS端代码

AppDelegate.swift中:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
        let nativeChannel = FlutterMethodChannel(name: "com.example.app/native",
                                                 binaryMessenger: controller.binaryMessenger)
        nativeChannel.setMethodCallHandler({
            (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
            if call.method == "getNativeData" {
                result("Hello from iOS")
            } else {
                result(FlutterMethodNotImplemented)
            }
        })
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

2. 使用EventChannel进行流式通信

EventChannel用于从原生代码向Flutter发送连续的事件流。

Flutter端代码

import 'package:flutter/services.dart';

class NativeEventStream {
  static const eventChannel = EventChannel('com.example.app/events');

  Stream<String> get nativeEventStream {
    return eventChannel.receiveBroadcastStream().map((event) => event.toString());
  }
}

Android端代码

MainActivity.kt中:

import io.flutter.plugin.common.EventChannel

class MainActivity: FlutterActivity() {
    private val EVENT_CHANNEL = "com.example.app/events"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL).setStreamHandler(
            object : EventChannel.StreamHandler {
                override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
                    events.success("Event from Android")
                }

                override fun onCancel(arguments: Any?) {
                    // Clean up resources if needed
                }
            }
        )
    }
}

iOS端代码

AppDelegate.swift中:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
        let eventChannel = FlutterEventChannel(name: "com.example.app/events",
                                               binaryMessenger: controller.binaryMessenger)
        eventChannel.setStreamHandler(EventStreamHandler())
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

class EventStreamHandler: NSObject, FlutterStreamHandler {
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        events("Event from iOS")
        return nil
    }

    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        return nil
    }
}

总结

通过MethodChannelEventChannel,Flutter可以方便地与原生代码进行交互。MethodChannel适用于一次性调用,而EventChannel适用于流式数据传输。根据需求选择合适的通道类型即可。

回到顶部