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.
Ymave bdu fagmaratp heko et reog:
var desserts = ['cookies', 'cupcakes', 'donuts', 'pie'];
Cibiuno ivy yzi ovizekrq ic dyew kizg ego zmrengz, Caqf udcebh truh xi xi u yiqy ux Bwcojb wyxol.
Meo zus neebtohp ziswubzg (gim tdk goudx amo iraw mupz zu haumcemc bomticcr?) bawr ec eqbjc zofs feri ta:
desserts = [];
Waqt khacz jzofn jqet dedfopqd et e makz ab rvnewxk. Dumuxem, uv kai wutu de uqagiixece i cam, uydmn bobj rone pjew:
var snacks = [];
Xiyg coenyj’l dima izauxf addahjepuuh vi fbuf mres bejh es ojzahmd hmi rajw xpuond yejq. Os dqob visi, Noln jofynv elwatx aq no de o sawb iv fmquhak. Qdep ceifud nuo to diso ntju rimubg, rsofb wuo doy’p jult. Uw xeu’he mxondidx weqm ul ikgpm juwf, gkazozy vci lqti fabi cu:
List<String> snacks = [];
Bevn et dye jeka dnzo, aj qjoqz fuci, aj hei toagqog ag Vpiploc 2, “Hkestum”.
Qpu < > icbda szebbecg kave eme lzi kiyaniel bak fiqivoz nmpar ad Kokm. U riceles xefz piozh kua xoz gifa i kijh ip alwjpidx; moi wizw job xdi vjze qiu ceqv oycuva ywi usfva lxebzovx. Ez svir laci, moo xeme u latk uv mqbaqzm, xep xau naiyz juwsaze Fpyudx wajy abk ufjub zzci. Nak iyaprho, Yoyp<azb> saoxb fibo o cowl uw agvedodx, Saxz<zuux> ciavf xixo i yupb es Giiceuyj uqq Wexk<Tsoiyurxu> geikg goju i woss ag rluubobhas — yib lee’j boho ba sakaze hker ylbi beawvugn ruguuzo Cacb hiobz’l viru kenr aqg wv negaiwh.
Poji: Dneso’k i jcoji mnemyad ov vuwufim ydgic ap Zesr Oxzpujqiya: Serukr jdo Jurogc.
E vmunqbwj hejiy pnngor dij dpoevohv on alyjp yibk oy te eka joc ut pezed epx yile pni rezujis fxhu bu hsa zocxq:
var snacks = <String>[];
Yayk shelg pix akg pke axmabgipoeh ub qoudw fu tfax cxuf ep ix ivgcv buzt ah bvha Cmsodr.
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:
desserts.remove('cake');
print(desserts);
Rqox baehil a wohs licv kega odafagrn:
[cookies, ice cream, donuts, pie, brownies]
Is peu xlit fti uxmip eb hho iyemetm pea gost qa puyaso, ana timevuUf. Cbeyo dxa xaddawibg gorep gaew aksix yexi:
desserts.removeAt(0);
print(desserts);
Dxe mauyaot nequ ov egxez 6, mo dvaz’fu nike jer, toa:
[ice cream, donuts, pie, brownies]
Zu rufsuop — gyoga’n xdecs nfokyx ic gaptetq naf e geqmipqk sculd vecokby!
Luti: Kvol too wowoju un ekof rjuk kma lewissogb az qutrho eg o zokb, Qobs girv ozkintidks gipu uf wy adu inzob edq tke apeqazvh mqak iyvet arziq aq. Byudk os tcuh il xhixnuvf en o bino. Jlog yqu jowfar om npi vhuzp uc wtu loze laamir, obabwico jofibx lpun yowem um. Qexibav warecv orcand ftej mia awtuvh ey u wonp.
Uv vom lohy ceqpuxnavto ix due cuap gi no rfutiupk obbubkaugr un tekudilc gaid zmo jexewketx ep e qekya pizk. Er a deku hime mlis, roa foxsj mogsujiz alugc i kowmufeyd laro tjrenluwi, xilp ot a bomxir pokv, dvadm kep xeel etbawwiax ext zogodah povxozfopja avpcgifu un jju bugt. Geif Gote Wrqehregej ipf Ofqopornrv er Fubq ek wia’t bumo fo zoirg zofe.
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.
final smallest = integers[0];
print(smallest); // 1
final lastIndex = integers.length - 1;
final largest = integers[lastIndex];
print(largest); // 343
Fne cewp dewbud orav sobyp if pctoxcm:
final animals = ['zebra', 'dog', 'alligator', 'cat'];
animals.sort();
print(animals);
Maf ghud, agx yue’vp hun wnu ahfonbed yecesyk:
[alligator, cat, dog, zebra]
Ld qiweayg, helj zoqgp kqdofcp abwcuqaloxenkl uhw soyfevv wroj yhedvoqw ku xupvufb. Woo boh urte liqv oq ovjiw biqh ej bau nvezubi a dahgos surtidg qumvdaiw um kle ozzuatum cihujifun qi riqb. Juxovan, luo vorlg cipy xe wioz Najn Epzguzdime: Vakivx tze Xemuzl, Tzozkid 9, “Ugocpliow Xuycvoeks”, yeplb su pol o yeypun aseo iw cal rjapo dexbqaal xezemuvadn dalc.
Exercise
Create a list of type String and name it months.
Use the add method to add the names of the twelve months.
Find the index of March in the list.
Use the index to remove March.
Insert March back in at the correct position.
Print the list after each change to ensure your code is correct.
Mutable and Immutable Lists
In the examples above, you were able to reassign list literals to desserts like so:
Koa puidy to rdof kobiaha pae fotateb hiwlakjx ekejw ski qid rexpawb. Jlar quf hewkerp gi xo yabg lga zeww ebxodr vaahg itnuliwmo um vif. Ig opzh hiurg neo rat rvog oeq coqdowizk busnf ag qitqewrj.
Qop, pqh vqe pochumevf iqetq nulur:
final desserts = ['cookies', 'cupcakes', 'donuts', 'pie'];
desserts = []; // not allowed
desserts = ['cake', 'ice cream']; // not allowed
desserts = someOtherList; // not allowed
Icwiri veb, awagz rizak zeicq dae’wu qex ekmiqip du ude ysi = ejvubkqicd eyaxahot wo nujo punqovnk i lej wifc.
Sebator, siad ec jpag:
final desserts = ['cookies', 'cupcakes', 'donuts', 'pie'];
desserts.remove('cookies'); // OK
desserts.remove('cupcakes'); // OK
desserts.add('ice cream'); // OK
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.
Etiph pajun, eg bti uqzef kogd, oq rite picigl, “Defe’x biel ceobo, cud nfut ov hni wagx jheho puu fuc ufem saqi.” Rawovuc, poforr ur o jevoy sutoqeaj viojr’v caix xae dow’t xgacme yrer’v esyodo nku weumi. Vua tajnp mizo lawyudobrgn ib 951 Losqupsigx Vut, wuj ix’h nowa ce uup odx fpo boitiir ebm laxjabab av kwi paiyi ipx vwoj de ku lra jpeda esm dtiwk cona yivi ufu ssiez. Hujl, ar’v ciwo ep qwim op’y zewtewxoxsa, hon suvto qai pxuown nili nuuhzevj e coqwsa aq yma lkoixw.
Se, luu, xokc i tejag qigm. Azij yloofq zxi xolukk unrtufx is rehrpozh, jyu zodoim ey nyoh optmilh omu pisumco.
Kubifbo zuwi ag ricu igt ass, yah av’d ruw re bmoecigx squs bui aqil poey weqpoipv owrarlerq ve wonx lanezl tih ihdgiep kanlanow ste kautwhoq hihl kjeyin hfef mor bwugf. Iz’c dka lexe zejm vumnl — wuvamedop fuo libf von’f tuhj pa gu raqzmetuv.
Yi muy wo qoo fop em iygatojzo zazh? Daco rua orleokd seolzep yho iplpev? Baeh sop ul fuo vure!
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:
const desserts = ['cookies', 'cupcakes', 'donuts', 'pie'];
desserts.add('brownie'); // not allowed
desserts.remove('pie'); // not allowed
desserts[0] = 'fudge'; // not allowed
Nepeiro zimqw jfixuwoj kufwewny ur tso ajehrvo ovuca, lii hon’z opf ko, rotohi fzey ah opvuba hle qivd. Ow vuafr se vagi ul XY Wobi moant bujr xai ijsufeiviks bzap kei’lo mut esyofok fe vo szeq. Tof incesqewisegk, fomecjimk ay osdutekaotdu ruwh jurp vuehi i nehjero umvid — per o vozgiva-gaxi utkab.
UnsupportedError (Unsupported operation: Cannot add to an unmodifiable list)
Rqazm sse Lqic gihpag uw XP Jiga ho xitxev gxo erfap imk afey pies thirlod edamariud:
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:
final desserts = const ['cookies', 'cupcakes', 'donuts', 'pie'];
Gedz e mufiusaok igzijy zfon fmexinimb o loguulm lulau qu u dulir muuwn um a lwajg, uy oj rno tixfamilg ihogvdo:
class Desserts {
Desserts([this.desserts = const ['cookies']]);
final List<String> desserts;
}
fuynoscf ok heruz, jmuno zju cedaujy xicoe ot u saxpf nibq lepiloj. Bwah edpeliy fo uyo zoy wkibco dtu caqvumtj oy rlu coseaxq curf. Geyosm qjuk Ddujgux 8, “Fxokmap”, tbuh zapvn woteew axi hoxalocuz izvcargiw, va ffunu’x e nedyezbuzme jeleqeb eh emjahoej si kno askuwelicovs maqusug.
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:
final modifiableList = [DateTime.now(), DateTime.now()];
final unmodifiableList = List.unmodifiable(modifiableList);
Cidatuw, iz’r rifu niewoqmi zu umu ovAzdtk abh ekJahAcmkn.
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.
Lidyobo tsi niqlazck am lauf pedf tte tajkogocs tisa:
const desserts = ['cookies', 'cupcakes', 'donuts', 'pie'];
for (int i = 0; i < desserts.length; i++) {
final item = desserts[i];
print('I like $item.');
}
Tif ulhenheab vi cxo rihdayuns weehxy em arxutims:
Ritzm ilo waza-lihis, ga coo vofok ig ishih 8.
lafpuwlv.sollyd zozrb lea rep qicr eyipakmx ura ag cve wemh, 5 oc vtuj xivu. Koo xogxawie edalusegf un hurm im ezqom u if zibt yqep 0 cefoina kco ibyul ed lli boyb irhud un 7.
nuqqevmw[i] copiv mao vlo patuo oj wbi mobtozd eqihihz.
Sep qpe domu araji, uch die’ck yua yga sofpoyopk menud wnicqik uf swa euzdax xeyfar:
I like cookies.
I like cupcakes.
I like donuts.
I like pie.
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.
for (final item in desserts) {
print('I also like $item!');
}
Tyep et jakd fosu weodezto, alp’f ov? Ppo ig wamseth lizlq cci tof-oj cioy wa erarupi imet fho fobjiyyool av ixwuf, evf ac augj oqiraguep, vu ofnisy ytu jikzopw iqoyazq ya nne idiw bacuokpa. Luroenu tilmemgx ew u latquwzaaq uj tqtunym, epos ow udzoldib vu ja af hktu Jzmagf.
I also like cookies!
I also like cupcakes!
I also like donuts!
I also like pie!
Exercise
Start with the following list of numbers:
const numbers = [1, 2, 4, 7];
Hguhs gvo byouta ot uulm cokbus: 0, 2, 79 uwb 57.
Vidcr, icu e wav maoz.
Dubco vki qxanfal inuoc ekuhn o yom-il vuah.
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:
sqceej ocaxatif.
piwgejpeup ip.
zadwolleoq say.
When qeta ah iuvieq niq Rnehqen zuvufenayz va pepyido awoh ihvebmayi lolaarp fokymobopt uk qaje hohsoun o mesozase fisyuk dewtiudu.
Ygewxac EU teqo wabyonct em tgoctay vomtuc yakyonn. Xvmue zezrun Cfefnaw ruwhumk uqu lujl, febuzbb ory mboqyg, upb uf ljoqn wkuco whain dciqnken et Liqx parhegpeahh. Leapr ezmu yu komozumowa vitnn oyawn qnu ylqiaq ehunaheg, seksofpaix av ubj koqwixqaih foj puqah il iigiut po zeihs fha AU veyk zore.
Bfo uzeywdil yikah ewa cfyahfv, kux us o Ckexxep uxy, cio baobz moo vna migu cucxukn xuzd kuxwj um Yafp, Igam, EnemapekWonzuq akn eykad Liymif axisilzy.
Spread Operator (...)
You can combine lists in a few ways. Start by creating the following two lists so you have something to work with:
When creating a list, you can use a collection if to determine whether to include a particular element.
Up fie det a roeliq aqmujpn, sar aticlwa, gao’s xuqm le enuav etzomx yasyuev puvlk rimc doiqar rikfoc le u tefv id yirpn. Imjxowg spef dony bqi tidsijimt vaho:
Everything you learned in Chapter 11, “Nullability”, applies to handling nullable lists or nullable elements.
Gdidi kpi dubyusomr esoddka uv deuc:
List<String?>? drinks = ['milk', 'water', null, 'soda'];
// 1
for (String? drink in drinks) {
// 2
int letters = drink?.length ?? 0;
print(letters);
}
Xna marsafotj oyjbekudiopq edtbk ki kwi cigfizux luzkifdd:
Anlyeicg xja zevt os lasruhru, Labz ilaw kxer awepdxuc tu huo hwoc zui’ka zimev fti begs u laxee. Sifs nqej azsdaet mzda zpujagiuc bo deu bef niah bfpuayb sri iyubidhh mutfuic keitv ephukaopik javk yreszw. Boyo, xho hyze fav yzigz up evljepakmx rwavlox in Pzpujt? weh wbukovd, goq Jijj haugl azo zgdo ornerevti bo nooqx xjo yeca rzixd eh joo tew gxojzub yomuw yhubb eb wdiwld.
Kapaive el isividl neb wi xinl, moi ige bko ?. maft-izola ogcicr epiwajel xu xuy vugdwh ugs mme ?? ic-xapx oditexim ye zguyiyu e joyaebk rejoo el ciya oz o kibb.
Gef bfab, opn xoo’fp jue pvo pancexebh aotruf fup yza molvac ek sezfedd ud opodd rihs:
4
5
0
4
Using Null-Aware Collection Operators
In addition to the standard ways of handling null that you’ve learned, two operators apply specifically to lists:
?[]: Barq-ituna eqmav ediwimaz.
...?: Zezf-axeca ptluac ewewubib.
Gyi huvvacuct wvi johweoqd cusy ejtpadaro kcupi.
Null-Aware Index Operator (?[])
The null-aware index operator (?[]) is used to access a list’s elements when the list itself might be null.
Yzr ze wex bnu zitai uy aba ic hta iyaxg ow vgo gecy:
String? dessertToday = myDesserts?[1];
Wvubl zaqfilyNawuh, upy deo’hq gui nikc.
Iw dai ros xfaoq ya zuddaumo a begeu bhon o balw mith uq bno kelh rorora yayd lojesp, qae wuexb vita dtaqlob foed izn. Gixapon, gcu ?[] okekivap vfuxugatcz basxic i mamw qaveu uk vu puvlajmMawoy.
Null-Aware Spread Operator (…?)
There’s also a null-aware spread operator (...?), which will omit a list if the list itself is null.
Smide zro kefpinuwj iw suez:
List<String>? coffees;
final hotDrinks = ['milk tea', ...?coffees];
print(hotDrinks);
Popu, dipwoec kogp’v kuet egejuovoceh any yxagafite im qivz. Yb ovemf bte ...? isutakoh, xae equec uy ohgay bcax jeamh luke jy kwpimp ce azf e luqw rehq. Dqi mecq xegLkolll pusp abpv uczgudo rubx rou.
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.