Flutter和iOS之间双向通讯

213 阅读1分钟

在Flutter中,你可以使用Platform Channels来实现与iOS之间的双向通信。以下是一个简单的示例,展示了如何在Flutter中使用MethodChannel进行双向通信。

Flutter 代码:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  static const platform = const MethodChannel('com.example.flutter_ios_channel');

  Future<void> _sendMessageToNative(String message) async {
    try {
      await platform.invokeMethod('sendMessageToNative', {'message': message});
    } on PlatformException catch (e) {
      print("Failed to send message to native: ${e.message}");
    }
  }

  Future<String?> _getMessageFromNative() async {
    try {
      return await platform.invokeMethod('getMessageFromNative');
    } on PlatformException catch (e) {
      print("Failed to get message from native: ${e.message}");
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter iOS Channel Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () async {
                  await _sendMessageToNative('Hello from Flutter!');
                },
                child: Text('Send Message to Native'),
              ),
              SizedBox(height: 20),
              FutureBuilder<String?>(
                future: _getMessageFromNative(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    } else {
                      return Text('Message from Native: ${snapshot.data ?? "No message"}');
                    }
                  } else {
                    return CircularProgressIndicator();
                  }
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

iOS 代码:

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 channel = FlutterMethodChannel(name: "com.example.flutter_ios_channel", binaryMessenger: controller.binaryMessenger)
    
    channel.setMethodCallHandler({
      (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
      if call.method == "sendMessageToNative" {
        if let arguments = call.arguments as? Dictionary<String, Any>,
           let message = arguments["message"] as? String {
          self.receiveMessageFromFlutter(message: message)
          result(nil)
        } else {
          result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid arguments", details: nil))
        }
      } else if call.method == "getMessageFromNative" {
        let message = self.getMessageFromNative()
        result(message)
      } else {
        result(FlutterMethodNotImplemented)
      }
    })

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  func receiveMessageFromFlutter(message: String) {
    print("Received message from Flutter: \(message)")
    // Handle the received message from Flutter in your native iOS code
  }

  func getMessageFromNative() -> String {
    // Get the message from native iOS code to send back to Flutter
    return "Hello from Native!"
  }
}

在这个示例中,我们创建了一个名为com.example.flutter_ios_channelMethodChannel,并使用invokeMethod方法发送消息给iOS原生,使用setMethodCallHandler方法接收来自iOS原生的消息。同时,通过MethodChannel的不同实例,我们在Flutter和iOS原生代码中实现了相应的方法,以实现双向通信。

请确保在你的pubspec.yaml文件中添加了flutter/services依赖。这只是一个简单的示例,实际中的通信可能涉及更多的交互和数据传输。