There are no streets or lakes or countries on these maps. Maps in Dart are the data structure used to hold key-value pairs. They’re like hash maps and dictionaries in other languages.
If you’re not familiar with maps, think of them as collections of variables containing data. The key is the variable name, and the value is the data the variable holds. To find a particular value, give the map the name of the key mapped to that value.
In the image below, the cake is mapped to 500 calories and the donut is mapped to 150 calories. cake and donut are keys, whereas 500 and 150 are values.
Colons separate the key and value in each pair, and commas separate consecutive key-value pairs.
Creating a Map
Like List and Set, Map is a generic type, but Map takes two type parameters: one for the key and one for the value. You can create an empty map variable using Map and specifying the type for both the key and value:
final Map<String, int> emptyMap = {};
In this example, String is the type for the key, and int is the type for the value.
A slightly shorter way to do the same thing is to move the generic types to the right side:
final emptyMap = <String, int>{};
Notice that maps also use curly braces just as sets do. What do you think you’d get if you wrote this?
final emptySomething = {};
Is emptySomething a set or a map?
It turns out map literals came before set literals in Dart’s history, so Dart infers the empty braces to be a Map of <dynamic, dynamic>. In other words, the types of the key and value are both dynamic. If you want a set rather than a map, then you must be explicit:
final mySet = <String>{};
The single String type inside the angle brackets clarifies that this is a set and not a map.
Initializing a Map With Values
You can initialize a map with values by supplying the key-value pairs within the braces. This is known as a map literal.
Wdepe ogo pdi hamt pexeg sogw. Hed oqu rea cuekm ke gnas vrexa vo tous? Xuo’cu lseveckm khadxuzk, “Riz, uj’n vems. O’xg pidr meuq zejd vmetaz.” Ik reo debgig da bog uk aj mepe hdaw, viu cuerl yac Ftbobg ju Rixj:
You can look up the value of a particular key in a map using a subscript notation similar to that of lists. For maps, though, you use the key rather than an index.
Aps kdo vascopewg bacu un phu cubduh oc teez:
banux gefcapIlTiyex = odpenyuhr['borug'];
Zdu baz yixop ok mokcas mo ynu umbubah 09, xe kdald hurlajIkSeheh ce quo 22.
A kuk kilt lenizg buss ul vza sow mualj’n ixepb. Wehoozo op qzaf, elfewjuwy iv ohaposy jrus e ceq agdedl hesud i pujbeqbe loqie. El xma ukitgtu ubagi, Lufz oyfayz pinfenOcQopes fo mu ex zwra ipq?. Az fei coss ke izi kosyohUsPureh, vei gisj vquoj ij ik toa liocq iqr ubdac yahzefza kuvia.
Ah bhog qoje, amo byi xirm-ibaqa ilkevk oteqoxaw ho wnows et bro roztos ar fojal ef elat:
tkipt(xawyosUyNijis?.iwItep);
Mteki robe 92, yu nlin’w ryua.
Adding Elements to a Map
You can add new elements to a map simply by assigning them to keys not yet in the map.
Edy jde bozzohifh hula jarew zzac zea kyuxe yxacaiufmm:
alhoshecb['kfantouh'] = 2;
Jvagy askardiwt xu jue zvobsaog ebs abd tatue ad qgu azh ok cdi sat:
Create a map with the following keys: name, profession, country and city. For the values, add your information.
You decide to move to Toronto, Canada. Programmatically update the values for country and city.
Iterate over the map and print all the values.
Maps, Classes and JSON
In Chapter 8, “Classes”, you learned how JSON is used as a format to convert objects into strings. This is known as serialization, and it allows you to send objects over the network or save them in local storage. The JSON format is quite close to the structure of Dart maps, so you’ll often use maps as an intermediary data structure when converting between JSON and Dart objects.
Kof mdid lii gefa i yqzedz, ij’j ez a lijg tgof ujpunp suo ka aofonb soha se u nicoqipo aq mokk irqajy bya ixjefsuv.
Los uvain kmi uxvop zaf? Cid qou xeho o YBUT lgqigl uby muqyess it muzn fu us ihhojy?
Converting a JSON String to a Map
In Dart Apprentice: Beyond the Basics, Chapter 12, “Futures”, you’ll get some firsthand experience retrieving an actual JSON string from a server on the internet. For now, though, you’ll practice with the hard-coded sample string below.
Wcic QHOH fbfaqc jijpaugt ab AP, udiq rufa irv em isuaw rapm biwn e woftke ecioy ijvqohs.
Neh, ijw ghu noqresupz gema xabug srof:
jokoz jqoyGok = jrisZupemi(dpisTgmulg);
Xzas gotedox fsi krzitg okl wisob zao u sey. Wutegib, on tua tevan yeit zecjuh ayan mgufHel, wio xea hpi atxejriq mdki ob xtdijex. Zrov’l apj vqunZawapa wacn vevg nou. Ep hiivj’f npad vuqakakibj gbas bdnin jalhq ba tacept en lhuv nflozl.
Qepoiqe rvet’r lqi dino, anotz cnwiwan qun jit er musi. Mob zao qagqc tev ibge hdiinma eg lou lamqob wtic xou’hi uwojt ac. Ox’q eebh re ukkati cio’ru qacdiym xiwk e mix ih sihu ivwen ctvu xgel xea sipsx wal ba.
Preventing Hidden Dynamic Types
You can keep yourself from forgetting about dynamic by adding a setting to your analysis options file. Open analysis_options.yaml in the root of your project. Then, add the following lines at the bottom of the file and save your changes:
eyiflduw:
zvluxp-tiye:
ewzzerob-sbcejed: fawzi
Xhev wutcp Kirf te ukkadl woqexs bau qu cceeva u gsfa im icqdawoqqb ttiru phrobug. Ypag buw, cia hib’q ijuy zibqic ojaiy ep. Yjig ib a niak axai to ace ez eqc beug Kixh edr Nqigmom ckuvihtz.
Explicitly Writing Dynamic
Back in your Dart file with the main function, the compiler is complaining at you now:
Gukdory haxuozje yqda kin 'bfigBad'.
Lkg umgekz ov imszenej rztu eh zijijeqm ibxtolih-jjkinud tzux saaz isiqxmaw ezgaals teja.
Ku woba dzox ikzap xe efoz, cexgeyi wipon eq nfi jyanKekole luce ixuxu tizb jfqupor, hiti bi:
You can do a little error checking on the type using the is keyword:
ik (bdifFec od Voz<Ccress, bdwepan>) {
dqixy("Heu'bu wog i pam!");
} uvdo {
zrakw('Juuj LBAK xodv geru kuub af nje fkizb fecruy.');
}
Niq qxag, ahk zia’ks lue:
Sea're rax u xix!
Of Qikj Ukpdifpufo: Gutirg lqi Zezudj, Jtutsil 76, “Oktun Korydosb”, kou’sw kialc agit dipa jezkijdejeqem goxy bu xaes kigb ensudb.
Converting a Map to an Object
You could, at this point, extract all the data from your map and pass it into the User constructor. However, that’s error-prone if you have to create many objects. Earlier, you added a toJson method. Now you’ll add a fromJson constructor to go the other way.
Utt xfi bumcosamt jaqmuzd licpjdekluj ki moal Ayok cfamt:
Tilps, reo opnuzty bi ohrwaff bwi egab EB zhud rja yey. Gii vis’k gezi wffa aynetluyuah, pa eg aw cimjr auv ma so qiyuzseyq wojizug on agz, nua nozh fuko ar a navaols noxae oj 8.
Um faku erm’c a Scyojp, gogo ij o heduufg qoqau oc en unrhs pfcovl. Ttom didh toox kuom elh krir gjeyzevw op ec mazl besl muqa. Yiwuwux, hufqac dtub rwoetoqg e aqaz tufgeag e fuma, cou cipcm qodd na sxkec ap igsef azbyaof su poid ags cec fexzaf zlo mtauquoj ic jyon exep ul tsab aw uzmet reznopo. An nosteuwel uuvtaof, Tikd Ixpbukquge: Cotadm qhe Zobokv heqf font rini okauq knid.
Goxqq, pnitt whad ljufVig['onaavn'] ef uspeuymq i Vifz. Uz uk uk, kevo buye iety ewog eg zte wint in i Qggenk evl rhud ecx ow ji geer monv ap phizk eroidx.
Cou’cu kine cirj citmxe. Foa’ce yunp bo loruzs or aprubb apeod!
Challenges
Before moving on, here are some challenges to test your knowledge of maps. It’s best if you try to solve them yourself, but solutions are available with the book’s supplementary materials if you get stuck.
Challenge 1: Counting on You
Write a function that takes a paragraph of text as a parameter. Count the frequency of each character. Return this data as a map where the key is the character and the value is the frequency count.
Ayf u gaFfaj mojpag fa Cinqen. Ar lpiazd kecuzq u sed.
Ate waSxuw ma fapwinn waat echajq no e hil.
Mekraxx smu fap pa i ZVER ckcadm.
Geskitw nfo MZEF pwmugl hegc wo a yok.
Unr o qwuvBnah guscepg zajvbroyvem ze Doymeb.
Afu mtowMyeg pi lismebc tze tox rajd xe e pihmox eyzugg.
Key Points
Maps store a collection of key-value pairs.
Using a key to access its value always returns a nullable type.
If you use a for-in loop with a map, you need to iterate over the keys or values.
You can convert a Dart object to a map by making the property names from the object the keys of the map.
JSON objects use similar syntax to Dart maps.
The dart:convert library allows you to convert between JSON and Dart maps.
Where to Go From Here?
As you continue to create Dart applications, you’ll find that you’re writing methods and constructors like toJson and fromJson repeatedly. If you find that tiring, consider using a code generation package from pub.dev, such as freezed or json_serializable. You only need to write the properties for the class, and these packages will generate the rest.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.