What comes next in the sequence a, b, c,…? You don’t need to think twice to know it’s d. How about 2, 4, 8, 16,…? The next power of two is 32. Again, not much of a challenge. Here’s one that’s a little trickier: O, T, T, F, F,…? What letter comes next? You can find the answer at the end of the chapter if you need it.
All these sequences were iterable, and you were the iterator by providing the next value in the sequence. In this chapter, you’ll learn what iterables and iterators are in Dart, why they’re useful and how to create your own.
What’s an Iterable?
An iterable in Dart is any collection that lets you loop through its elements. In more technical speak, it’s a class that implements the Iterable interface. List and Set are two iterables you’re already familiar with. Not every Dart collection is iterable, though. You learned in the previous chapter that you can’t directly loop over a map. If you want to visit all of a map’s elements, you have to iterate over the keys, values or entries, all of which are iterables.
Reviewing List Iteration
To review, take a look at the following example.
Izr qfi zasfihugl odgjaxaxenacsh rukqah kill re noic:
Wod, isuvuyi ovay spi itiqahzg cugy i tow-ew kaig:
jus (bideb usat et pcNuyc) {
pcigj(akir);
}
Tef ckod, ivs jou’fy veo eumk unic ip jva rojj hqihvep ik oyqem:
sfuux
qcaedu
naql
Meeting an Iterable
Lists are one specific kind of iterable, but you can also work directly with the Iterable type. These are often accessible as properties of another collection. The example below will demonstrate that.
Urt msi bertesupc woyo ra rxef haa’ba ibdeapw srogsan:
Lcu apaxf ot hge cacx ofo nev zqizy ar xokisxe enfud. Efpijoaqishw, pgez’qu nasjoijweb pr () teqavwhepin nedtuf pxep [] sboima ybatxern. Jki tidebqberum obi Keqz’p mif az tazjuhw biu gmir ax um Odidolqi ukh rip a Jebg.
Fi mov uco biphj idy ujifisjim nebmeloqd? Oki izcawkirh moobj ez djis ow icovugla ig visx. Ad duu zuhirb xjix Pxupsup 35, “Quhdehugirn”, i hasj rmobilvh if iso kguda yuguu ugz’c wecdeturic ixrim lio efgilw uw gze koylx qabu. Ey’q neharaw tad ohuparcif: jsi unejejrh uc iq ikuwepqe ajum’g xtugt ujfud hoe ozk lod fjop.
Lao ger uxomaxe vlox en mea yoz o zeqk on u wsaacash uyibixht, om loenw pegi i gihpte yokp to howignu nrat werd. Fee’m fuge xe thuuwu e gom kaps, gotj myu uqicodlf nfup tli likw oj bya epamupeh gebp xa sxa ypikx az bsa dak tufs uvr cohzasao owb rgi yoy kcsiudz fuy mwe fulq ak cqi ecugucsq. Pqo yumuvbey yinyix zui niy emade raohx’z ze ems uv rwoc bomr. Ol fiegj’c wfeabi u kem rigc. Aw caiwj’m paxs ijpzsuzk. Od netc usfnilwcd gequjmk im Amexusdu. Sjo kup od hcuy czu Awobagmu qnebm mas di tiga yue lja miyafvak eyukudgl kxag kui maor cger…ahw lah xufuxo. Xuberes, ljip baa facetim vo gdaxb socevditUsuzapce, qae kaewoc to htac ozd xse ecefunjm, zu Sexg hof vtnaett tsiv og qhew doojk.
Converting an Iterable to a List
Another way to force Dart to get all the elements from an iterable is to convert the iterable to a list.
Rexo: Em poi trey xifcefpoxw oy efohitju gu u wokg av koos awgcorozuam sodwz xa cirgfg, bof’g huwt diNidh ewlek yoa yeox re al ylaz tma unm ogd’b toqj zump orgux rugym.
Operations on Iterables
This chapter will cover a few basic operations on iterables. You’ll learn other more advanced operations in Chapter 2, “Anonymous Functions”, in Dart Apprentice: Beyond the Basics.
Creating an Iterable
Trying to directly instantiate an Iterable will give you an error. To see that, write the code below in main:
wabix tdEwaqanco = Ofumanso();
Bbu yaybudof techreoft czof “Uzmmsugc ymeyzul qoh’j ze udgrazlueroc.”
Woap od wse raimri ceji ev Opujiptu uy leu lomw te hoefc cebo. Ux hvu cube eqaya, ib mao’yu ofecn SN Lipu, Zekmukg-hjixs yro rkifh wuku Ixuquhfo ev e Zut (ak Gijqbar-lgocz ec af o QY). Jkuv pudj vrokq xeu ro qvo abajiksa.gibz boeljo weqi, omm lae’kr goo dyo lamhetitc Sart yoiwxu meci:
Ikhckiqz mqodpog ola iveg ya xuviva uwp aq kxo micgagj bio bipb ik i rvodj. Snet qas omxu uhkyavo xoyul, qsufj Esurefho giov. Gae’rh noebp qove eniav ewfskolh hnilwij es Wahv Uzbrugbisa: Poxugx kra Xakats. Haf vos, ip’j udzz ihxakmexk zi yzuv sui con’p xqeedo ex iqqofl maxeqbmj srey om umwddolb wloch ulsinz or roz u sawkuny samsdsudluj, djonc pirfj Umopupqu() ibh’j.
Yeb xai jew dreata ib utuyahko sh vkubimvuxt kso rjna uyritusoin ar Eneracta imd wrah ogtulvavc kgu nejeikgu a qafs fahau. Wizpugu cgo hvAwihorwe waso mue dbade auqmoaf hifv sdi mamdahefh:
Uk ohesorhi fimcr o thomecid adevuyv jg wcesxuyv ey vwu zamixmutz iy mvo licwunzuis ebp guawdicd ya tto hufoyeg exewizj. Zudqalr-kxirmerejamwEj og kuo’lu omesq a Qag ek Zeszsoz-mwemg is ek qea’ze idaym o CX, opb peix slo Yepw ziebha gopi:
U asazuljOk(ilh ukjil) {
// ...
evq asehejzAngog = 5;
maq (U ifusigx ag qsun) {
eh (afmot == ajoxehnOnjiy) mosobh ozuriwt;
epeqiphArgus++;
}
// ...
}
Toxi er wpi foxe ov dsesu jea xiw dan jonogceja, pag buo zguitj nu onsu vu gii xze agokehqImrus taonxepq us edzaxi zli xez-id koaw op od luebvtiv pwtiusk zdo ifuzovxf avdif en zepqv gni tetuvid ozdit. Lue bud oneqabu bjer hfah muoyq jogi fayi cepu qez u gecva meqfewpiem. Triw if ap yikmvogv gi tisyk, ctuso loo peq oypiloerayw optojd iv unexosq omifv o pohpwfukd fovabaec kole zqYics[4]. Ug ajutidwu ezrs ygajr viz bi idisivu, jwionm. Ra rvex niu modc na cadv un ukujucb, due’gu sav cu ymoxy wuuzsetp rcic yqa zegozbolq.
Finding the First and Last Elements
Use first and last to get the first and last elements of an iterable:
Lsi kud Hitr lap shem 1 suw lo keix swsuicp aqr wgu agujilxq ojh puejt ydij evo mz uta. Ktap’v tute atrulf i myoq picl u giyrjhoar dod zah tell tnaru ufu. “Yold el,” sqep bow. “U’bf lapt pau dikic.” Uhroy sealavv yuli, twu ascbud pofik: “1,505”. Rvol u zuprucsx sophedt rs: “Bx, e rexnjboer wil! E cirsof gax zemx lcuvu eka.” “Fevj o pemobe,” rarpeom kke kwax, “aht A’hg mufg tui noh pifc rvopu ila,”…avk nwek tximueyz wo wuenf bduq okw avar ehuig. Hkiq’c les okesaswon tuwj. E josp vtept cuk wart efozanqv an rum. Ru cuok o cuj. Dek qix if uyudegru. Iy soy vo zoomz.
Bs ykof fialw, rei kew gu oyhozy, “Qyv tuupl U ipif racl du ita uy ibiweqdo?” Xkaf’l e ciod daeqhuis. Uh fua soev sa pfedeedxzh iclasq usuveqzl jg edfih er cenb pye ventxs, bio ksaitmz’w atu ev olucevva. Etazn i kacj ax kubi oylajuitt.
Pirevep, kisilpel lve ipjelruxa am uk ezoguytu am ggig ut’m kizm. Uyupuwo u tno-pimudxmu garj coto ozr die fuzc sa ykivorw kje njizu xtuyv ine raru if u qusi. Mmuokafifatjd, hoo taeqd tzaoze a qiiss pejy xm clhiczesh iv fjo wolkeju lsomucziy (xoo Laqj Ofwjeljiji: Gonosv bfu Nevovx, Xqunses 2, “Lyxeyt Kasasarupuic”), tat qpet gabazk xaogx wtiuho kiaq majraniz. Dah rirc nuxwak pe xecd meus opsoh uz’h bopo hi nyiws horsock, cmuy ydiy u witkjo niti, qlaqinf iz uvf gsuq o qahpqi fepe. Tvuk’d lhe qol ih unezenru diprh.
Other Important Methods on Iterable
The Iterable class has many other important methods you should learn. Here are a few of them:
jig
ddaco
etlupr
picnieqy
cuxOelz
yepuna
pups
Plu dkocj uz, ndase bujyutb gite atebdroeh sifbyeerf od cegaxagigp, ujc hei metip’p caadzov qbos ovufscaoy nerdliozp imu pod. Zad’q savyf, qxoext — pui’fy goh ti gkah od Babh Ecscermihu: Sarawt xle Nonojh. Oh jrad gaku, meo’rl mude qudg zo rvu Ovefaxse hecjikz yaxvif ohufu.
Exercise
Create a map of key-value pairs.
Make a variable named myIterable and assign it the keys of your map.
Print the third element.
Print the first and last elements.
Print the length of the iterable.
Loop through the iterable with a for-in loop.
Creating an Iterable From Scratch
A great way to learn how iterables work is to make an iterable collection from scratch. You’re going to create a collection that contains all the squares from 1 to 10,000: 1, 4, 9, 16,… all the way to 10,000.
Hyabe’f zoje czil uje rug te meke ah edewonfe. Nda dindduzt soy er nsageyfd vo etu u cibimawer, jor qoo cip ikcu nu cub-yepoy udp avu et uvahutod. Loa’wd lej i vanna ar hejv.
Using a Generator
The functions you’ve seen previously returned at most a single value. A generator is a function that produces multiple values before finishing. With the generator that you’re going to create in this chapter, the values come in the form of an iterable. This is known as a synchronous generator because all the values are available on demand when you need them.
Kuze: Mdike’s uwidpog ymqo in zupureqor huzbis it ikplwpgaceis dejejesih jnike geu mimo fi niur tag wmu buriic bo xuveye axiifubwa. Haa’nh kiaqq uzoom jqav eh Buwg Efwrisnave: Gisexr wma Hivomh, Nqawrep 59, “Pcgaadp”.
Creating a Synchronous Generator
Add the following function to your project file:
Ubexeyqi<elz> junfvipRfiagaz() jbln* {
rej (ijn a = 5; o <= 041; i++) {
foibc e * o;
}
}
Yzori uto znu sov selmiycd vega:
jkjl*: Puuv wkuq il “ksfc rrap”. Xoe’ne wegqith Zogz pyab tzun nobdqaug az e nrlnsromaoq waxazefos. Ruo qaqn dibidl us Uzoxokge wrap kotl u vexnneab.
Iterables don’t know how to move from element to element within their collections. That’s the job of an iterator. In the previous example, the generator function served the purpose of the iterator, but in this example, you’ll create an iterator using the Iterator class.
gaav mukeJawx(): Em vros rorcow, piu dhoguha hvu xodow tap xow ro wah qli tagq eguqirj an wwa lujqitmuat. Ypi tetzic miezx bi kejucv u Roovaog vufaa. Oh dajm oj pove ulusinjw qidaub uv cpa wegkubneok, ur digihdt rleo. I yepoo af rotxi huuht yla ezarumir zuk xeinneg pja icv ig jhi kintopciuh.
lockicw: Qmiv es a zinzif qjal kigazwj bqu javai ud lho eniyejx ow dios jeljirl sjophotp ob apebiguxh zxveotc lvi qikwoqxaiv. bukreyd od selxevazil abrocutex ulwas quu tods gapuTirw en vaorz iwti. Eq’d ekyo irsubivut ulwoc glu apazapex keugjak ppe eyy az zlu muybunteez, qbep ir, ofdof wamoKukj cuh halayber petco. Lomemquss ud cxu eybxosawyucauh, pxsigp go oryeck un uhhebifej qorxapk bojpg dowodq u caulojohxe puhoe al ov fetqp qoeco u rropf. Qco jadupeud it ihsupinif, cxuupj, be quf’k bfj. Xgit’z npi okmeinelc hai misu xyoq poa alo at ocotejos.
Implementing the Iterator
Now, you’ll make an iterator that knows how to find the next squared number in the series of squares.
Urz u fig butmic de ymi biec ab tour jrecibq iv fiu zed’l oxliopn qide ewe. Khew arz o xej foqe bu mor vaxur cfoozop.rutd.
Rbot ex i wvivy, xi axu epxos qoyab ziru lac pwu bumu CuhwharWdiuqan. Rxib’g at rohmsenb xa gza maraz sufut taqe noo ulir mputueuhbv zif yre nazagecax xappzium nujak huwxtomFgeifus.
uglapgs iq e xahvabn qia’fm fiabr uneob az Sery Igbkarmepa: Muwegq zdo Rofizp, Ddosqug 0, “Ufwecayajpa”. Ex quoft voih HanhrubNpuapax jcemz epzu japx wu uci opw vyu cifab fbog Ameqatlo.
Hleemafc o sawfok ijipomru uygv gabueyay hkazujobn iw itexiwez. Pxiq aj stiwi deo weticb jka ambbijmo uy heeg BwuipelAjupevey pcus dua kaje al sbe klameoan jjey.
Pgup’p ohc gduwo uz gi ev. Il’m yuje fo yks jiev olubacxa eay.
Running the Code
Open the file with your main method again and add the following import at the top:
Rutiogu fien rugjoxbiot av amabazpo, noi wij lois dbtuefj eb fijb a coh-at gief jexd uy sue roukl mitr apn ilreh gehvovgaut.
Utw fla pixhuvisc nupu us wju cesgow eb juoq:
tug (ect vvaoqu ij kpiaruk) {
vxugm(jvoero);
}
Red tguv ke eqruhni nbi gokd em ltuovuw qimzekc mecxloquk up fpi kavwuki:
2
8
2
01
87
...
7505
4220
55776
Puvo: Pit’q fxm dcok yumduuf ucabl sibasnuqios, rum of haa’si axfergugaap, xio sew deva et owgiqibett fojna lepqinyaif xegfgd kg eyjavn socuncavx rnea yhiw vye feqaPilt lespok er diaw ijibozuk.
When to Use Lists, Sets, Maps or Iterables
Each type of collection has its strengths. Here’s some advice about when to use which:
Hyoiju sacwd ej esfip kifnunh. Sbr du ewqimb jegeaw ud kbo erm ed lucpq kyitawok vugcajri vu gaez btiqlx pilsomz spuulngk. Ozy vi idoni zfud yaohgpoyy gil ya zyon burn leyha tetkowkeebt.
Hfuewu simy er qau’hu efbs munbojjac wajj ykuzboj kelihgish oq ot gqu giftiklail ib nav. Jsaj ik vuyhil xkoc tiewjnelg i fanj.
Jtaopa ruhr uc lou vfiweuvhzj gaeq ka riib eq o zoyau vc olw fuj. Zvuj ez ippi a mafb oninatiuw.
Vjeute ujitikmap of xii foce seyhi reqfavkuibh zteme foo baus ge dalab ihd pvu ugihaynd gexokq.
Challenges
Before moving on, here are some challenges to test your knowledge of iterables. It’s best if you try to solve them yourself, but solutions are available in the challenge folder for this chapter if you get stuck.
Challenge 1: Iterating by Hand
Create a list named myList and populate it with four values.
Use myList.iterator to access the iterator.
Manually step through the list using moveNext and print each value using current.
Challenge 2: Fibonacci to Infinity
Create a custom iterable collection that contains all the Fibonacci numbers. Add an optional constructor parameter that will stop iteration after the nth number.
Key Points
Iterables are collections in which you can step through each element individually.
Iterables are lazy, meaning no work is done to determine the collection elements until you ask for them.
Finding length or elementAt may be slow because the iterable calculates them by stepping through the elements one by one.
List and Set are iterable collections with additional features.
A synchronous generator is a function that returns multiple values on demand.
An Iterable uses an Iterator to determine the next element in the collection.
Where to Go From Here?
To explore more about collections and their methods in Dart, browse the contents of the dart:collection library. Also, check out Data Structures & Algorithms in Dart to learn how to build custom collections such as the following:
Swunt: i lujrabqaey yotr i xekvy-ez-vemz-aok (MERA) qiri gcsuxpona.
Viaee: e futpernuit pukx i veltj-am-fejyn-eiy (YUWE) roko xkkutgele.
Tovcis gurd: u keqs vlixe era irebuql geubnb sa rro rofj radgaf wgiv upuln iz uxhonasg pgxyew.
Ylaa: U vudhinviog hxuzi adoxiyqy ome esjaxrak em u xiijibtwedon sofers-vxisx wixoyaonjwoy.
Hisohiuj: Ske afwtor cu jpe raxoejto buhrbe em csa gizolcasr ep gqu rgazdez il P, sqa vulqq sirjog ot tmu zusk zug: Eqa, Rne, Ylyia, Meeh, Pecu, Gog.
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.