【发布时间】:2021-02-24 18:36:42
【问题描述】:
我已经查看了很多关于这个主题的类似问题,但没有一个解决方案对我有用。我正在 Flutter 中开发一个应用程序,但想从 AppDelegate.swift 调用我的 main.dart 文件中的特定方法在原生 iOS 项目中。
为了删除所有其他变量,我已将问题提取到一个新的 dart 项目中。我正在尝试使用methodChannel.invokeMethod() 从AppDelegate.swift 调用setChannelText(),但没有成功。
有人知道我哪里出错了吗?我知道我没有对methodChannel.invokeMethod() 中的“名称”参数采取行动,但那是因为我只希望调用调用该方法...
这是我的 main.dart 文件:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
MethodChannel channel =
new MethodChannel("com.example.channeltest/changetext");
String centerText;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.purple,
body: Center(
child: Text(
centerText,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 30.0,
),
),
),
),
);
}
@override
void initState() {
super.initState();
this.channel.setMethodCallHandler((call) async => await setChannelText());
this.centerText = "Hello World!";
}
Future setChannelText() async {
Future.delayed(Duration(milliseconds: 200));
setState(() => this.centerText = "Another Text.");
}
}
这是我的 AppDelegate.swift 文件:
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
var methodChannel: FlutterMethodChannel!
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let rootViewController : FlutterViewController = window?.rootViewController as! FlutterViewController
methodChannel = FlutterMethodChannel(name: "com.example.channeltest/changetext", binaryMessenger: rootViewController as! FlutterBinaryMessenger)
//This call would obviously be somewhere else in a real world example, but I'm just
//testing if I can invoke the method in my dart code at all..
methodChannel.invokeMethod("some_method_name", arguments: nil)
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
最后,我试图在启动后立即更改文本,但事实并非如此。
Screenshot of app running on iOS simulator
提前感谢您的帮助!
【问题讨论】:
-
您可能缺少 swift 端的结果处理程序:
methodChannel.invokeMethod("some_method_name", arguments: nil, result: {(r:Any?) -> () in })