swift – Method Channel Flutter (ios)


AppDelegate

class AppDelegate: FlutterAppDelegate,MessagingDelegate {

    lazy var flutterEngine = FlutterEngine(name: "my flutter engine")


    
    override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
 let controller = FlutterViewController(project: nil, nibName: nil, bundle: nil)
        print("flutter test print : 1122")
        let nativeChannel = FlutterMethodChannel(name: "test.flutter",
                                                      binaryMessenger: controller.binaryMessenger)
nativeChannel.setMethodCallHandler({
//            [weak self]
            (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
if call.method == "getMessage" {

                  result("Data from iOS")
                  
              } 
            else {
                  print("flutter test print : else")
                result(FlutterMethodNotImplemented)
              }
        })
flutterEngine.run();
GeneratedPluginRegistrant.register(with: self.flutterEngine); // self.flutterEngine
        return super.application(application, didFinishLaunchingWithOptions: launchOptions);
    
}```

File.dart

class TestMethodchannel extends StatefulWidget {

@override
_TestMethodchannel createState() => _TestMethodchannel();
}

class _TestMethodchannel extends State {

static const platform = MethodChannel(‘test.flutter’);
String _dataFromNative=”No Data”;

Future getNativeData() async {

String? data;
try {
  final String? result = await platform.invokeMethod<String>('getMessage');
  // final String? result = await platform.invokeMethod('getMessage',{"param1":1});
  data = result;
} on PlatformException catch (e) {
  data = "Failed to get data: '${e.message}'.";
}

print('flutter data : '+data.toString());


setState(() {
  _dataFromNative = data.toString();
});

}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Native Data Fetcher’),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: getNativeData,
child: Text(‘Fetch Data from Native’),
),
SizedBox(height: 20),
Text(‘Data from Native: $_dataFromNative’),
],
),
),
);
}
}“`

Unable to send values ​​between iOS(Swift) and flutter.

If you use

let controller : FlutterViewController = window?.rootViewController as! FlutterViewController

an error will occur.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img