Flutter平台交互 #

一、MethodChannel #

1.1 Flutter端 #

dart
import 'package:flutter/services.dart';

class NativeService {
  static const platform = MethodChannel('com.example.app/native');
  
  Future<String> getPlatformVersion() async {
    try {
      final version = await platform.invokeMethod('getPlatformVersion');
      return version;
    } on PlatformException catch (e) {
      return 'Error: ${e.message}';
    }
  }
}

1.2 Android端 #

kotlin
class MainActivity : FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, 
            "com.example.app/native").setMethodCallHandler { call, result ->
            when (call.method) {
                "getPlatformVersion" -> {
                    result.success("Android ${Build.VERSION.RELEASE}")
                }
                else -> result.notImplemented()
            }
        }
    }
}

1.3 iOS端 #

swift
override func application(_ application: UIApplication, 
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    let controller = window?.rootViewController as! FlutterViewController
    let channel = FlutterMethodChannel(
        name: "com.example.app/native",
        binaryMessenger: controller.binaryMessenger
    )
    
    channel.setMethodCallHandler { call, result in
        if call.method == "getPlatformVersion" {
            result("iOS " + UIDevice.current.systemVersion)
        } else {
            result(FlutterMethodNotImplemented)
        }
    }
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}

二、总结 #

2.1 核心概念 #

概念 说明
MethodChannel 方法通道
invokeMethod 调用原生方法
setMethodCallHandler 处理Flutter调用

2.2 下一步 #

让我们学习 国际化

最后更新:2026-03-28