0

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?

2 Answers 2

2

Just call

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

before you encode it

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.