0

User can save his name and photo. Users can skip to upload a profile photo. So, I already store users' data inside my DB. So, I didn't want to set null into photo.url. How do I create a map for this?

Future<void> updateUser({String name, String uid, String url}) { Map<String, dynamic> _map = <String, dynamic>{ 'info': { 'name': name }, }; if (url != null) { // if user upload profile photo I want to add url to inside `info.photo` // got an error when try like this // _map['info']['photo'] = {'url': url}; // this way is replace info, it's mean 'name' key is removed // _map['info'] = { // 'photo': {'url': url} // }; } return _db.collection('users').doc(uid).set(_map, SetOptions(merge: true)); 

The final map should be like this,

{ 'info':{ 'name':name, 'photo':{ // if url is not null 'url':url } } 

}

2 Answers 2

2

You can try this:

 Map<String, dynamic> child = <String, dynamic>{'name': 'name'}; Map<String, dynamic> _map = <String, dynamic>{"info": child}; Map<String, dynamic> info = _map["info"]; info.update( 'photo', (value) => null, ifAbsent: () => {'url': 'new url'}, ); _map.update('info', (value) => info); print(_map); 

I used a child map to enforce the type casting.

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

6 Comments

wrong bro. please check my question. I want to add url inside an another map(photo)
Yea, I saw what you did, but you get the idea. Well done.
Sorry, it' wrong. I want to add photo map inside the info the map
your result is like this {name: name, photo: {url: new url}}. I want {'info': {'name':name, 'photo':{'url':url}}
yes. it's working. but I actual map is very complcated. there are so many conditions. Is there any amother way to do it?
|
0

You can do it easily using if

 Map<String, dynamic> _map = <String, dynamic>{ 'info': { 'name': name, if (url != null) 'photo' : {'url': url} }, }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.