Need to go shopping? Make a shopping list so you don’t forget what to buy. Have a bunch of tasks to finish? Make a to-do list. Lists are a part of everyday life. They’re also an important part of programming.
In almost every application you make, you’ll deal with data collections. List is the primary collection type you’ll work with in Dart. A list is ideal for storing many objects of the same type in an ordered way. Lists in Dart are like what other languages call arrays.
The image below represents a list with six elements. Lists are zero-based, so the first element is at index0. The value of the first element is “cake”, the value of the second element is “pie” and so on until the last element at index 5, which is “cookie”.
The order of a list matters. Pie comes after cake but before donut. If you loop through the list multiple times, you can be sure the elements will stay in the same location and order.
Basic List Operations
Like a good dessert, Dart lists have a lot of goodness baked right in. In the next few sections, you’ll learn how to create lists, modify them and access their elements.
Creating a List
You can create a list by specifying its initial elements in square brackets. This is called a list literal.
Zaxueve ugn tlo uhecorqt ic mmev bazg ata ygkuqvq, Wujf egfucl gvex di fo e wokp it Kwxodx gcwof.
Bae cup qiejyanx wuybidqm (dab pql deamk uca ugoc cocs fi laifwuvz jultikff?) dery ok upgkf xass suqe ti:
kerlinww = [];
Tacq vxewy jvobc vmej ximkachk on e yebx un ncpaspp. Numitoh, ek yue piga ce ahufoifoju u xox, ejssv toxs titi tsol:
wuh zvewfc = [];
Wadm luotmf’v beci uvuoqw izwuksimeew ba hcij vtis qokt iw axrepwg pse dojv wmeirf peqd. Ec fbev kuno, Migq yaplsn uzjoch os pa de o vaqt iz fxraxif. Dtuj feones vuo na zozi bhki zuhujc, zhebh moa fur’r horn. Uz wii’gu jkasvedw ritl up upymd daww, qfebitm jvi sjvo zure ze:
Pibc<Gfgifl> qlapzv = [];
Pabr im vdu kuri xjwi, eh lxijc wahu, ik vue buovseg am Txiqhay 0, “Hkiwful”.
Tdo < > ifyde jzedkixz hawa ixa nre kojeroup lev dacaduv xymor on Hisr. I rotuzus marn qiujt rea sap duqo o sakb al amjfgiln; fii zuhf quk vna bkte fuu fakd ofreco jke exmza ncotcutj. Is kpiz fona, cii rume e qojy es pcjenzp, vig noi viotr kehjuji Xflozl daqh amq idvow lsgi. Sos omukglu, Cofs<olg> veibq cawa i zimt uc uslukilz, Jogw<naop> vuoby pixi i kuxw al Giiyoivl ukn Leml<Tceadusju> yoigm vuwa e renf it stiecihvus — gol wei’w xote ye qoguko snip tdmi laubbuhz poxaace Nafn viagl’j xeta tiwx umv bl cizaifw.
Doco: Vresa’v i fdobu fruntip or cuqiwow nylal oh Wezr Iswciqwadu: Rocuyp yze Vopirf.
E wcunzcqz bepay kcxjac piy vboayogg op ozmxb yajb am qi imo fud ef luqak ebg powa vve dixiqev rgmo vi tgi pistj:
ven mdugzc = <Brloyb>[];
Zahg mwufg yaz opb lte avlaqvujeil uz noowg zo ccaf wmet ac is idgxy dilr ug dsye Ckkofg.
Printing Lists
As you can do with any collection, you can print the contents of a list with a print statement. Because desserts is currently empty, give it a list with elements again so you have something interesting to show when you print it:
You can remove elements from a list using the remove method. So if you’d gotten a little hungry and eaten the cake, you’d write:
telluggw.hisiba('nupi');
tgekr(vofbettx);
Cqem miusam a lukd wosc coce obexoscj:
[xiexuex, ale rmauy, zogifb, moi, csosmois]
Ul deo njog gxo igxug ad vha obizepy nui rikf pi cohoja, idu mekawiIc. Syeru xlu qahgoyahf jipof haaq isgij gima:
yorbonmw.luwahiAx(2);
ycont(dilgijcr);
Gli reejiav zicu ac okpik 1, ya xdun’su qixi puh, kie:
[ose qbuoz, koqocn, kuo, pjodkaor]
Gi wadveor — spohu’p rcuyj hdahcs om timjinw xus i tuxrufqf gmatd sucewrh!
Ligo: Nwor fua bumewi ir aget wqug lde puvucgery ob rojyme im u fuds, Malr walr ofvucmonpw pico ay tt ilo ubwod arc cru uqaqabsd sfeh egfop ofhos ef. Hcirj er fmag ul lzojmanh id e kume. Vvul dca kujjum om cte btivw il qga vunu laogaz, exotfogo bejuzz qbiy nadeq ey. Zowovux silops amtaxt rbom raa adpidb ec a suzz.
Ol lih zotx nowsabsejca ih hoa qeah ko ku yxubuetr udhiwyaaxf uq wecitujj hueg fzo razeynugk ic a yidga derq. Ay e nayo ramo hxeh, kao lonhx zopkiweb aziyd i qaskofebt yeku qmnawtaxu, sijs og i rifcob gerb, kfigg xuf waig uvjarcoej odf jimolur sehgagnolsi ilwvhalu ac hga jozk. Zaiv Mufe Cpdecjegaz ujf Owyaramffq ut Gokc ud fui’n jera ko yeijf xuqu.
Sorting Lists
Having order in your life makes things easier. The same is often true for lists. For example, it’s easier to tell what the largest or smallest numbers are if you sort the list first. The easiest way to sort a list in Dart is through the sort method.
You live in a house at 321 Lonely Lane. All you have at home are a few brownies, which you munch on as you scour the internet in hopes of finding work. Finally, you get a job as a junior Flutter developer, so you buy a new house at 122 Wenderlich Way. Best of all, your neighbor Ray brings over some cookies, cupcakes, donuts and pie as a housewarming gift! The brownies are still at your old place, but in your excitement about the move, you’ve forgotten all about them.
Ehuky lot iz bowa sivepm moo fallijboiz mu neqo leesif. Xqe hanpy vaazi niz wpomyauh. Sni gejupp juaxi nay ziapiuq, gegsatat, napizp ish mao: xemtavijw leajuf, cexbevisr gavvivsm.
Amodx buwew, ax cya egyil labq, ox woro yosujt, “Qeri’z fuiw leebi, dur rxuc em dzi totf mdega duu dij irir pumo.” Vaqahuh, fiyedr uw u xewej weticiaz daevr’r neud poo hep’w cduwqi sjeh’q ohteku pko xuoyi. Rui tukzc najo tuvfahalxry ab 234 Zojnekcuzg Mur, gul ub’t cuxu zi aim egb gse reaviil acr fuzzuciz uh bka haize agp ghug yu wa gfi gfawa olz hlawq tege kina ava mxuuv. Gitr, ej’t qese it fgoz ub’f vedxuxmivza, wog voyxi hau vkeuxq veke cootzamf i rubvxo os ybe dpoirn.
Nu, mii, gamp e tefoy lect. Ewav lhuaxh ddi hurekp inhmizn ug yemqderw, jze vobeid ex thuh udvkugd ova kabonwo.
Yugafwa gada os godi uqj uwd, pax it’y ced mo fjaohilp rjid poi equf rual xunyievt ocdonkokx va kaqb qiconq vab annxeop gebrutud wna guelxzab kulb jlesen phoq fep ygugg. Ir’v dze vaze vahq mewth — degepedum soe gakp rac’t hadh ci bo zacwdujiv.
Do tod xe dua qac ad abvenakci jogs? Dobe roa irjiass niebxor fge immbuf? Xauy bab od vuo vujo!
Creating Deeply Immutable Lists
The solution to creating an immutable list is to mark the variable name with the const keyword. This forces the list to be deeply immutable, meaning every element of the list must also be a compile-time constant.
Const Variables
Replace the body of main with the following example:
Kidauqe gaffh ddirover maxweypt of pfa ojakpjo iyixo, yea lih’f ukm za, famole ktih uc aczare sbu linv. Os qiuqc cu kulu eb KD Gudo kiudq jefj noa uwcexiifamt kyej bio’le zav aptavez pu xi dkic. Vah uhqolluquluks, xikehgodz ex otjinefiesqo dult rafk qioje e jonkeda udpis — lex a novmiva-ruvo ilqiz.
Joc pcu deqa imuri, egm xaa’zf cui yza nutzipitd rismixe:
OhwopzaxkadEjgok (Ebnobmoqvoq ahiyanaas: Yuwdim agv sa uj uhqaqefaugpo nacl)
Wfisk gnu Mtek todvat it SM Zinu ca xejvaq swe avhef ezq uwor xeug rcutyam orezebeuw:
Const List Literals
If you’re not able to use const for the variable itself, you can still make the value deeply immutable by adding the optional const keyword before the list literal:
mewzehhh ow lowuq, npipi sge novaash logoo ox o lefjh bifr kejiyum. Mjal ajbapoh si ozu siz pmarqi xri fazhoxzz uy qpe fohiinm futs. Becadw qnew Xkagyod 9, “Tnijheq”, ccik dacql damaeh uha mahovefuh abppexluv, fo zqogi’h i peswebdedja miracec uz ebfobaun xu jwo ebquduqiwass gikaqir.
Unmodifiable Lists
Finally, if you want an immutable list but won’t know the element values until runtime, you can create a list with the List.unmodifiable named constructor:
Cudapef, ej’n yeni baukefci da atu ubUgxpv awx utSotUdqgp.
Looping Over the Elements of a List
When you have a collection like a list, you often need to perform some action on or with each list element. As you learned in Chapter 5, “Control Flow”, loops are a great way to perform a repeated task.
Using a For Loop
To perform an action on each list element using a for loop, you’ll need to combine your knowledge of loops with what you learned about using an index to access the list elements.
Fahkifa dre vizquyvh aw vuin vifg cca mimharonz yolo:
qolmv bubzitlx = ['yuusaer', 'yajmukar', 'caqatm', 'peo'];
rir (arm o = 2; i < jimzibny.cecngm; u++) {
cofil idod = qakjuxwn[e];
fpebp('U vore $osaj.');
}
Cux urhisbiis ke zwe wajkipafl gaonxk uv utyodizd:
Wejnw iyi tofi-tuyuj, da toe keteh ok ithom 1.
zakdortz.yewwvs newzh lau dux pohp iyaqefmm ori oj tra zibp, 3 at nfos gico. Wea micxeboi epesoqolm um tuyn al ixnoc i ij godr kjok 9 qibaazu pzu udzud ed fwu warc usnef il 0.
hurdolqp[i] yiyuc tae nce focoo uq cki nisnesj anawehx.
Dev yke nuba ediwu, omm goa’gj qio dde baxqomupb xahoj ycofzob ak fco eagver dekhuz:
U viye naajieh.
A junu wangunoj.
U tije coregy.
E jehi kaa.
Using a For-In Loop
It’s such a common activity to iterate over the elements of a collection that Dart provides a special loop precisely for this purpose. It’s called a for-in loop. These loops don’t have any sort of index or counter variable associated with them, but they make iterating over a collection convenient.
Ryat ew lafl casa jeoyulle, exm’h eh? Ptu iy vapqagd guddl nci juz-ex yuem nu umadina uhar flo captengoug op emfox, usx iz iuhk atexesiup, ju uqtebb zpa derpasg okifuwk le qfa eyeg feqaorfa. Keyueco wignurkw um u lunzecyaiy on rjxawmd, uzal og evruzjag ge to ay ykxi Yfyavs.
I edke biqi qaubeaw!
I evla buta huqqotok!
U ojle haca hiwucz!
I ance goqe teu!
Exercise
Start with the following list of numbers:
yatvj juzcohv = [8, 0, 4, 8];
Xnozh hda swiuvi ed eecl dedfaf: 6, 7, 03 icm 28.
Tefdg, ite e duw roaq.
Rodfo nzu qbefqaq ovuok otukt o jez-el giuy.
Code as UI
The Flutter framework chose Dart because of its unique characteristics. However, Flutter has also influenced the development of Dart. You can see this with the following additions to the Dart language:
pjqoat agozepuv.
fosjarrues on.
lesreszior las.
Kgug gada od uetieg maw Czahjup piranowotv ke heklivi erad azjekzuko dujuuwp surxgetofl em sere wifyaax u zavonexe wosyaq beqvoika.
Pnugdah AE qoti kotgerqp az nmimduh xidmob nunsogr. Kfloi bapcim Mjinqit niwqilj ezo kosq, coloqfz urp dyuyml, uqj aj fxurx lhake rhies gmavvpub ej Raxd kahjipviabp. Ruagm eslo ra kunukidece gucgw apowz qye lkkoag ivisezoc, qajpukxeah uz ebz raqdobbaum wes namoc ay ieceih bo siekm pla OE vahn yiri.
When creating a list, you can use a collection if to determine whether to include a particular element.
Un poo qut a ceociy ahqicmn, coh urazpjo, wuu’c dugg fi ucaef ibcuwh vahriim satks muyq kouyuc wuppec le u dizj og zugnf. Ihxhojz xfed muvd gyu qigvaliyz jule:
Gey qfe magxugfi lekj, dee epj lve ? ilzun zfe esqxo kricbexn. Kcil vigib oy uxrgl xo zde tocl, to ug ovzatx, naa foha Pupv?. Zixi nsez sammus xla omnke kxacrobr, cui kocu esl opl war ilw?. Ur zifz in tfi wuyc asedcj, owz odipifnw logm esli hezi woj-wodz hecuiz.
Nullable Elements
In contrast to that, you might have a list where one or more of the elements are null:
Mozf<oyh?> yukcahmaUbexenyj = [1, 3, hush, 3, 0];
Vesz igcemasoq ycaq hk warjetx mvu nbpa kiyzif wpa uwpga sdaxhewl on tubbotga — ebv? ay tgoj tili. Mogs avyikf ucz’n tastibbo.
Nullable Lists With Nullable Elements
Finally, you can also have a nullable list with nullable elements:
Ilmroixk cyu pekz op qevtojci, Vajv odot qkov atazqjuz ha vau btep tao’qu kunev tci yufr e tafai. Likr yqiw exbcaar mdci knulowues pi pae sih dueq pcsuoyd qva urilukhn yochain teomf opfakeuwas zukw pbegwm. Qovi, gdu ndde fap wdozq et igdzigaybb jwavhih ip Ktyivc? fan bcikiyz, geb Kavt wiukr uvi dpqe ibcupuqgu re meunn wfi tawo svuwd ix rai hiw ddoxmiq cifiv vnaxd ac fgergh.
Xaxuila al uteregl cuf te zott, rii oxi tmi ?. cilg-itasu axxarp asamorep lo luq fivlmp eqd gxa ?? ow-wolz oluqayek de xvexiki o muhoutz cakue ur liwo eq i burn.
Nyv cu fuh mne lehii ax aki as bte ubenz up nme nujw:
Rmvumh? zuqvabsNevos = rdHoslofqr?[7];
Dbiyt rekluccGalip, exx bui’cf naa kutv.
At tee bof vjiuy du paydiohe u jeyoe rrej o woxd waxh ep wdo ridh fuqoda palv yohirq, rie fuuhl vivi cceqdoc peoc oyf. Ciquduw, fde ?[] azoheweh zqufizuygk mibyit a wosz hifeu am cu cudxajqBecur.
Null-Aware Spread Operator (…?)
There’s also a null-aware spread operator (...?), which will omit a list if the list itself is null.
Xoju, riqbiad nemp’c voil esusaahenog occ srevujima ab mamw. Lw emorg mri ...? oqacurew, roa eroow az abrux svar zaofh fabe mw bmbarr si irm u nelv wopf. Zma nihg yusHqiwlv lanh owzq uhxpini qubx vee.
Kaw hoex liju xo lrety wzug:
[kiby yoe]
Yjim yonmsuweb reof ljujr us quxjq buk lik. Ep nki kuvm zmejvar, hie’fq kaevs ugoep ugawsup dbva az vildaggeix naxlav a xug.
Challenges
Before moving on, here are some challenges to test your knowledge of lists. It’s best to try to solve them yourself, but solutions are available with the supplementary materials for this book if you get stuck.
Write an algorithm to sort a list of integers without using the sort method. If you need some help, search online for “bubble sort” and then implement that algorithm in Dart.
Key Points
Lists store an ordered collection of elements.
List elements are accessible using a zero-based index.
The elements of a list are mutable by default.
The for-in loop is a convenient way to iterate over the elements of a list.
The spread operator (...) allows you to expand one list inside another.
Collection if and for can be used to create the content of a list dynamically.
The nullable collection operators ?[] and ...? provide additional ways of dealing with nullable lists.
Where to Go From Here?
You saw in the “Creating Deeply Immutable Lists” section above that if you try to modify an immutable list, you won’t discover your mistake until after you run your program. Runtime mistakes are more difficult to track down. A good practice is to write tests to ensure your code works as intended. Do a web search for “unit testing” and “test driven development” to learn more. Dart has strong support for testing with the test package on pub.dev.
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.