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 ?
CodePudding user response:
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');
});
CodePudding user response:
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.
