flutter代码
// main.dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final BasicMessageChannel<String> messageChannel = BasicMessageChannel<String>('messageChannel', StringCodec()); String _message = 'No message from iOS'; @override void initState() { super.initState(); messageChannel.setMessageHandler((message) async { print("Received message from iOS: $message"); setState(() { _message = 'iOS Response: $message'; }); return 'ACK from Dart'; }); } Future<void> _sendMessageToiOS() async { try { final String? result = await messageChannel.send('Hello from Flutter!'); print("Received response from iOS: $result"); } on PlatformException catch (e) { print("Failed to send message to iOS: ${e.message}"); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter - iOS Communication Demo'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( '$_message', style: TextStyle(fontSize: 16), ), SizedBox(height: 20), ElevatedButton( onPressed: _sendMessageToiOS, child: Text('Send Message to iOS'), ), ], ), ), ); } }
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 = window?.rootViewController as! FlutterViewController let messageChannel = FlutterBasicMessageChannel( name: "messageChannel", binaryMessenger: controller.binaryMessenger, codec: FlutterStringCodec.sharedInstance() ) messageChannel.setMessageHandler { [weak self] (message, reply) in guard let strongSelf = self else { return } print("Received message from Flutter: \(message ?? "")") let response = "Hello from iOS! You said: \(message ?? "")" reply(response) } GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
标签:return,iOS,override,message,messageChannel,flutter,BasicMessageChannel From: https://www.cnblogs.com/ZhangShengjie/p/17897614.html