我正在尝试将类型为User
的自定义对象从本机平台传递到Flutter。 User
类是库的一部分,不能直接访问进行编辑。这是我的android和iOS代码实现。问题是我找不到如何通过方法通道传递该对象的解决方案,以致于我无法轻松地在Dart代码中对其进行解析。
Android部分:
private fun loginUser(uid: String, apiKey: String, result: MethodChannel.Result) {
MyChat.login(uid, apiKey, object : MyChat.CallbackListener<User>() {
override fun onSuccess(user: User) {
Log.e(TAG, user.toString())
result.success(hashMapOf("RESULT" to true, "AVATAR" to user.avatar,
"CREDITS" to user.credits,
"EMAIL" to user.email,
"LAST_ACTIVE" to user.lastActiveAt,
"NAME" to user.name,
"ROLE" to user.role,
"STATUS" to user.status,
"STATUS_MESSAGE" to user.statusMessage).toString())
}
override fun onError(p0: MyChatException?) {
Log.e(TAG, p0?.message)
result.error("FAILED", "Unable to create login", null)
}
})
}
iOS实现:
func loginUser(result: @escaping FlutterResult, uid: String, apiKey: String){
MyChat.login(UID: uid, apiKey: apiKey, onSuccess: { (user) in
// Login Successful
let data: [String: Any] = ["RESULT":true,
"AVATAR":user.avatar!,
"CREDITS": user.credits,
"EMAIL": user.email!,
"LAST_ACTIVE":String(user.lastActiveAt),
"NAME":user.name!,
"ROLE":user.role!,
"STATUS":user.status.rawValue,
"STATUS_MESSAGE":user.statusMessage]
let jsonData = try? JSONSerialization.data(withJSONObject: data, options: [.prettyPrinted])
result(String(data: jsonData!, encoding: .ascii))
}) { (error) in
// Login error
result(FlutterError(code: "FAILED", message:"Login failed with exception: " + error.errorDescription, details: nil))
}
}
我的飞镖代码:
Future<String> isUserLoggedIn() async {
String status = "";
try {
final String result = await platform
.invokeMethod('loginUser', {"UID": UID, "API_KEY": API_KEY});
print(result); //How to parse?
status = "Hello";
} on PlatformException catch (e) {
print("Exception");
status = e.message;
}
return status;
}
答案 0 :(得分:0)
您可以在哈希图中传递数据。
在Android中:
result.success(hashMapOf(
"CREDITS" to user.credits,
"EMAIL" to user.email,
...
))
在iOS中:
let data: [String: Any] = [...]
result(data)
在Flutter中:
final result = await platform.invokeMethod<Map<String, dynamic>>('loginUser', ...);
final credits = result['CREDITS'] as String;
final email = result['EMAIL'] as String;
...
答案 1 :(得分:0)
您可以使用invokeMapMethod,它是invokeMethod的实现,可以返回类型化的映射。 像这样:
final result = await platform.invokeMapMethod('loginUser', ...);
,或者您可以将json对象作为这样的字符串传递:
在Android中
platform.success(
"{\"CREDITS\":\"${user.credits}\",\"EMAIL\":\"${user.email}\",\"LAST_ACTIVE\":\"${user.lastActiveAt}\"}"
)
扑朔迷离
var result = await methodChannel.invokeMethod('loginUser' , '');
var json = json.decode(result);
var credit = json['CREDITS'];
var email = json['EMAIL'];
var lastActive = json['LAST_ACTIVE'];