我正在尝试将类型为 User
的自定义对象从 native 平台传递到 Flutter。 User
类是库的一部分,不能直接访问以进行编辑。这是我的 android 和 iOS 代码实现。问题是我无法找到一个解决方案来解决如何通过方法 channel 传递这个对象,以便我可以轻松地在 Dart 代码中解析它。
安卓部分:
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;
}
最佳答案
您可以在 HashMap 中传递数据。
在 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;
...
关于android - 通过方法 channel flutter 传递自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55900977/