简体   繁体   English

Dart/Flutter:在转换为 JSON 时,避免 Map 中的方法解析?

[英]Dart/Flutter : Avoid Method parsing in Map , when converting to JSON?

In Dart / Flutter, when converting a map (which contains a Closure method) to json using jsonEncode, I getting following error:在 Dart / Flutter 中,当将 map (其中包含闭包方法)转换为 Z466DEEC76ECDF1F,IDFCA6D387 时出现以下错误

Converting object to an encodable object failed: Closure: () => dynamic

The Map having: Map 具有:

orderedMap1["fooddelete"] = () => deleteItemFunction(
          singleitem["orderId"], singleitem["id"], singleitem["shopId"]);

If commented above line, then jsonEncode works, else throwing above error.如果在上面的行注释,则 jsonEncode 有效,否则抛出上述错误。

How to instruct the jsonEncode to skip the closures when parsing Map to Json?将Map解析为Json时如何指示jsonEncode跳过闭包?

It seems highly questionable to store closures in the same Map that you want to encode to JSON, but if you must, you can encode a filtered copy of it instead:将闭包存储在要编码为 JSON 的同一个Map中似乎非常值得怀疑,但如果必须,您可以对其进行过滤后的副本进行编码:

var encoded = jsonEncode({
  for (var entry in orderedMap1.entries)
    if (entry.value is! Function) entry.key: entry.value,
});

I suppose you alternatively could use jsonEncode 's toEncodable parameter to convert closures to something else, although I'm not sure what good that would do you since there's nothing the recipient could do with it.我想您也可以使用jsonEncodetoEncodable参数将闭包转换为其他东西,尽管我不确定这对您有什么好处,因为接收者对此无能为力。 The following will replace closures with null :以下将用null替换闭包:

var encoded = jsonEncode(orderedMap, toEncodable: (value) {
  if (value is Function) {
    return null;
  }
  throw UnsupportedError('Cannot convert to JSON: $value');
});

option1: remove "fooddelete" key using orderedMap1.remove("fooddelete") and then parse it.选项1:使用orderedMap1.remove("fooddelete")删除“fooddelete”键,然后解析它。

option2: put your Closure inside the double quotation.选项2:将您的闭包放在双引号内。 so you can save it as String.所以你可以将它保存为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM