Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get String from nested Map in dart

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

like image 296
Austin Reeve Avatar asked Dec 14 '22 14:12

Austin Reeve


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.

like image 184
vipin agrahari Avatar answered Dec 18 '22 10:12

vipin agrahari


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

like image 42
mehdi zarepour Avatar answered Dec 18 '22 11:12

mehdi zarepour