Flutter方法频道传递JSON

时间:2019-04-12 21:09:38

标签: flutter

我正在为当前项目试用flutter模块。推动颤抖的视图非常不错,并且就像一个饰物。现在,我试图传递一些JSON数据,但是我无法接收数据并将其解析为Map<String, dynamic>。我的实现如下所示。有想法吗?

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)

飞镖

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';
    });

我在做什么错?

1 个答案:

答案 0 :(得分:0)

如果您希望通过flutter通道将JSON结构作为参数传递给Android / IoS,则可以这样做:

  • 接收参数使用:call.arguments as? Dictionary<String, Any>
  • 从第一步开始使用防护let paramName = args?["paramName"] as? String
  • 通过JSONDecoder package解码json字符串

否则,如果要将JSON字符串返回到颤动点,则可以使用JSONEncoder package对IoS结构进行编码。

但是,我不知道如何接收Android平台的JSON结构,当我收到它时,我会完成答案,祝您好运!

更新:

如果您将dart类用作参数,请确保您的类具有toson功能,例如:

Map<String, dynamic> toJson() =>
    {
      'name': name,
      'email': email,
    };

还有

jsonEncode(your_class.toMap()).

对于Android平台解析:

val args = call.arguments as Map<String,Any>
val argName = args["argName"] as String
Klaxon().parse<TargetDataClass>(argName)