Reputation: 2431
I'm trying out flutter modules for my current project. Pushing a flutter view is quite nice and works like a charm. Now I'm trying to pass over some JSON data but I can't managed to receive the data and parse it into a Map<String, dynamic>
. My implementation looks like the following. Any idea?
iOS
guard let path = Bundle.main.path(forResource: "chat", ofType: "json") else {
return
}
let data = try! Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let flutterEngine = (UIApplication.shared.delegate as? AppDelegate)?.flutterEngine;
let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)!;
flutterViewController.send(onChannel: "chat.json", message: data)
flutterViewController.setMessageHandlerOnChannel("chat.result") {
(message: Data!, reply: FlutterBinaryReply) -> Void in
print("get json from result")
self.navigationController?.popViewController(animated: true);
}
self.navigationController?.pushViewController(flutterViewController, animated: true)
Dart
void initState() {
const channel = BasicMessageChannel('chat.json', JSONMessageCodec());
// Receive messages from platform and send replies.
channel.setMessageHandler((dynamic message) async {
print('Received: $message');
return 'Hi from Dart';
});
what am I doing wrong?
Upvotes: 2
Views: 3079
Reputation: 21
If you want to pass JSON struct as params to Android/IoS by flutter channel, you can do it like this:
call.arguments as? Dictionary<String, Any>
let paramName = args?["paramName"] as? String
JSONDecoder package
otherwise, if you want to return JSON string to flutter point, you can use JSONEncoder package
to encode IoS struct.
But, I don't know how to receive JSON struct for Android platform, when I get it, I will complete the answer, good luck!
Update:
If you use dart class as param,please make sure your class has toJson func,like this:
Map<String, dynamic> toJson() =>
{
'name': name,
'email': email,
};
And
jsonEncode(your_class.toMap()).
For Android platform parse:
val args = call.arguments as Map<String,Any>
val argName = args["argName"] as String
Klaxon().parse<TargetDataClass>(argName)
Upvotes: 1