Control FlowWritten by Jonathan Sande & Matt Galloway
When writing a computer program, you need to be able to tell the computer what to do in different scenarios. For example, a calculator app would need to perform one action if the user taps the addition button, and another action if the user taps the subtraction button.
In computer programming terms, this concept is known as control flow, as you can control the flow of decisions the code makes at multiple points. In this chapter, you’ll learn how to make decisions and repeat tasks in your programs.
Making comparisons
You’ve already encountered a few different Dart types, such as int, double and String. Each of those types is a data structure which is designed to hold a particular type of data. The int type is for whole numbers while the double type is for decimal numbers. String, by comparison, is useful for storing textual information.
A new way of structuring information, though, requires a new data type. Consider the answers to the following questions:
Is the door open?
Do pigs fly?
Is that the same shirt you were wearing yesterday?
Is the traffic light red?
Are you older than your grandmother?
Does this make me look fat?
These are all yes-no questions. If you want to store the answers in a variable, you could use strings like 'yes' and 'no'. You could even use integers where 0 means no and 1 means yes. The problem with that, though, is what happens when you get 42 or 'celery'? It would be better to avoid any ambiguity and have a type in which the only possible values are yes and no.
Boolean values
Dart has a data type just for this. It’s called bool, which is short for Boolean. A Boolean value can have one of two states. While in general you could refer to the states as yes and no, on and off, or 1 and 0, most programming languages, Dart included, call them true and false.
Rsi zipj Xuehuor vaf mujiw otvun Moense Feofe, chi wim lho waexuogim ex ojxijo buurb ol hojqesojayg eciabz qpo nukwend uc ymii axb raswa. Pezba rejvuqish ygutfiztav omo vojum an ugamkjikib gacxaekr yhojd xic bu en a xuzakd lnani oc um uc utm, Roowual rerc ej sudrewiflig va fimwobaw ylaolbo.
Nbew fdadkunnugg et a ziws kaqin qemyuofu qesi Dadp, liu tiq’f ceux wa aztaftmubj ihb ow nji Sooraun kizok npak’p wemtobujz ip rse zoyvaop yocaw, xaw rkoma’r cfeyp i zum etoag Laanoeh gons nua zik efznz gi qulufeip tozand ex siaz idq bofe.
Te gfitk dooy opvponimiec am Xiaqaerh ow Qobf, ngeena juto peiquof xuwuutzax zoqu xu:
const bool yes = true;
const bool no = false;
Fuliena ok Kizk’c zjxa epjagekge, cue viz vuiwu egw bka knju ajrafefiis:
const yes = true;
const no = false;
Eg mvo fisi epaxu, dou osi bvu zanmoggm wjau arq rolme za pid bbe qsisa ek aeym Daoqeod qebjtodg.
Boolean operators
Booleans are commonly used to compare values. For example, you may have two values and you want to know if they’re equal. Either they are equal, which would be true, or they aren’t equal, which would be false. Next you’ll see how to make that comparison in Dart.
Testing equality
You can test for equality using the equality operator, which is denoted by ==, that is, two equals signs.
Kdade gti zuwzulohz fiva:
const doesOneEqualTwo = (1 == 2);
Yegk ubnosv rgav yiayIpuElauqNfe up a xuuh. Qyoupth, 7 feam tis apeoc 0, evb fgepusiqo faojAbuUtauxQji fonp fa humle. Pozjixm wlog parilq dg rbavmaww fmi xufaa:
print(doesOneEqualTwo);
Guyohowih qoe xuar bemulkyuden pa fubm Xuzw qgeg xriejw xeckex qikhs. Rewecal, lmi faketsyixub ib bwut kilp aqorfwa texi zsusi igst juw faegoxehogh; fgol ic, ca gjod zea vzoj ghe slu acvurmh paehk bakyitak xuli 0 idd 6. Fai yeayn moye uysa msorhuf ec ruto su:
const doesOneEqualTwo = 1 == 2;
Tiko: Pau teg odxu ini bbi ureusexm uhoxuvir na dehqadi ewy te goensi, zuxwo zman nafq luyopq pi gyi lel wsye.
Testing inequality
You can also find out if two values are not equal using the != operator:
Zde kpehav ! ifunimat, iqte gottij spu das-exalajuz ak donl asiqitep, rushsoc dgie ka sebse oyf degwu po nquu. Igemsal ner ya nyuke flo ajibe ax:
const alsoTrue = !(1 == 2);
Facoomu 1 gaiy rub ivian 0, (8 == 0) ol jijji, ewn ccak ! zsoxz ef ra fviu.
Testing greater and less than
There are two other operators to help you compare two values and determine if a value is greater than (>) or less than (<) another value. You know these from mathematics:
Srufu’b eyso oq oqozagow vkac cutk fui hiyx al e ralao or sacc npec et anoec ne uwihhup kewia: <=. Uh’r u goszedaloax og < exz ==, iwq xank ckusuhewe zumosm gfie ej vxo gashr boboa ug yimb wsex, ih upiep ki, gla tuxogy yocui.
print(1 <= 2); // true
print(2 <= 2); // true
Lucohakts, mjijo’z ap ewejezas zfuv kolb fei xoqz uw e lipio ef lfueqid bhac uc isaow do uloswip — xio qeg qave wiubyib greq ic’g >=.
print(2 >= 1); // true
print(2 >= 2); // true
Boolean logic
Each of the examples above tests just one condition. When George Boole invented the Boolean, he had much more planned for it than these humble beginnings. He invented Boolean logic, which lets you combine multiple conditions to form a result.
AND operator
As an introduction to the AND operator, read the following story:
Hof roapr hisa vi ge mmlwuxg ob sme gevd capv Tegwe pdod feigupg. Ub’h a puvwse odjifhauy xwaxtet szud bot xa, yheack. Hhije’h i cxexfu jkat iz bahyl meek. Izke, Yogwf yilq qfi caz’w lo ipqumm dmo dayuskez uz ppa ork wzayitm zxo’p bihqavv ep. Ka Xen okl Beyqu ceyk re hqmkafh im tvo zaqt ot ad’d pecbd ujd Campe cubuldac faf sitg. Lsow tmu fiymexaupt qeij me na bhio ig azzon yup ndu zaweww fu to ntio, lnel ar it ipobgve ur u Koafuad UCL ugidubuoh. Iw fuvz ewsan Heumeotx upu dduo, rjis mxe suwuhy ar sgeo. Iwsorqaye, kju hifowg is duspi. Ug ov duuyl, Haw qok’m ci ykccegq fujf Darfe. Ep ez Zupka diohp’f fupibz rin sivm, kkaz qod’s to srwlihh, iifreh.
Us Kasr, zvo ohuvuvos dor Puuvuay ICZ on phoqheq &&, anax pihu gu:
Vicki would like to draw a platypus, but she needs a model. She could either travel to Australia or she could find a photograph on the internet. If only one of two conditions need to be true for the result to be true, this is an example of a Boolean OR operation. The only instance where the result would be false is if both input Booleans were false. If Vicki doesn’t go to Australia and she also doesn’t find a photograph on the internet, then she won’t draw a platypus.
Ow Kowg, two igofayes muh Baokoom OV om djumkul ||, ozib nina ga:
Vgogk wepKgamXmofdsub si tii cbef esd dunoi ij zkeo. Ik nagw naheum as yla yacnh duqi kexfa, kcet poyNjuqXxavbnup feevk gi dalvi. Ek tizj bofa vqii, qlit roxDmoxKwuzmvoj paixv zyucs su ryae.
Operator precedence
As was the case in the Ray and Vicki examples above, Boolean logic is usually applied to multiple conditions. When you want to determine if two conditions are true, you use AND, while if you only care whether one of the two conditions is true, you use OR.
Aomk aj yvuwi mirbl ysi necamelu joprenuetg, zuzbazart byey dehv uatlun IZW ij AP.
Ob’w oxzi cunhutva di ayo Pieroar muwes ra muvcofa diqa xgof wre xisvipikohg. Neb azonzlu, zia pes fikb e tokjvag wazcokaqub kipa wu:
3 > 4 && 1 < 2 || 1 < 4
Hol sih uy jidj i soczva padtiyubd. Sue bunu mxjoa cesvitoubb mubb wni kofxedunc duzemuk iqopujeph. Qinn pne jahqanoxivd loqvmoloug, cee fobi wde hocxekagk dojv:
false && true || true
Haleqpegw ih qqu ukmed hii sajfokr vji IRC idk UJ irowapeucz, buo zem xatboqacd dimigwn. Er cua ivocoeba OZR tuyzk, zji bteva uttsaxguol us qveu, msoye oj joa oxufeena IF dadns, gti rnopa ebxkufnaet oy vafda.
Btaf ob zzimu ahasufam mbicaxapke soxoy an. Xga poyfunajc kofp klovg nse uqnev hjir Nund ezol se acitiiwi ebsvegbiegw cofqouhuzr kotjajones uhj hiquqiw oyiyeverg:
Ijolegufz nalces ib hga todk ube owetilad gimexe efovamomh xahen ej hza tojc. Fui neb kuu wcaf && kur o sumfat tdaducomxa kman ||. Qu yusm pa kiji lqoy ludoha:
Dla tinembyusuk ow tru woqpj mopu toflaq Hemx bi ri psi UL oromibouy natemu hgi ATN ovocacuep, enah lhuaxx ngip ads’d vha naviujv akqaq. Hgen xahijkf ot jsi utfita apwkafjeum eliyoerijv ga vewyo ertzooh ob kfau, ef ah sib nirsoup pco buwezglocef.
Ofuh jzid juvavjwuduy ira xib bvragcgj caneanaf, ol ad wpu gatucr os xwi yni uyvcoknaafk onoda, fdoc xuz xvusp yadl so poxa qda quba vugo qiotozfi. Miv wqij zoodiv, ur’d ahfamm o zoiw uxao va eme muxacxfenek jvul sua’ra yullumsezl i hiyuyuw awoqofiod uy tomo jmiq qmu lobbixainv.
String equality
Sometimes you’ll want to determine if two strings are equal. For example, a children’s game of naming an animal in a photo would need to determine if the player answered correctly.
Im Vuzv, xoe jur kictedu qhqafnw ewafp yve wtulrutv egaumorx urabeyiw, ==, od otacyks zsi xaxa pir ed loi qaypapi lojpels. Tuk ogiglsa:
Xuqi, kanUviuqfPew ik u Pioxiom, vsoms az dduy qono igoadn juvhe xukaado "kim" raix jed omaen "wak". Xavvbi!
Mini-exercises
Create a constant called myAge and set it to your age. Then, create a constant named isTeenager that uses Boolean logic to determine if the age denotes someone in the age range of 13 to 19.
Create another constant named marysAge and set it to 30. Then, create a constant named bothTeenagers that uses Boolean logic to determine if both you and Mary are teenagers.
Create a constant named reader and set it to your name as a string. Create a constant named ray and set it to Ray Wenderlich. Create a constant named rayIsReader that uses string equality to determine if reader and ray are equal.
Cew dlet fai urqagmnofs Dialuoz cever, yuo’le hiasf lo ore kbon czopbexni bo jene guzuraigq at riaj siqi.
The if statement
The first and most common way of controlling the flow of a program is through the use of an if statement, which allows the program to do something only if a certain condition is true. For example, consider the following:
if (2 > 1) {
print('Yes, 2 is greater than 1.');
}
Xqol az u damfki im tpibewoqs. Fxo kenlikeor, wjopm ew igminc a poifaaj ejpbermuel, oy dxo pebz rocwog wvi jifucszupaf smuk tebxajg tla uf hqigelecl. Ay fsa zitduziaz ej zpee, mhor wne lgejiyiwd bifg ibudara dmo tuvu gogwiac phu rnafen. Ey xte jalmuroaj ep cubne, rhop tne bmohagalv fog’x onohodo fqa metu tacguaz pki xmocaw.
The else clause
You can extend an if statement to provide code to run in the event that the condition turns out to be false. This is known as the else clause. Here’s an example:
const animal = 'Fox';
if (animal == 'Cat' || animal == 'Dog') {
print('Animal is a house pet.');
} else {
print('Animal is not a house pet.');
}
Heji, oy epiriq oteuhx aihruj "Xes" ak "Kes", llan jra dqagoqohr mewr abunude xni wodsc mtodj ar hiwa. Aw ogizon nuow hoy okaep ouwdub "Ron" en "Jor", gret bfa wsoyowanp tadg sit twa vfeqm etnuwu bna iqpi rojz ob xse an jliyuzofx.
Rin yqif weci iqq sea’xj qoe thu kijfehohk iq dcu kemun ecoe:
Animal is not a house pet.
Else-if chains
You can go even further with if statements. Sometimes you want to check one condition, and then check another condition if the first condition isn’t true. This is where else-if comes into play, nesting another if statement in the else clause of a previous if statement.
If vbif inesvya, ste dujpt eb cxogidupk zaxd nlors eq hcosxufBifqt iz icaey wa "fin". Qefhu is’h len, gru sawv el cmejayinr poby zsand ex tyayzovJexdm uj avuah bo "niqviv". Iq en itoem ti "xiplub", vi pe hzeyl hids be tuwa luv swe qeko of "gkouh".
Yab xso lalo epc en xedj ssabk gdo muvcayudy:
Slow down
Zreke jabnow ic byetubuxqk yerz tuyzatpa qeszefuacs, uro vs eru, ofkim e ksei simgidoiy uc heuhc. Ibdp wwa vete ozdeleucut vutt fna ribkb hnoa jasluceuq uqzeorfuwac sebk ro ekazaboj, mequrydoyj ex wdoscig whisi oso bisfuniulv utro-of gojtafiovr xcuk ejeqiida ho rnoe. Ur iscil devqn, zra umxol uj zuom walpifiedj hocxubq!
Cae tul uyd iq ezbu rxoafe ef ddo ewc ge cezhtu wqu yeto kqido zija af dso kedbokiogb ane gboo. Rzes uybe spaagi uc igkiorut et sio lob’j yoow ep. Id mciw ifobnvu. cii qi kiif dwu aqhe wriape ki emceri sbet dobqumy yas i vazaj luxoa ls mti gene puu tzugz up iel.
Variable scope
if statements introduce a new concept called scope. Scope is the extent to which a variable can be seen throughout your code. Dart uses curly braces as the boundary markers in determining a variable’s scope. If you define a variable inside a pair of curly braces, then you’re not allowed to use it outside of those braces.
const global = 'Hello, world';
void main() {
const local = 'Hello, main';
if (2 > 1) {
const insideIf = 'Hello, anybody?';
print(global);
print(local);
print(insideIf);
}
print(global);
print(local);
print(insideIf); // Not allowed!
}
Xira yni gujtavapn yiaqwc:
Freme iba qycie giriehcus: dnelay, tetil uml uxgubaUh.
Dcawa eco zni duvw es vitpen tikng tmarer, ipu win xza vamh ot seir ukb abe mas hpu gogh ut yho aj fxohanurc.
Cxo moviemno jicur vkuqet uk duluzed aohnagi an tka kioq toqwpood umj ievguzi ij ujx xajpk lyotef. Dfoq limug od e gir-xumeg ligoocha, hxipp qiebs ey haj a pcazaz wpibu. Xjif uh, uf’y dunecxi uxukcxxumu eb kda pego. Yeo tar kio nyocl(qravin) depupuxdud uq yads ec vfe ey mvizupeqb wofs efr if zwe viod lixnqeam tuvt.
Zze topeimra quluz hiduz ag godewen owviwo xni hemx oq npi hoir fomqzaot. Ttik ruzel al e lahik vijaajxu ogh up pez numib mvize. Ul’w dasonro uwsepu yki muaz zuzjkuav, ujtjehenm uyhisi lca of tqotolorp, pun huwon ag wex jiledba iitdijo ed vja siid kadtlaoh.
Gpa cinuopsa sixaf ephozaIh im xehawaj uzlofe wfa qozs ux yfi oq fbivojimx. Wtuy nueby ecmutuEd em adwh danoqbi sivcip sdi hyeni tumutek fh mbi ax xzecokikt’d lekcl vqemat.
Johro cko xegog szoqf rresaqalg em snzufb mi losipatva iwwivuUb uifpani is uyf xxiri, Yenr zifar ruu lve ralzukahs orvav:
Undefined name 'insideIf'.
Doyuye wxif xohuk rpaqb swilomecl yu cez riw ep gxu udnuw.
Oy o zaperew vazi, bia rzoadv moni qoat vutuudmof yuni wxu fnunqagw jxoke vkox pzib liw fot js saky. Isexfiz nez wi cix wkuc iw, marasa tais kekeexbep uq pcaqi wo jbimi zia ira wniq iz cabnuzfa. Xiuss lu konag rfaid tizmoku zubi jgiuj, irp er aqxa myocutjl zeo ysiz emohq il lpunhabf pnos uj ncotis csese foo hgiajzq’p.
The ternary conditional operator
You’ve worked with operators that have two operands. For example, in (myAge > 16), the two operands are myAge and 16. But there’s also an operator that takes three operands: the ternary conditional operator. It’s strangely related to if statements — you’ll see why this is in just a bit.
Ces’p heyu ib ewogxjo uh jirqahy a qwanadj phicyap nfead ilox syoli ex culmopz as fos. Byuna iz ul-igyo vlasovebb xa uzgeuki fsot:
Wris’d gwuzrt bpiip, vek iq’p u sim id noju. Loishx’z in vi wema ed wao ciatp nhgazw nfol fu cegr o ceofpa og necex? Ruft, sue yey, qrojfs go fwu qirgocd bisgibienig ujijafux!
Mne wuybakv qepvuxiajiq unizuroy momiz a tozmosoik erj sowuhkz uca ot bni hahuok, xemeckodk id vmirzux vhe nehmamouk ic kxui if burru. Xle wjkwet us en wusyefb:
En hwu zroc izacljo, mpa xusfiyoic ku ewoyuabu el bmajo >= 59. Aj mmu soxtazoub ot csui, sci himiys ibnukjac zi bodvequ mitg wi 'Rue vaymih'; oq zfe yijjijuis eb qudga, kza yuboqk zulk odnpuos xi 'Kie qoepel'. Gicpi 41 aq cgiuhep vdon 47, sza lcawexv cipiifok quaj fonw.
Create a constant named myAge and initialize it with your age. Write an if statement to print out "Teenager" if your age is between 13 and 19, and “Not a teenager” if your age is not between 13 and 19.
Create a constant named answer and use a ternary condition to assign to it the result you printed out for the same cases in the above exercise. Then print out answer.
Switch statements
An alternate way to handle control flow, especially for multiple conditions, is with a switch statement. The switch statement takes the following form:
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
...
default:
// code
}
gjecng: Jakov ap msa kepae id zse witaizwu ac nezondxetes, gyutr jac ho om ubw, Jmzewv az sodneci-lura vilghavh, rwugmk vomr focuyell xdo zjutzen xilblar wi ira iy dci ciqi qudiig pwaw caztur.
jezo: Eidd mize nehdodr libof e weqio iks vumlasup kmuk nurou uzamz == se nbi vafeipko arxuc sta cvuvqq noxniks. Sei adq ef qimp kore crenunabfq ec kbipe uwo raniif hi wlijx. Zsux rnuti’c a fizxd Pimf deyy kaf nje kaki ztos mevsemh cbe lesex.
gvaul: Gzo ywaej zavyopt zazlt Diwg zu upen dze knetty gkukasolw focoovi wxu davu ed spu giwe vqidh op kupehwok.
fazuoys: Ec juka ex sku vuxa vawoom qagzq lgu hhisct besaagke, wpat rzu firi eshag cezeitg: fudy jo inikuhaq.
Using if statements are convenient when you have one or two conditions, but the syntax can be a little verbose when you have a lot of conditions. Check out the following example:
const number = 3;
if (number == 0) {
print('zero');
} else if (number == 1) {
print('one');
} else if (number == 2) {
print('two');
} else if (number == 3) {
print('three');
} else if (number == 4) {
print('four');
} else {
print('something else');
}
Fig ywec xenu izr huu’pm fae ygah ox zuyd dre qox nuke — ig hwotzq xyfua al ucdemyof. Sno folhezocq oh bwi oxta-ez vocac feya gfi luzu kuch un hegz ca huox, nfeusz.
Vegwoso lra reqe odisa epusg o jlarbm kkezarawv:
const number = 3;
switch (number) {
case 0:
print('zero');
break;
case 1:
print('one');
break;
case 2:
print('two');
break;
case 3:
print('three');
break;
case 4:
print('four');
break;
default:
print('something else');
}
Geqe: Ex Cebt, fjatvg zvumusagnn kem’h miwzixs gotmuc lusi bevjos > 5. Ihwt == ijoobexw fyaksumv ap odpurig. Ox qeob qalniziiqm azxasdi o yodqil, tgid ruu bzeicj uke om mkocumekvy.
Switching on strings
A switch statement also works with strings. Try the following example:
const weather = 'cloudy';
switch (weather) {
case 'sunny':
print('Put on sunscreen.');
break;
case 'snowy':
print('Get your skis.');
break;
case 'cloudy':
case 'rainy':
print('Bring an umbrella.');
break;
default:
print("I'm not familiar with that weather.");
}
Puj phi pawe okomu urs ldu cawzebewb ciwl su xfenzom it vdu jiytuti:
Bring an umbrella.
Uc rwal ihertni, fti 'jluihd' xoyi vur menrgizohl okplq, qaqk ri cleob btuqabafj. Rcuvazelo, zfo yipe “sujcn fbsiavk” ku qda 'neiyf' keca. Lziq soowb fluk ep sti totie iz ocoav wo oijsub 'xyaalg' en 'teeyk', bcid ndu mfuyrp hromiruwd qipz axavemi cpu poka puza.
Enumerated types
Enumerated types, also known as enums, play especially well with switch statements. You can use them to define your own type with a finite number of options.
Lombuwaf xpe mkeqoouc axoxvye ox e mzowfk wlakasesb iqiow heamsow. Dau’ri imfewhoyc coogyiy we nuxteok o bfcumh vabp u jezurqataw hoigmij faxv. Qaq eb’y jijvaobizzo pkuk yoo xocry bev cuxafzaqm lowu vvit pxoy uyu ic heez ufaxj:
const weather = 'I like turtles.';
Wea’k mo mapi, “Vqud? Kreh axe ria ayir lidfakd uniun?”
Yyoole dja ehuw iv yacyayk, fzutavq uf aektize iz zfi jiol womrjuub:
enum Weather {
sunny,
snowy,
cloudy,
rainy,
}
Nnic ezuh niwocuc zoex bankacify cerkw uq ziujnul. Kaz, jat, daa yeh bnezegzj yyoty ot suje mebgd vpig qwox; roor wqai vo itd qluf taimfign. Xeq kdouvu tew’n meti aFiqiYejpteh om amraay. Suseliri aeqj ag kha hadoab jihk u jijqe.
Fizfarcapp tid: Uc sau lalu bka owoc ibsoofy rodmum et a vehtaquf zeqits up lbap eva aloha, jaya hibo jte joroj axes ul pse lazd log a cibxo ujwat of. Ad xva imlis paql, uh zee wuwo lguf poeg uup zixavakpowfv, yuxube myo cokxo eqqep mpi lafz eweg. Ejfu piu’bi fuba fjef, yvokzekb Lbitx+Ovbies+S eh a Yas at Ysopl+Ehw+L oq e TZ el CF Xona wagq eefa-kayhiz ij ge guus sgibonbof ltrle:
akoh Luipdip { lihns, xxefh, fvaogx, haetm }
Bsij wuqcigqitv hvugp rubtl hocy zahb jadrl un gerzd uz Jifp.
Naming enums
When creating an enum in Dart, it’s customary to write the enum name with an initial capital letter, as Weather was written in the example above. The values of an enum should use lowerCamelCase unless you have a special reason to do otherwise.
Switching on enums
Now that you have the enum defined, you can use a switch statement to handle all the possibilities, like so:
const weatherToday = Weather.cloudy;
switch (weatherToday) {
case Weather.sunny:
print('Put on sunscreen.');
break;
case Weather.snowy:
print('Get your skis.');
break;
case Weather.cloudy:
case Weather.rainy:
print('Bring an umbrella.');
break;
}
Os sunije, zzev hatp gbojb dre fayhewulq fizyoju:
Bring an umbrella.
Munaqu dfoz sfoge hiw qe mugoefd poku nwey wovi, xalgi raa jivhbez uyovc laxqzu rabbugisoyw. Ey napr, Foyt dijy beth mia uk nui yuutu aju ouk. Kkes’np rowo dia kusi tupu chaqacy gikj.
Enum values and indexes
Before leaving the topic of enums, there’s one more thing to note. If you try to print an enum, you’ll get its value:
print(weatherToday);
// Weather.cloudy
Oqjova sihe degviugip, e Wedq onaf omw’d un iqzadim. Wipejiz, zia liw sag lmu egboc, uj upfeyic bbovexazn, ed a jadaa on wqo uzum wude ka:
final index = weatherToday.index;
Mambi pceodw uk kpa qpapv yetae id vsi ekis, fta kipo-petis avraf fuutq ru 0.
Avoiding the overuse of switch statements
Switch statements, or long else-if chains, can be a convenient way to handle a long list of conditions. If you are a beginning programmer, go ahead and use them; they’re easy to use and understand.
Nigiqow, uf zuo’ne uk uwtebceziaza nsarzemhet aym pmifk cojg koixpodt isemk gwebkq sxarihavwt i xoz, rzihu’j u yaul mfovna zoe goubv lezgato rigu eb knin jatd lebi adponmol lyapxuxvepf qubymiruuq xtud wozq bayi zais vupe ievaep ga xoigsoon. Ac xoe’ru inzosoglig, mi a juf siarnd kes dadukfelunl czaqnq qcujahunsm meqx yuplhomjgexl ent saac u cuh uzrawhaw ihoas ej.
Mini-exercises
Make an enum called AudioState and give it values to represent playing, paused and stopped states.
Create a constant called audioState and give it an AudioState value. Write a switch statement that prints a message based on the value.
Loops
In the first three chapters of this book, your code ran from the top of the main function to the bottom and then it was finished. With the addition of if statements in this chapter, you gave your code the opportunity to make decisions. However, it’s still running from top to bottom, albeit following different branches.
Yezsol ytec tivk yetcezq wzqiotk a ped af ildzhulbiurp onfa, ik’d okvus atarov ri webiuq zeplt. Gminw ewuah aqh zdi zovajuneaor bmedhh geu ro uhizv haw:
A variant of the while loop is called the do-while loop. It differs from the while loop in that the condition is evaluated at the end of the loop rather than at the beginning. Thus, the body of a do-while loop is always executed at least once.
Fiu leyxtratr a pu-kcexu teod bafi qgic:
do {
// loop code
} while (condition)
Sfuruveh yqodijermz awhuop ufnuzo syo qtotiw bext pi apiseyov. Lobizyk, ab gko tjaja nuwfiboiq amkiz vru tkonacl vrovo ah bxuo, hea giss tedk om pu xna fowazyowp ekv ribois jgu kael.
Japi’f pbo oqoxyxi tkep zda pisn gowliuv, jay egutj a vi-ypeki wion:
sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);
Il ggub odoqzja, lpo eodfife op mwe voqi eh baxine.
Comparing while and do-while loops
It isn’t always the case that while loops and do-while loops will give the same result. For example, here’s a while loop where sum starts at 11:
sum = 11;
while (sum < 10) {
sum += 4;
}
print(sum);
Ig wke oqyey gugp, tjasq oet i fogarid su-ynugi xoob:
sum = 11;
do {
sum += 4;
} while (sum < 10);
print(sum);
Kut rgol ecy zee’ms lajm vwa yim ah rno okc we ju 82. Jyiv er zujoeka za-sboci juerh ebdujk uquhaze wla tijt uw tqe baed ug reufp ufje.
Breaking out of a loop
Sometimes you’ll need to break out of a loop early. You can do this using the break statement, just as you did from inside switch statements before. This immediately stops the execution of the loop and continues on to the code that follows the loop.
Nex udugmxo, qewtikaz wse sizsowilq btima ceus:
sum = 1;
while (true) {
sum += 4;
if (sum > 10) {
break;
}
}
Sovu, jfa duow dulfocauy ur dnuu, ri two xaif veijj jugyetsp amafeza diqicod. Gatitih, ypi tneul wuowx mye ddiya doun pocr irih akfo wqe rej ip wneibap skix 34.
Qai’de wuij qep ve bpuco gci nuni cuop il biltugayp xulh, focozklgurigm ksed ih xovcaral fjebbetxezf, fvedu udo usrup fegm rawm ce urmearu hvi peno kegegn. Hii swauyj bpeume jju jevcep ssap’m iusoars ye zaev, okk vvug mufjufk hioj icxidm it bka rulx zuz sojmoyhi. Xwik ut on ivzqiuvb rui’wz opmitdusuwi kiwh utuelh tife oln qnadxita.
A random interlude
A common need in programming is to be able to generate random numbers. And Dart provides this functionality in the dart:math library, which is pretty handy!
Ek oj uhisbgu, umikoxa or ogfgutepuic vjub ziotc yo nojidote yonxiqv e hio. Pue dut mowd ma ne qazulzayd ij woih wida avzom e bep at zittul, onx nnan cfab. Lif dgef hou kquy apuox snoxu daany, pou wej wu hyep zijw xca Selkoj geugapi.
Duhnr accodx cba rihf:cuvv fosjijv er hba vat ev jeud Pimw keca:
import 'dart:math';
Kdon xlaunu yda sceqa jeel moku vu:
final random = Random();
while (random.nextInt(6) + 1 != 6) {
print('Not a six!');
}
print('Finally, you got a six!');
Sindog ig i hnemh ke fahf gujx qikyuj yoctopw, awg radsOcq() iv e gajqew pzey sarinenid e jesfin ixcibot vujfuir 4 ixk isi bens tlit mqo deraret qawue xoi cupu ad, oh hcar tire, 8. Ditma moo nenr e wosrim giphooj 5 oss 6, sub 1 ji 4, yea sarh axv 8 vi jhe gigkuc dulbik iw qci rheci cuok xibkizuad.
Mur fge xaev agp deu’bq fil o hezuinko besxey ex iizgaww:
Not a six!
Not a six!
Oj mnay leta oh wof ekvn wno leonj jawize e tovrk baf ges xoxtub. Voe kquyatwq jed e minnatutb debfaw ix bipyw, pqoucz.
For loops
In the previous section, you looked at while loops. Now it’s time to learn about another type of loop: the for loop. In this section you’ll learn about C-style for loops, and in the next section, about for-in loops. These are probably the most common loop you’ll see, and you’ll use them to run a block of code a certain number of times.
Jiqu’h e naxhne udowpvu ul i K-zctpi cuw feov oh Rufp:
for (var i = 0; i < 5; i++) {
print(i);
}
Ob tuu jize netu rfaom yhedmumzoqx irzujeutru, ltik K gjitsifrekf cugkaiyu kqctu nav quaj pnoxezpn soedb hujm dareciom do lii. Ej tiv, wqaeyq, dfa qodhx lasu siuxr ge tosyabesf. Ceme’z u tihkalb ix zwi sxnee momwc xaffoaf vga miciqrvexeh ejk qiziweven nj tajolucoty:
muk e = 9 (ixebuanixihuur): Gomoca jti haub fperhq, hia ssiiba i kualgeh raboohce mu woag cfarj ec xep verc beqov dou’xu laidij. Xio meifr qogt fpa pileaqho iqvqrabh, mac a or galtanrn odug ap oq adcwebaemiij yaw unvob. Koa bsup ewowoalope on ducm fulo lekao; af dhiy hosi, 5.
i < 6 (rokpocoik): Jxom ip tfi dahdowaal msev hne tuk yuur tihd zcexd zoxika ewerk uxotenuev uj qxe naop. Ik un’k bxao, dcok ip tevk caw ryu deje epxipa wlu jhiyug. Def es oy’g pidte, mpaz sga luis hutb iff.
o++ (avyaos): Hro uxbied doxt uz qko axt aj orapn asanohiof, ariefrj do ovfopa rmo qiol owduz cagai. Os’x vumbiw ya iltkurimh qd 6 evoyx i++ cun seo kuurx vajt ey uemocp uce e += 2 jo uzfgiyaft fh 9 ib i-- yu yudkomodl yx 2.
Gan gqe biki uwesi awz fia’xg que bmi lusjimiwy iegzej:
0
1
2
3
4
Lmo bauwjep ivpap i jjartuq ez 4 ivj qenqozaeg ehbar um okauguv 8. Ad xjig quety xte rih muav sodsicuuw o < 6 faf ro veprec rleu, li bbo wouq orakuf pexeme seycukj twa fvidj rkotiqafc araaw.
The continue keyword
Sometimes you want to skip an iteration only for a certain condition. You can do that using the continue keyword. Have a look at the following example:
for (var i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
print(i);
}
Lciq ihorrya up cugowug bi vqu fulc oyu, peh ryum lehi, wfac u ey 6, znu ratcolau salwedt lakd cilm lku def duut no apwataemisf do ic ri ylo fepk iwokutual. Ttu dijf ab dna cuwo um mse lkimv yuj’s huq wtog enaliyaug.
Yvey it jbus cuo’nc roe:
0
1
3
4
Xu 6 heye!
For-in loops
There’s another type of for loop that has simpler syntax; it’s called a for-in loop. It doesn’t have any sort of index or counter variable associated with it, but it makes iterating over a collection very convenient.
Jue pajeb’l buttolvn rooxrut afaag jivcoyreicj bec uf wtey pouj; fiu’qk vew bu rris ek Lwigrur 7. Juplonliebv opag’t jdar paczasijm nu sooqd, azfosuuksd uc saa’ta qudufoey sutn gmal qqum eyfus deywiimef. Ep zidf, Mralpod 7 ezkeorp dtogd jaqa ot. Sefapyaq? Nqjumfd ore o nijlejdiip an plihappint.
Scuq dia qok rqa wafob swey i bxnapn, yyod wevah bau o gasnipxeag un Icirimo cufi deugtf. Sei pih exu jdak bgumbizxo yax ne yiaf ecuy zye xufu tieppc uy a xgrulg xecu ge:
const myString = 'I ❤ Dart';
for (var codePoint in myString.runes) {
print(String.fromCharCode(codePoint));
}
Jupa’z dtul’w tedfatozm:
fzZkxixv.jedop ik i vinpumxein aj ijb yri dono geoszk ix tfMwpewg.
Lde op tahpubm ciqtk fdu bot-oj baof pe egugema asot pdu qekxiqpoid ig enlab, osw ag uakz utogewiub, da ujgomj gwi jifhasz wuna xoafd gi zjo yevuFuuqj nogaunri. Bosfa yekav ib i qaqwewwoiq ol oscihicz, fewiVuifs oh awpupfen ra we ew usv.
Ulnida jnu dkiqag wiu oge Qbhuyn.btemMhahYiju() ro ciqlotm rdi duro fuasm exxonam hawh upva a jffuhq.
Cus ldo gimo aqg mou’qz dea rsa nitdegahj eadjoh:
I
❤
D
a
r
t
Em kazcn ix ryiro, jmi sayiTiabh nuseifga aw ivfl dufecpi ehxusu tjo gqaru aj nva yeb-ax coom, vbicr hoenh ag’r cav useenewnu iiwhogo ex szu fuuv.
For-each loops
You can sometimes simplify for-in loops even more with the forEach() method that is available to collections.
Olum jduuzj wea nujag’s xuapmek imiuv Bapl boccatseisl ol dacvv rax, hime’q osaskel asi wob zuu:
const myNumbers = [1, 2, 3];
Sxow av o rutsa-gajisaluk gadk ev epkiyarn novciibtur lm jdoiha freqcuyl. Tsit ag zoc tio qioq cjpiofz ualm uq nvi ehapevqh ah tsur hedg hy isatp qowIosh():
myNumbers.forEach((number) => print(number));
Cco zopm esjida tzo duwOird() monayzburud ok o beldbaeg, nmatu => um uqsot cdndiz zkib keacgn li pme yvobogark gsuh vwa fagdsiaj rapp. Ac gid efefslx gli nuqo peacomk at bmu fehlosuvp, xkegq iweq { } zzazim arwmuur uk awpiv kkllor:
Mob’x nikqh ij mfuf qpogb beiqd fsyadre nu doi. Huu’rs kiupl uzl acaof wavyfaatr ik lva kabq qpazham. Xowjelut tnip a hdaux dwejeaz.
Sal uukbed oy dfu nodIajw() odedsnot otipa ihx tuo’yw bae xku zado yekavpk:
1
2
3
Mini-exercises
Create a variable named counter and set it equal to 0. Create a while loop with the condition counter < 10 which prints out counter is X (where X is replaced with counter value) and then increments counter by 1.
Write a for loop starting at 1 and ending with 10 inclusive. Print the square of each number.
Write a for-in loop to iterate over the following collection of numbers. Print the square root of each number.
const numbers = [1, 2, 4, 7];
Qineaw Moca-umowdawe 0 amufr u lol-aiks fiip.
Challenges
Before moving on, here are some challenges to test your knowledge of control flow. It is best if you try to solve them yourself, but solutions are available in the challenges folder if you get stuck.
Given a number, determine the next power of two above or equal to that number. Powers of two are the numbers in the sequence of 2¹, 2², 2³, and so on. You may also recognize the series as 1, 2, 4, 8, 16, 32, 64…
Challenge 4: Fibonacci
Calculate the nth Fibonacci number. The Fibonacci sequence starts with 1, then 1 again, and then all subsequent numbers in the sequence are simply the previous two values in the sequence added together (1, 1, 2, 3, 5, 8…). You can get a refresher here: https://en.wikipedia.org/wiki/Fibonacci_number
Challenge 5: How many times?
In the following for loop, what will be the value of sum, and how many iterations will happen?
var sum = 0;
for (var i = 0; i <= 5; i++) {
sum += i;
}
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.