get String from nested Map in dart

Viewed 3756

My Map:

{Info: {name: Austin, Username: austinr}}

I'm using this line to get the myName variable to be set as "Austin"

String myName = map["name"] as String;

However.. this line seems to set the string "myName" to null. just looking for a way to extract my name and Username from the map

Thanks

2 Answers

I am able to run the following code successfully.

 var map =  {"Info":{"name": "Austin", "Username": "austinr"}}; 
 String myString = map["Info"]["name"] as String;
 print(myString);

The output is Austin as expected. Please try this.

Also if you want to work with maps in Dart, especially with nested keys, you can use gato package too.

Basic way:

var map = {
  'Info': {
    'name': 'Austin',
    'Username': 'austinr',
    'address': {'city': 'New York'}
  }
};

String city = map['Info']['address']['city'] as String;
print(city);

But it's a little dirty and also you will get an error if there wasn't the address key in your map.

Using Gato

import 'package:gato/gato.dart' as gato;
.
.
.

var map = {
  'info': {
    'name': 'Austin',
    'username': 'austinr',
    'address': {'city': 'New York'}
  }
};

// Get value from a map
print(gato.get<String>(map, 'info.address.city')); // New York

// Set a value to a map
map = gato.set<String>(map, 'info.address.city', 'Other City');

print(gato.get<String>(map, 'info.address.city')); // Other City

Full document

Related