5

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
  • Is the map a json Object? Commented Sep 21, 2018 at 10:01
  • I could use jsonEncode to make it one, correct? Commented Sep 21, 2018 at 10:03

2 Answers 2

8

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.

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

1 Comment

That is what I was looking for, Thanks
4

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

2 Comments

Running the gato code provided by you is giving me the following error ``` New York Unhandled exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, Map<String, Object>>' #0 main (package:flood_mobile/Playground/test_create_file_folder_structure.dart:30:5) #1 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19) #2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12) ```
This problem has been solved, please use the latest version of Gato package.

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.