简体   繁体   中英

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:

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

The Map having:

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

If commented above line, then jsonEncode works, else throwing above error.

How to instruct the jsonEncode to skip the closures when parsing Map to Json?

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:

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. The following will replace closures with 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.

option2: put your Closure inside the double quotation. so you can save it as String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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