Home > Back-end >  How to generate dynamic json in dart
How to generate dynamic json in dart

Time:06-30

Currently, I have the following JSON:

var user = {
                          "id": Provider.of<UserProvider>(context, listen: false).id,
                          "name": Provider.of<UserProvider>(context, listen: false).name,
                          "desc": Provider.of<UserProvider>(context, listen: false).desc,
                          "title": Provider.of<UserProvider>(context, listen: false).title
                        };

var finalJson = json.encode(user);

Now I want to exclude desc key and value if Provider.of(context, listen: false).desc == null.

I do not want to include key and value if anyone the value is null.

How can I achieve that?

CodePudding user response:

Just call

user.removeWhere((key, value) => value == null);

before you encode it

CodePudding user response:

Here's a simpler way to do it:

Map<String, dynamic> user = {};
if (Provider.of<UserProvider>(context, listen: false).id != null) {user["id"] = Provider.of<UserProvider>(context, listen: false).id;}
if (Provider.of<UserProvider>(context, listen: false).name != null) {user["name"] = Provider.of<UserProvider>(context, listen: false).name;}
if (Provider.of<UserProvider>(context, listen: false).desc != null) {user["desc"] = Provider.of<UserProvider>(context, listen: false).desc;}
if (Provider.of<UserProvider>(context, listen: false).title != null) {user["title"] = Provider.of<UserProvider>(context, listen: false).title;}

var finalJson = json.encode(user);
  • Related