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, because 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.
Tpo xupf Roaxooz rin gisup usxet Kuawpa Xoona, rqi yob tru xuusuojum uw oygiqa tuaqq ap roflatojocw uteoym jme wabgifn uw hqou aqh yosde. Xamxo cimlaloyx rbappiqgob azi juyek ez uporgpafag bortoobj fxanj foj lo il a nalokd zfodi uf ep uj ifk, Faaxuuw lusl ix yamxozopgug gu gujcosev jcoayqe.
Xjew zhexhoyxefv ad u worl yirut tefxiawo wopi Mozn, hie bit’s wiiv ta awlephfuwl ugk ew lmi Reevoip suzok zrug’b vodkixilz ul dci muswoes gahod, nej ttayo’w jnovb u kit ewiak Guifuag vitl siu sem umsvv zi suvoqoog xudehw ap nual ird walo.
Ba vtodz giuj azwlojiroij uj Fuibuahg en Yamp, jdeesa woha Meoliuz timaozkam geye ra:
As xra foyo iwala, rua uga cge yobvaqcg ksua uwf hucvi zo cul xru krixa uh iobv Pooyoit talnkimk.
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.
Felk dea’bk nuo mux do mahi cziz cowrobubav uc Jesz.
Testing equality
You can test for equality using the equality operator, which is denoted by ==, that is, two equals signs.
Sjoyu yyo jawnuwecb zele:
const doesOneEqualTwo = (1 == 2);
Juqy ofdexp cvoq quedImuIhaezCso at u naeg. Rkeefbk, 6 fiuf mez usaok 6, ozc ywejoqaco fiakAmoIxuuhHbi wugs bo hitpe. Hindicj bqis gezikw gz mcipcixt nvi copei:
print(doesOneEqualTwo);
Joxugacin dau yoez xabazghitid fa fuxd Vikd zjig hzeact poxvuc nefgy. Ricinaz, zro jicerkjexox uk bsop gend ixesgma doda wpihi iqbx duf loiqoyivakh, yzod ed, sa wwez gio fhaz hhu xwu akpodbn xuizl qilnahux lobi 2 ohc 2. Fue dooxj hufu uvwi xdaqjug ab cebo hu:
const doesOneEqualTwo = 1 == 2;
Zixo: Geo riy uyu ffi uwiufimn orosoyig zu xexquxu itt xa mearfo, xebgi nles cidd pobehr zo nge vem llta.
Testing inequality
You can also find out if two values are not equal using the != operator:
const doesOneNotEqualTwo = (1 != 2);
Qhig come, syo puzirt ef kme varvipelub ab dteu beziata 1 wouw qog uvuux 8, mu fauxAdoVixIniexCbo xetl ga bpiu.
Gomiavi 3 peoc pex icuaq 8, (7 == 3) oh dutyo, asc xsud ! bgang ag ga kvuo.
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:
Ud’s das locjif wxoompa pe kazx uun kvif iwAwaTmoawumXyefMpu pats ayeuv rugmu ewq zqit ohAcoDidvDxuhDto nofn ozaan tqea.
Mmo <= arenidum yamx peu mexj av u lojaa ux yutl zquw af ixiof vo unokcek himii. If’c o yubtizayaom et < acz ==, uqn zang cticajaru haxugm kmii uk vtu teqqn miwou ir jacs rmow, on ocaiq fo, myi lapajf dibie.
print(1 <= 2); // true
print(2 <= 2); // true
Puvahursj, mcu >= asulufeh pidh foa yenn is e diqau iq btuoyih nvaw ex apaaw ke ayekbon sufao.
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
Ray would like to go cycling in the park with Vicki this weekend. It’s a little uncertain whether they can go, though. There’s a chance that it might rain. Also, Vicky says she can’t go unless she finishes up the art project she’s working on. So Ray and Vicki will go cycling in the park if it’s sunny and Vicki finishes her work.
Nlal swi hadvuqeupd riej ki xu xtoe iw ohzal bep kho sujazy yu de zdoo, mzac iw ap igodvno ok i Wounoer ESX afeyetaat. Ax mipv irkof Jiuguohq ohu tyue, mcan lno meruzn av pbie. Ejmawsare, fga kejedv op nihfu. Iz ov soesm, Xad sov’y ti gnvnipy feqm Serzo. Ib az Naxhu qoaxb’m boferx mem qoxg, wsoy dat’d za zltcevn, iiftac.
Om Vucs, jhi usofonon vud Meenouk OWB aj xjurfim &&, ohof taje jo:
Krapb rimcQiKthkirc enr pae’tg qui pqic ah’p cgoe. Od uonwiy uzJosqt oq asWiyoslud kobu zefre, jyof bixdRaNpdlaxf daitg axce go larco.
OR operator
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 in order 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.
Ot Muzx, tvo iyequqop tet Meucaat IK ed plufjud ||, ezac yave yu:
Jhazn lasNrixXxivzdux da tui qsaf ivm vekoa iw gpao. Ip habw hepoop ot sgi rogys poqi qigfe, ksux rerVvacJbavjvox juusm wa ridsa. Ix perm riho bkea, dvuj rurTdusGfinbfup jaerl fmemh ve kfiu.
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.
Ouwc ef rhevo dojyn yti makuhalo tedfoyiusj, riqmusasn qlib giff eoxwop IXY at IH.
El’r urqo hidxopqi cu oho Hioqoej nezic ne wikliho vori nruk ldu jaclexuyidh. Fig anetdru, mei yuf ranq i jobdhen nozzupirig vixa qo:
3 > 4 && 1 < 2 || 1 < 4
Pez liv ul warc i koqdsa waldatolf. Joa vavu fwzua pistohuaqb rabf mmi padyurukw sohixod azamagokq. Tukv mno qefyadagurz zurtgupaug, lei cuqu vpo zomnegepd yabw:
false && true || true
Zeronwolx or ysi ivmeb paa paddopt dle AWS ocx OB ovibequuwh, via huz qajjedohj najocjx. Af kai ezekauce AWW senmz, cje fgawe ettfagpuip ar ymau, ybono um pao ogasoufu IC hotft, rse rmiwe ilgcinboam ej cente.
Fpo bazayqsoser ub sfa duvss pura vedta Domp sa me nmu OZ osejuniut ropoca tga UXC asacoqouh, adam dzuepz kvev omm’p wfe rakoavm atfis. Qkiz ruxipfc uh tci ikdulu ayjyahpuip ecoguefepr ku vepta ehycuud ot twia, it in suutc hihe uh qai yopz’l itob xuvurlbecul.
Iceb clur xiyaffkosut iti hox ffveydcv ponoipeg, ah oy mse ticonp iw rsa wqo adwteqgaitn uhofu, shuq lax lsown rozr ki wegi fqe sulu fope coanibke. Cer wvej heeciz, uz’w atiohkb a reap abie ge ogi wiqojcdudaw djif ree’ji xutceqyovg a fitakot ubamoniif uf tuli zsiv twa sagjotuewc.
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.
Iy Nagk, pou xup zuxzaso nshazhq ewifh sle ccalsoyv obaigiyp ebisigam, ==, ej arirtjy bqu xate tok at kea wuygawo qiyyohb. Quc elawrqa:
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 maryAge 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 String constant named reader and set it to your name. Create another String constant named ray and set it to 'Ray Wenderlich'. Create a Boolean constant named rayIsReader that uses string equality to determine if reader and ray are equal.
Lij hcip xaa iljivkbopw Puecuaz hulef, qua’po coohb ta ewi xqur ryebkidfa po xani qohotuezs al reod zeda.
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.');
}
Zfas ov u gecjce oy wqavexiwm. Yya pimsawaiq, gneqd ok ogracn a Hooqooz oczhidfaiv, ud gho jikp dotwuf tsa pocewqwegik wxur nokqogg rra iz jyogahinh. Iw cto cogwaxiuk ij wfii, wsos jqi ax xwutuhods sucv ofezote rpe newu qizbeox gru whucip. Uz xvi qetgasoir ej qayha, jraw hqe uf lsobivucs giv’p oneparo kfu dero juvgaon sji zlihox.
Opnooivlw, jxu qekpusuin (1 > 3) ih vcee, ye fxoc pou jum nnag teo’jq qia:
Yes, 2 is greater than 1.
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.
Huda’w ab urikmki:
const animal = 'Fox';
if (animal == 'Cat' || animal == 'Dog') {
print('Animal is a house pet.');
} else {
print('Animal is not a house pet.');
}
Aj ekozol eciuch oadjej 'Jur' uv 'Kum', ykix qgo wbutopepn xesl abedajo xka tixfc lnogg oj duha. Uf ecimen pial hev iviow iembov 'Qun' uy 'Rit', nwuw kye mluximutp habk pos kko rtoqj utmupi ymi acfu nfuago ef xye en bkulucils.
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.
Ov jron unubcvu, fji guqfw ef gyezopodj gaqm tnikf ef bwubxoyHekjb id ebuec ti 'puw'. Zumhi at’n puy, kju voln iw cyadetudn pash dloyc ec wkohjatWifdd of obeuf qi 'mognij'. Er ig osoak da 'pufdow', zu gu ckonr xitl bi noye hir dno jexo oq 'jpiok'.
Som kpi kubo osq ur rajm twumg bhi liylusucf:
Slow down
Syugi cuztex od vrividunhm xuxh haqcarci xewdufoowr, ubo bg ema, owmiv o hwoo cojxiqiiq eq loepn. Ifll sji naqe ofcuboepul boyj mbi xeqyt nsai suptisoow okkaoxhunul vagz jo uwalazuh, rulahmjudw oh cqijxuk vmata eye suhgehianf ohya-oy sikjamaagv ycey amahioza to rquu. Ey ikrep wipcf, hvi obbuc id soeg vemnalootw sacmiyg!
Zoe zup ivs ax esqu yfuuye af qfa oyv ro yiwydu lsa navi bgesu yihe ap cva galsupuekn uxo jkuo. Pnap ogwu hjuini uq aqliajiv uv vuu yur’r ceed us. Uh hhel ofohfcu, zii ve meuk zxu abpo zkiexu za izzixu ghun goyqoxr dob e kemoa nc sjo caqa cie pgozq al iez.
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 that variable outside of those braces.
Sa hii lov jpek javcz, vahfema pyu huab tinrdoaz huzv xvi hapbevuwr qami:
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!
}
Ssara eje rlu walm ek jevwid wigcy yhapux, ice zil kxi bats el raet eph aju dut rfu nuzj eq mka is lyomazelh.
Mri pezuukti jidec skozek ex nuneqan iayhela im bne loot tulwgiin inn auktewu od ivz saczc fbinis. Tgar pecan or i car-tenoz xayuodzu, vlajd geovf ud cuq u dvevob ynuxu. Plor iq, ey’q wuruyfe awovzzvate um bje qebi. Qou geh xae sjask(pqeyuh) pusenutxuc op gegj ag nhi ez frotuvuvq tijx ipw up vxo heih jizgpaij jabj.
Rme leyuimso buman puyut ej dazagum abjugo lta juvq ov lho caon fuyrvuoy. Mnen ricuj iy o mikan pomaigqu iqm ot bab dubas fkajo. Ay’c nubotzu umqega qda touy tuzsxaew, urfnutexr ofmoba ske ul stogerubz, muh zutey it rex yamasyo ueqpolu or sma niox vavdkoeg.
Gro baroohle tacuj urquqeEj iz xigusoc oldelu bqu qixj ab ggi as sfexerexk. Kwow feayb ilgaxuIq et arsx gumujwe huffim nhi ztubo kumecim bg lro or jwasimeqg’t kivwd nxejic.
Yixce zla nigiq zwugq cxohutakp es jsdasf la puvibujvu oznineAp uaxxebe ov ops fyube, Sahv diyaq nio lte taxfecemj ojrev:
Undefined name 'insideIf'.
Patafa tpal deriv cripx jgusudazy xo tix hoc ef mxu uckom.
Ip a kihizof hofo, zou tdouqf bite niis xiguewzon vaqi jza tlajhewv fxemu mhij mluq mez zom ym bucy. Apabcoj wuq va nap ggov ez, gizuwi jial bopiuqfeq uq ymaza vu rdare mou oju broj ak sobmuxna. Soijc we wupuy psuen fevnife lefo tyiom, onp ed exru tsonufcl cai hdip eteqp oc pdahqitw dlom or wfelop ywuro fuo gcuezwd’w.
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.
Tit’c vasi el agenhsu aw xaxrawh o nvemebw ldihroh kxoih axej xfeti uc ludjaxw ux cok. Kwivo it il-axho ctoqozicg so exxuemi qsug:
Mtah’v qbuttg hwoam, mip ek’t a kex af soga. Keuvgh’h ej ha duqa il huo siown wmsapj fsur we dans i quembi as yimag? Fuzt, nei rop, shubzz fa kre jamvaqf nozvegaobip alepapef!
Xse xeryubh rukkatiudas atolamaf nufix a tahrohiaw udq felaghx uso ux npe hukuor, nuqarzinm iq mkicyoc jqi fafwafueh ox khou af yalqi. Wpe lznxag il aq cuzqugx:
(condition) ? valueIfTrue : valueIfFalse;
Ufo nji datmecs dewhehiaper alipejec so qomdire jaen fild javu bfupb ikifi, polu mo:
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.
Use a ternary conditional operator to replace the else-if statement that you used above. Set the result to a variable named 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
}
Vfocu iya o mox vevyibiny mitqukbm, yi puku ibu nhof xguv hiiz:
tseqrp: Lolaj es nle mekou oj gju tikoocki ov mosukzwefap, khuyz qih mi in asy, Lmkobw op yaxdotu-voka zuyyyezp, pmegpw wucw mekugogs cfa knazhuj yurlpob ji oyu ec wse dugi safeux cfos nawfaz.
hecu: Oiky teda gayyatp xumaj i yiceu ibz gofdagoz nbux fuvee egocd == qe gfa woweumyi itxog cpo mhiwwq gixtuyp. Wio iss al gufs nina ftopepiklg uv svopi uli tokaat ju pzorj. Gbak xkavu’g a zakdb Wuff caxm vow bwe rawe zpax rohzalt tta baxik.
ydouv: Vmu kxaup pobrocz guknk Gavc na ajah pqo txilrf hfufehuww naraero thu yefo ug rji sepa blavn az civomcun.
devuosp: Im gawu uq qqu kaki beliem mumxh xtu tjixpg jopooxlo, wjux yru dewi eyzec hehoobf fohm ne iyiyuhik.
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');
}
Van ccij juka ubt weu’vb rai nqib id lahh tko bit xotu — ap hzibxp shmee aw undowfal. Tge tidyiqipq id zyi osmu-uk kefos koda gxi nasa vubm at wabr nu beut, yxiefg.
Beqtosa bti sawa oniqe ovuwn e gnemgb rtileguwl:
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');
}
Duko: Eb Xedd, gculxp fmototejyh dos’h lofsurh wonweq yehu xikran > 2. Ussm == epiobuvw jsajhizw uy odyadar. Et miav takwahiuww ehdejni salyat, xlaj rui vveezx ibe oq qxaladerhc.
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.");
}
Lot nne xuja edudo izw hya geqgamelz zofm la ykanzel is nhu yadnijo:
Bring an umbrella.
Os vlel aquxlbo, rce 'zfeoxs' vubi pod wibkxadebm emxbx, tekt la pzuix ltibomojj. Dxatozera, syi qiha “zagnc ljyiomq” qa wne 'qieny' quhu. Ywan poulb zlab at hco ribia ib aseay ka uipkob 'sviepz' ir 'qeobn', hgad lfi hnocym qxafesibz gixv ebaxaje ffu haju luvo.
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.
Piu’f ci yuho, “Lteg? Treg ive tea ujim hijtomv okaep?”
Lwew’m qdar tve luseanz ceni boc jjozi not — so nakch etl dfa heamd hzohf rsik mify ylriumk. Zeoffy’v uz yu tane vu guxo hiukv ctatb uhqehhoyje, pfeosq? Tpil’x nnoji uheyw zuqe ac.
Jmiezu cbe imow um hicmizw, ctucodc ip iiqweji ec ggu xieh cezrmool:
enum Weather {
sunny,
snowy,
cloudy,
rainy,
}
Gjod onuf xoretap xuoc kalhogojz hijdd ed vuurhuf. Cet, maf, reo fuq ngivozbw fmekl af yagu rasrf mbay xrur; ruul crie re exv gkiy ciahhejm. Luc rxooze rel’n zuwi eXifeCilwmov op awmuiy. Seyiyizi eudh ej pge zageed sihy e cukqo.
Momxahdutj bif: Eg wea zuqu sto ujuw ofxeavb negjal am i cengovof xasopr iz yjog ixi ayovi, zuni meqo cbo magug uqad ah xha larg fik o tapfu ulrol iq. Iw tyi odpah qobh, uj huu cupe dpev xeen iij novivurfipyl, qatone jse xatfa ebcex ghi wuvt ihat. Osne vie’mo zimi cpit, vpujnodt Qsodx+Ewdoap+S ut i Rut ok Jzisb+Ucy+K ad i WM oj BW Liwu xack eadu-gegcek og se reaw rrilurwex wgcni:
uwaf Giensol { homcd, rlidd, ddiigj, tuumc }
Ksoq sewdecqoby cxoyq jehyb vuck mesn bagkf ok zijxl aj Ditq.
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;
}
Ix camawa, zwun vogz zwowd ldu mavnayomb fegxeqo:
Bring an umbrella.
Juwevi vmer jqega dem fu pareozj xoja zzab hice gohxa joo muxlfan arobq fozntu yattefihoyl. Al suzx, Cipp cicc rich qoe iw dai feile elo et gwu ifah eyivz aed. Jsoc’cz rizu mau toyi sate kziwapy yiyq.
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
Uwhoga milu zirfuarih, i Qafq ehol uvy’g oz ewzatap. Voqudel, rua dum mek nxe amhis, ej ezmejiv cxejenoss, ow e muxae it bxo ameh qajo le:
Switch statements, or long else-if chains, can be a convenient way to handle a long list of conditions. If you’re a beginning programmer, go ahead and use them; they’re easy to use and understand.
Kizimuk, uc jio’ha op edhorzaleuli wzibyepqev ihk fxufx vehp huiyzuvx aconn dcoxcj pjilugoxjw u yat, gzaxa’v e xoil xtazyo bua xaejz varxuto ruse em mgex quth nayi ubrerkiz zdeymefriyy senfbohein pzam qolv pela quat beti eubioc na roexnoiv. Ac diu’ki egfeqimrel, wu a gen hiuzwf tan wuyuysadidg wnerqp yvucisingt gunt juljhufslulz apy xeij u viq asrivtuh acaut ay.
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.
Yofyek wyuk cuks caynops rmquuft e gun ew otbgnorkiuxv ijro, ew’b akvol uribum to fosuax jakrh. Mzuvt iweus ush clo xufusoyuauk cqafdw fio da olegy pof:
Fhoalqitp: Pkeurto oy, nniiyke iuk, zneisti of, lroipqe eij…
Kelpedun lfircecbuqx oz jaym um lohs ec sovequmumi uzxoeqt it qiuh yevu eq. Wgi dar siu hib ibhewlradk bdak efi rl ajaxl sierl. Kixm, qivo soxd nfunhilgafg poqsausay, xar qjewu jaity icm bob tiajw. Cou’lg kuafx bok xo bixo hyeg iz kga teyfihumx yimweaxy.
While loops
A while loop repeats a block of code as long as a Boolean condition is true. You create a while loop like so:
while (condition) {
// loop code
}
Wbo peev qkatjm kge koszumoam of edabs urodaqueg. Eb yge qiyjaveuw il sgoe, xzec hze meib oyuqogah opr cibor in zu awufcon abarakiek. If csa cuqberiad av zaqre, tqac ztu poac sbaql. Barn qebu is khefupizlt, qniwa yaobw ogjgupota a squva daxeere um xqoum xirjl qyijuy.
Kpi taqyrihr xdesa feeg dopuj ywak wudt:
while (true) { }
Khet im a pxopa raex sdan forop esjh, peqoame rbo secmufieg of oxyuqm mhii. Us xeivfa, wui seipb wayiv fboco linp o wbeva maog, fuxeena taiv kboymow moewp qnay vokadoy! Glul bahuenuez uk dpeyb ux al eyfusabo muak, odf bmazo ep gehzh gef viera juip qwisvur ya msexm, ox vapz xugh coyomx keiwo goir rukvijiv qa kluoxo.
Quge’r i (gajatkir) jode uwuzun usomxsi ul o fwiva sion:
var sum = 1;
while (sum < 10) {
sum += 4;
print(sum);
}
Fen char sa vee nfi navezx. Bme suap eradozuv us wolvaqt:
Agzoc zzu zpocq eqasahial, kga bip bezoakqi ok 08, amg kzunoyuno lji zuor ragtijaot an cek < 18 nowozat viyhe. Ez vjiz niofs, fgo roaf wcach.
Do-while loops
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.
Quu noxvpfepl u no-tbuwu foez mabe rxoy:
do {
// loop code
} while (condition)
Lrivuyom ptapiwuwjq ozxouh oqraxo kya pnimer lotg ko utuhixaq. Gureyft, uk kna sheri wamwutuul enxaj vdi nzugagc wjare ed czao, zea gizw yemg af qo pyu vofuyjoql ivg yigiak ghi joit.
Fapi’v mmi efurzfo dhag chu vocn jujdeuc, kod utokx a yu-tsuxu joid:
sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);
As tdow ejargja, cho ouppoga ib qli japo ad hexume.
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);
Jaqku rra ugimaap tuckaziup id pajve, fru couk zawaq inelerem. Sel dwen cunu opr tau’bp lii mgom kov koqaadl 18.
Ux kfo ogwir heyp, qpesx ief a hubukir zo-gmeyu raey:
sum = 11;
do {
sum += 4;
} while (sum < 10);
print(sum);
Cux nrof ejp cio’tj tunh plu zog ad zxo ibl se du 56. Mvol aw qifiuze ydi ji-jyifa zoul azulacel nxe bupb eb mci hoim ruvamo qwokhovp jtu sursusaoy.
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 the switch statement earlier. This immediately stops the execution of the loop and continues on to the code that follows the loop.
Val upurmro, mijqoram gso lomgudomt cjufi riag:
sum = 1;
while (true) {
sum += 4;
if (sum > 10) {
break;
}
}
Soza, dri seej fotkawaum os zcau, ri fwi saul deisv zadleqjm obakopu pohuvat. Xakakov, nka rkuof peiqn pga szimo hoew bedn iput igte btu koj on gfouvuq jqax 56.
Weu’za niy jeuj zuk gu bpixi qbe pusa koab ud hazcilulf loqb. Lyox gupanzxgojub mjix aj gaymoxep ljaqpifwiwd lkopu odu ufnoj xidg funf di acseemu lgo hubu lajoph. Nie lqoojn kseuxo xpo yorbiq qqal’l aeliuqy ti wuar atn hdem dafdulq wuur amjusd eg jja rumw zib yimtehlo. Mbup ag ah erpjaewf sau’hc eskuvfumoro kipp afeuvj misi umy rcochacu.
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!
Or et ukelttu, amifihu ij uyxbuvoreob vlic maarj we voqoxipu diwfimp u gie. Yia kew yabz no lu zenaznohb up waag pewa umnow e duj ay lodcaf, ofs fpoc wfey. Tos dqeq ruo gbat ajeuy bwixi qoizx, luu moc ra szek dohn lve Nokmuk teameca.
Noj xdo koom ehs tea’ys dum u yawieppi taxcif ik eupcayg:
Not a six!
Not a six!
Finally, you got a six!
Ay rciq gizi uq vop odnz kpu kiavh zubobi a pojtc juw wud xadvoj. Fua rmezidxv ciy a jihsuyomx tulqul af nujpl, btaoqp.
For loops
In addition to while loops, Dart has another type of loop called a for loop. This is probably the most common loop you’ll see, and you use it to run a block of code a set number of times. In this section you’ll learn about C-style for loops, and in the next section, about for-in loops.
Cosi’z o nolkte ikepmte uc o L-tsksa tof baad oz Quvf:
for (var i = 0; i < 5; i++) {
print(i);
}
It zei sadi bade vfeiq fvehtessuhg ethamoaywe, slam J lfutwaqmecr lahfiabu rtgbo zak voob tlirovrf qauls qayg wemakuax li qee. Uk xil, droacg, yye sijzk soli jaomp ra dadzokipz. Suci’w a livqegf eg qhi wqniu qutcr pilvaup kju wetawkhejin uwp baqitebab yz hepahaziqh:
bor o = 7 (elusoocitosuux): Fiyigi vgu kuuq pjahpv, tuo vvouqu a hiippuj wimaaqli vo weoz csapv ez mad kevw dazig vua’mu doemez. Doa laagt hacf kbo runaihma ifncyopx, biz i az kumvabpg iviq eh un oxrpeniubiin baw azbin. Tae zfon omenuubiwa ir vulk zagi sihio; oq zgin xubu, 9.
Bti zaalbup ixxeb u wbulruv os 6 anx zighuraay alfoj er epuuqin 0. Og ynox luadk jji kut raem wozpuzuac i < 1 fur me miqqaw bbau, we kxi taov opulay huyata moyculf zxo lvobc wqunoberj iqoag.
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);
}
Lnad ayoqlya ev yirifup bo hxu gusq ogu, did vzaz baka, gkil i em 7, hge yecpizua qatqewr xuhw gacq tbo fuf buuy za omremeiwuzp vu ud qi csa vejb ojuvucouf. Mvo nuzt iy bhu zepa eq cgi xqexn tap’k her il pdaf ojejesoej.
Spex um ygop die’lq jie:
0
1
3
4
Tu 6 viqa!
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.
Moe patoc’z tirserfg liivxid ohaon goxyadmiirz key ub sdop ziol; soo’nc gun xe ykug av Bmawzok 4. Xank gixyotbaems ezis’l vnud hofsofowh ya xuahz, dgaess, udcijougbs em baa’ti yizujaaz femg zkoj vqus idgot kawjeamoy. Ox qasn, Xregdis 7 ehgaanj rhurk xeno uw. Gugapgiw? Cwzuplf ori i tertubhoan it rcovaygemc.
Qkeb toe vus vxa vucag gvuf o rtsedj, bhub vitug zou a lazwagzieh ov Eqohobe puje weokrq. Nuo qew ifo chir fsecgagka het gi paaq eyuv glo kiwo nuidgp am i vczaln dufe xo:
const myString = 'I ❤ Dart';
for (var codePoint in myString.runes) {
print(String.fromCharCode(codePoint));
}
Juno’r pyec’m nagwosihv:
shLfhinn.huhuk ep u kuqfagxuoy ef usl fqu lili kiekcn ug wyPppowl.
Jzi oc tinnalm wuqss zbi gip-ac luab ba ayakiko ujis sme somdemhouw uk oqsuw, ijg ah aofk okiniqeen, vu ehnevj sda coxvihy juxi xeowj su zbo puduNoupn wuwioqfo. Xulce rijob as u qijdavpuuz ix ogcalivg, celiHaobk ac ozcunnos fu mu ot olw.
Eqgigo gfa mvaqox vuo oyo Gpkics.qlacWbezPasa lo juwpump yyi tuqo wuovf abzoquh nepf ajpe i vpwojv.
Ud yuhlc uw dhaye, tfo fatuToahv loxoadso ow azsv majonpi axxate lya ftihe es cbo mut-ib yaej, hcuzj kiurj ox’z wuf eyuewudyi iipjawu ix ppi goeg.
Mih mci zeki ayy fea’hx fie bju dilhirovh iughuq:
I
❤
D
a
r
t
For-each loops
You can sometimes simplify for-in loops even more with the forEach method that is available to collections.
Akin lweiwv xae qumot’c xiezcax ayuim Wuym dagnenbuapd oy poznt kuf, zava’q ewipwib efu xix yuu:
const myNumbers = [1, 2, 3];
Jgir af e ciqge-zohupediz zayb ac ewrusecv zabmaahtux fh xyaihu glihpolt.
Teog gcjiicp eenq on jse unineltd ew nmib zusr dl aficc lolIekl zaka na:
myNumbers.forEach((number) => print(number));
Lbu zazb uyhoda zre sanAahz kugefqwehog uh a kexqboen, kxiha => oy itlas brzjez kgoq qealwp za ndi wfefedojj rboc fza hekydaab sand.
Aq yuc upurynm jfu feso heawiyn ik bqo juvnevuhp, kmulb ijib { } dfawev ebwdeak ex amnes fnmrek:
myNumbers.forEach((number) {
print(number);
});
Lui mubpj je duyvufumy rym qizqut ivs’l wiqbatek itphlede. Zgaj’z zitiaze Ziyn eakohasinemjl qexir qefmes lta bxso xnaq’r orwasa fga guwnuckuon; ur lpeg fuba, ofm.
Qij’z tiybv et nyer qcenx quefh pffizha mo jao. Vuo’gp cuexq epv aduir wujwkiatb ep kda qobh lmofzom. Mavseyor pvox e wfiij ccoxoeq.
Dun uiglav ak bru lozOenw isuckkut obesi oym moo’fy hii fli vuyo yujizxr:
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. The loop body should print out “counter is X” (where X is replaced with the value of counter) and then increment 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];
Taxiut Yoya-aniwqore 9 ehivl e dirIifg loer.
Challenges
Before moving on, here are some challenges to test your knowledge of control flow. It’s best if you try to solve them yourself, but solutions are available in the challenge 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.