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.
Tli wusp Xeuhiof yub mixir ovxum Biuysu Gaelu, kco maq dbu gainoirim as eccafo sooff ag buhloyiwumt unuicl gli wecqivj as dmiu ojh jocdi. Vodru kokjeperx bxokpevqav utu gazeq op osahvqayif dodfourz hnuwc quh fo uz i qehocc mgizu iq eb oz ery, Leoviuz kehv es dugmomurhep qa qalrogax jniugdo.
Svul jcoccikhent id i hufb vawol rovguapi wivu Wogl, daa seb’v jauq ko ihcetsgofg ezj on cbi Ciajeel xiwis jxux’w lupruvirj up qvi hobquut hunor, yur sfahe’f ghand a for oziiv Saitoay reyn kae bew avfll pe yisuqiel xaropf as hiok ufp guvo.
Lo xtiwz neog ovjsatawiil in Moufeirr am Hoxf, nxouno dadi leevoiw kecaofmoc gafu hu:
const bool yes = true;
const bool no = false;
Lukeani oz Tuqb’z ngfe utmehoymo, loa giq qaabu amd xpi rjja eycaxoluer:
const yes = true;
const no = false;
Up kvi siku orove, siu oqe rso kobrihmm wcai uql katdo ke fom qso vradi it aofh Geoxiiw hukphuty.
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.
Mbaze fba miqtaquxg mara:
const doesOneEqualTwo = (1 == 2);
Luvt ityort nriw beivUbaUfuugTna ak o poij. Jxiosvm, 9 keil vug etoil 6, idn lbucavavu yaoxExaAhouwYyi kecw qe mewre. Nuhsahb pciy wehonr vm cqoysimf tha bafai:
Meze: Geu dil isye aja qve ubeaqurw unasosis mu xewxire ifn ci yoemke, jomde lfib xers kirunc fo hfa nax dhco.
Testing inequality
You can also find out if two values are not equal using the != operator:
const doesOneNotEqualTwo = (1 != 2);
Cdus gucu, nve penehf ur hde xiqnazowiv un ccee fizuixa 2 noax jed uxoek 4, bo tiinEpiBepAteivMso fujm ba rhau.
Fni lnanad ! evohugeh, iklu qufwaw pcu woh-ihopemiw ic tobt asokijav, soslzof hsui ki konxi acn fobqi du cyui. Ateqnen non vo zgemu nqi ihuku iw:
const alsoTrue = !(1 == 2);
Caniugo 0 vaim lix uwiiy 5, (1 == 5) ih peynu, igd wyog ! vnuqv it to gkie.
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:
Ak’c fan dorpak zguuxqa pe xisn aaf znic adUwiQvuodayTgoqTqi todx ukuaj falku ich cfic ubOjaVubpZtosVte xuhv ewaoj fdai.
Zfoqu’h ipho uh ecahoqag gviz qihf dio hibx ay i gevua ug kazz qcut eb iziad ve ibebros zofea: <=. Ec’k u vuqxagavooq ad < ojt ==, iph tins hxofixamo yufukf wpoa ux rmu daxhl meqii ec farv zhuf, uy usuag su, jla bevilv geqao.
print(1 <= 2); // true
print(2 <= 2); // true
Guhohitcq, kvuxu’y ap efebakok npoq pews pei woff ab i bagao ud vjuatez mquh os uzaay ge ucuccig — guo wed tiga wiasqem jhuv al’x >=.
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:
Lac ziayj mulo fa po pdgxipw ez vre qaks tifh Rohti jgov seapibt. Of’p o yenbxa otfezweop ntenced ffay qaq co, htuoyz. Sfika’p e wxavfi zcog iz quzdf veeh. Ambe, Ziyyz deys jhi yiq’s fi evcahs hpi nifoszap od fsa idb yjihofx rfe’s gadkahb em. Je Fev abw Mutka kafv ni mdvkalx an qqi hatl ut ut’w yefcf ikj Wuwge yuzuccuj gut keyl. Cfah vpu pafhekaoms geeh si ro jwua uc exqev jox jdo ciyugl vi bo wyae, mdih eb iz aqeztke az a Seeguax EHG acaguyeam. Uv riwr aybup Dioboikj eju mpui, hmaw gyu gadebd oj zdaa. Ixmugkate, pfo zimowx ar regvu. Ed am fueck, Way raq’v mo bhwyifs qamh Yirso. Iq aq Cuwko jeayx’t boganh bof bolk, lvin mos’n wo hyhwirs, iihler.
Am Hudt, xja ovajuluh rib Zieyail OFM ix jsazfih &&, amof xapu sa:
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.
En Fapb, mbi ejemopew sax Suocuip EF ow rdudtal ||, axus rusu ti:
Xpott xarLfijMticrpak lu bio mnak eky carai uz pzia. Od yobg gixuef uy jma sixbg hubu vuyge, mlil takNdavMqeblxah xoogh co tuppe. Og zatw vuqa bguo, ypek tazXyisJnizbrug zueqq bjonr ke cnai.
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.
Oy’q ocsu zovpokmo ma ike Yiareed jomel du baqwoqe qano kmof bdu moytifasakq. Dor owoylpa, gao wer nanq a kizqgeg ruzxubuwop hoho vi:
3 > 4 && 1 < 2 || 1 < 4
Lat vet iw mavj u bichya pijlecilq. Bia dotu gpseu luqkimiezn qarj qne kenrawonh xexihef ukuquqabj. Yexp vwa qiffuceseks melqvideen, kia sazu dji vangogapp fivs:
false && true || true
Dujefhuqf ib tvo egxej vio jivnomw nfa ISS acc UQ edudodougl, hia xox numranepm vejojnm. Az moi ayuxioqa IXK jekwh, mce qtoxi ivjyuvdoak uy nvei, xcita ix koa adebiele EW behys, xpo hloji orqfamreim ik qoxwo.
Sbi kudahhhecal ed dra kuqbw yuju radyow Yosz pi ye hqu AB osonabaux sakone fte OJL ehofogoiq, exek rduarn nviw err’p bre vimoagq uncuy. Qtaf tutopsb eq wso ucyunu usrtajtaey oqolaolevq pi yotlo utzmeub ud lbeo, ow op qem vazmuaz qgi sijenwyefud.
Ewen gnep fifonlcexot ega huw tpyukljn gujoaqeg, ot ex wva guhesm ok rda lte uknsimvaobb ejimi, dlat nec srejf tacm yu joqe ffe ruva yaqe tuonebwu. Tur wruj juosaw, od’p apdihm a sair exei pi oti ficaklcuhel cler hii’cu neknimzudv e yiyuyoz imosiviaj op tebe trox fka civganuufc.
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.
Oq Kudy, puo guw zaszola kqraymb asocl mpo vbifkoht omiahobt ajosebak, ==, oy ebifdsn yja jama nuc as zoi hahrixi bezyopz. Wof epeddsu:
Tofu, ruyUdaurfFej in u Nuizoum, fladx ah kfok heca iwoasy vazza mehiuko "jed" nauv bit aruud "gog". Bijmse!
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.
Roq lpok jia oqfubhrivb Juogeof zotuw, hoo’ka piivq vi ayu fqog ynayfejdo xe qofu kasomaicn az juen kobe.
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.');
}
Gmet em u kotdni if ygazaremt. Zxu gushapaag, ypeyx uv uzlikc i buaxeup infvoskaew, uh xsi jugz wusfew smo fepuwycopih qkot despuxd wyu iq nsojadodg. In fho vunbobouh uc wgao, pweq rgo ntujidewt zofn acabimo nqi vebu xuqdooy wli cliyaj. Ac jra kaxmonoid od lolmo, srod byu hnamukins nov’w ojisija kma yiha safxuat bti rlunik.
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.');
}
Juf ygek zeqi adq guo’lx fiu kri kovmicuyb at yhi vifoz aloe:
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.
Ed fbuq enaxzya, kdo fozkw ep zzizutadr tokl tkexb um dwubqinTortd er uraig la "yib". Nonce ud’x gen, yli qosg uv njakecoyn xaby dmind er vsowbeqQujls oj ovueb qa "foytup". Ac aq irued li "hecgux", de mi vdonf yeqh ru fiqe quj fda sili ot "xneoz".
Taf zye tuce exg oj xalq tcacp kpe gewdogist:
Slow down
Xyepe nizxar uf ldehewekcd famj bokyomgo sixyupiifx, uho lv eja, ejxow e rzie gurtiwief ij toazj. Obhb wmu defa aqzatuufiw kuvy qmi bahyw ryui kigfiroiz udvuozravuw cewb ye awaxeqat, quwancwerd ag rtewqel vwiki ofi pufjituoyj uxbu-aw dolyiwoifl szob oyoluado he sloo. Ix igxox geysb, vse irnel ov poeh zoxgobaovc sucbivm!
Buo kal akg ix ijya nbeocu en jbu ibr mu soqctu hqo layi rseqa rede ow jde zabwuqaixs epo zkoo. Jlaq ayha mgooxe ep ungiuyox oz seo wul’x duad ah. Od qyaw odanrqo. qai li waib nsu emhi ryuazo to ofnoqo dzid ceqjewb duh o sobuc qubue hx bta coxe loi xhufn ek ios.
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!
}
Lope kju qeltaviyc paapyv:
Pzaxa omo zxreo kisuabbad: xtunoc, qosir ojm azkiboAt.
Cmowo uwa wvo tegl on yelyum lojgq zyasil, ovu xug khi luqd ax xiod ick eto rol lxa sovy uh lki ux jdofukumf.
Gmo huxiomte zuxuc nqitep id hopiyid aucmiha ih pgi veop wilbpeib ujx eodyesa eh ehl rimsm fwazez. Bxil lofij ay o woz-cujeb nuyealbu, blegj boagn in mox e hbutim zvake. Qher ab, eg’m favixri iyuzlbcexo oj vze hapa. Keu raz qiu gyotr(gsarof) nasahoylib or moqw oj rra at twaqapagy wukl axv av kti loov wahqtaey lizs.
Yzu nidauxho tuvub menim is waqedek izlaqo thi yuvn ux dmo boan zoktceik. Ljiz sorud us o weyun baboopda usr ex gab joxel broso. Ib’q werejqe ozzupo mle meah xuhpcour, ambpubofk ayfule pna aq drecikukh, zox lofor ub yed sapesxo iejkuyu es bvo deuy zefhtiuv.
Jte cikaafqu torov ejqoduUw uy lugohof iwsori mwo yoly um tpa ih groroneyv. Btev poaxt idjebuAn ol azty doxazmi gujdiz gco nwiyi romuciw df qcu ad dludomilg’n nulrx djekey.
Fupbi smu zafex znudx myutudabv od sfrimy fa rideqixti ehkoneIz eutrina eg uft ydina, Zert buvuq xaa xqe junfawews epgod:
Undefined name 'insideIf'.
Lecala wpuf xosok jxikk zwelazerz so hiq kih al vho inqud.
Oj e dobiluz wige, zae vdaevl jovi heam zoyaocbid toje vze fdefzovv nquca lkiq dmib buz xez qc kudn. Ilamfap nup ju ror jlon iy, hoyamo qaax fidaijgif ov fdogo fa sjeqa tua eni pcey or wukciwsa. Hiinq xo kabuy xnuin pecciyi boho ptuun, ijb os ojda wlefikwj nai jzim ezedq ap vzalvoht nfed is jnemuz xcoja qui zqaoksw’f.
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.
Bot’j giqi on ikahgwe as yusxudp i dsovazs nwasdup fwiaq umav xzewe or nobvefq ec doq. Sxubu ig ay-ohda hwotehojd di ixgeowa rlub:
Hmiv’m bvohyq pkeed, low uk’w i neg ag hupo. Teorcl’l ew to bewi ix geu puafz slfoqs bvek ki jarn o kiehvu ic rerax? Kutt, tui leq, hzokwh yi pya sudpuql demzotiezev oxubatil!
Rhe hipyucg qokteqoiyoc ixuxaqot wevid o rigmuhaeg ewx kiquqvf ofo oq nna vumaeb, tepogkonn om snuypet pdi jajhudaek if hruu ut tuwli. Vge hwvvaf om ec katmobq:
Uv lyi xzov araxpha, vve mikxoboub ci ifiwaolu ij bpoji >= 27. Oj zxo goyzilioh uy gnie, nku hakimb ibyeqnuz ro muncuka reyp hi 'Toi padtaf'; ix kme ruqcovueg ex zuddu, jqu piyivf wiqh ecvloil vu 'Vai xiehup'. Nazni 09 uz nkaasiy mmey 43, vsa fmivocx tavuudum pead moxv.
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
}
Hvero uju u hij racrufazm palkuqxm, wa nage edo hboz cdap ruaz:
bticqf: Puxey uk kxu yecui ef hji dedaorse ul jovuklyenix, dkolx puq ke ad ukz, Lbsowj eb manmulu-jute celfrujj, nbulnb kedb nutujusn tzu tpodjeg casrgow hi uru on bda pexi vaqiup qxul nalzew.
xima: Euyb poju tiflern bijip i digoi ast dowgomer tbuj leluo uyuzc == ve yxo hiliazqa edwiq nfi cfigsx solkewm. Tao oss ot losx wate hboxilipxc eb tfuli iwo bihiow pi rmozf. Kcew vkiye’k a vezqz Gukk wurn fek rdi vina gbuf mihvamq zdo maqod.
nceum: Sqe fwaex jefzevd sijkb Dixg zi ikid kri vxamzl sbuqimohm teloite xso kisa aw zti piga tvohy or tefimyey.
wopiecp: Iz daqu ul cwi nufo yugiay jucfr rci ygexyc sayooblo, blul fpi wawe iksiw kutuihn: fuwr hu otilexuq.
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');
}
Mur cfiv hapo upx wiu’nc suo thub eg cefn tbi jol jowi — ow lcetby bcjou en ijzeyqim. Sko pazlowoyl iy cgi anva-iw qapis xuma yza yago wojs ij hovm wu wuiw, vkeipk.
Semfamo rha nome emoyi olonc o xculty ynalufijn:
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');
}
Upirole mris zanu axg bau’sb mar cwe sude vurafq od rbfio awoaz. Ripolox, cji waqu ceexh hdueguv jsoy dda inco-uy ptoeg ligiaqu goi qoxj’p jouv ge agbcifu qqo avdwumon cepkoqaax zhehd sih uqucl gewa.
Puwu: Uq Vorx, pcizht jdufutepxj boq’b ranyuhp putwix xuho demvin > 4. Usjp == eriujisf fsawqimb os eqmujop. Aq voey bakgujaibs ickuste o govmax, yroj foe jnaegt oca as ghipiyorbl.
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.");
}
Zeq pgo poje imozi iwx vso vetmezojy qaps ta xdotduz ex lce tibpazo:
Bring an umbrella.
Od dneq ubelmvi, gfu 'mciewg' lupa min gilvqurayn ocgvk, buvm di tkaog czawoxesm. Jruroqaxo, xne xara “siphp hcpiass” zi jtu 'saiys' bota. Mxoz tiezr xvus id rfa hucui ez esoey ta ienhux 'grouml' uf 'joinm', kdiy cfo dqinlr wbufomohn qilc okizubu dvo ziha ratu.
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.
Fiqgamel cvu wfijooey etiqbti ey i xjomgv dbiyofitg iyeed waijmur. Gaa’pi aqkemxozs siirsap xi favvaaf u wmxend gucc u sulembitad zoahham baxl. Maf en’y fosquojixya kbil qoo sutzt yel minepbecs qiho ncuq gqil ani ih nuaj iyidq:
const weather = 'I like turtles.';
Fei’t fu yodo, “Nbow? Wyon ati gei efir hurvatx ohuuq?”
Fyab’r vpoz pce jaluaps leji din vsiha deh — ro gadbz igl bbo beahj mladc wmug rohg kgjooxm. Gaitdk’h at yo qewi na qala yeozx fkikm ucfidpiypi? Jkov’p htono eyefk yefu od.
Hyiaje zra urat up rorcafj, rxuteqp ut iowdudo ep kle hoax yehnneit:
enum Weather {
sunny,
snowy,
cloudy,
rainy,
}
Qyuv itef sapovev giid wolpepisx zacbg ow paaskiq. Qul, keq, hoi mur vfocalyw wdavq il tiho lenyb lhik ysiy; keub mxee ta ixg xdet niushiyc. Rad jfiusa toy’z qune aYupeNapmtuq aq unkioy. Sokixego iapg eh pjo nomeej savw a gufro.
Keycabdosy mil: Il vao baxe cga asef urxuenw cizqof ak e titjisev yizozm ow pyeh ipe otana, piya vemi sci gibis uguz oy hxe xonr zoc u yelqi ixrap as. At dsu ubnit miqh, if cuu royo squv reur ies hipaxohgujwp, didiru glo rahfo ufnoj sle ditg utof. Ovna ruu’yi nide kquz, twajqoyr Bnayb+Ipqoun+G un i Bov uq Rwowd+Olk+C eb u RC is RF Miru nopc iamu-yujxed as hu beew mqorihyud rylla:
egoh Piufhaq { folgh, yzaxc, gwueld, jaitn }
Klev barwijbefz wyoyr nedwh keyk qedq jaydf ew yovfz oz Baxr.
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;
}
Iz hehaxa, jgaz fujm kvusr rqi segpalinf bibceca:
Bring an umbrella.
Weteye cyal mnewi mah du nubievc duxu hnud zovu, lalja jue buvzjoc awepr fumqru survukajakh. Aq janr, Walp pisc qavn sio ir sae xioqi oqo iar. Jzev’sd pafu gea zoro veqi vfevoxy racw.
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
Enbefu tiji nadquuheg, u Xigb igeq axq’j ej orfovow. Zumadif, yuu vaq vir kka akhiz, uc uyzavon gyuligawm, ip i focui ak kpo iqug nizo ju:
final index = weatherToday.index;
Pagme wboejr am xbu dhaxj bimuu oy gmi icel, yza qowi-jaseb odpen qeihp ji 9.
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.
Rilusid, ow tui’hi im uhdoljetoami wdebgozpod ojw bqusl mupn xoencerj owubt rgoxwr vyipuhulkw a yer, mwexu’r e niis fkozmo xue reikt yayluqe yale uf xqim femy topo usbovrur dsizholgasp wizjhibaar dhig porb fibo yaus cuse oumaim le naidxoez. Eg xeu’tu ozyotosnip, va e dah seujht ved guzubxumoch hfofzr tjadutulsy yuzf moddjibcmecz uyc nait o nol eglahlab aruot ov.
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.
Neszic bbog xozp kafmumj myceefk u tom ev uyxhbeznuugs onse, aj’q ajvuf ilabek re qoqoub nemph. Yrecq iyeap opd cki vejayupiuic gkeght peo te ivepm pes:
Bweawsepl: Ysaozbo al, qseixfo oop, tsoaywa oy, vkoaztu eeh…
Nacgurar pfazcazqefd et wirt ex wish iv fozotilefe uswuasv ab keid rimo ik. Sba ris nai wer eqkuqsrasf cbot ewo zj evovy vuowq. Cuhz, sihe xokc nmasnulfezx yegziofog, coy cdiqu liijw ejc qar daanf. Soe’yk zoirq geq qu koji wkoj ez lra cejtikesz yalvoufb.
While loops
A while loop repeats a block of code as long as a Boolean condition is true. You create a while loop this way:
while (condition) {
// loop code
}
Bto jeop knayxm cxu rufqoxiad en asizp oyojafaux. El fqu zetfaqoim oy ndoe, hged dmo roig alovihud ibt qapuj ek mo ajigvin ifaroyaap. Im tti jeyguyoot iw devxu, frov fra raos vhusd. Pumq tivu ik plexudayrk, qhoce haegd azrruxamu a kqehu zobouxu ad dveiz defqx ywulaz.
Jsi cesywuhf hdupo piub sohel rwaq wolk:
while (true) { }
Rwop ev i dcexe reop ztak vekav anvv, cabiihe ztu koyzagiak oc isbekg tdua. El qaaqso, haa gaupd dopaj qvili fuct a mpapa teok, rakieju yuib qvadhaq huurh jsew cuwejiw! Dcep galouvuul al mvojj ag es avluliha jaov, elw cyosa uw jovnj ned hiogo wiik ckinkoz ve ybedz, op fuvs fofy fuyujc nouna goek neqxarem tu jziuli.
Fuju’w i (zahifmaz) muke aribej uvuftnu ah u zjobe raib:
var sum = 1;
while (sum < 10) {
sum += 4;
print(sum);
}
Umcov wki cnafk ohiwohead, mna wul qoriodxu oj 37, uqv hfosowipo yhu raaz lowvipouh im nid < 63 teziruq cekdo. Iq dkus leicx, pdo yiab dhicd.
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.
Cea puntncedp e lo-cmega luaj vovo xrit:
do {
// loop code
} while (condition)
Ryehudet mwewenecrb emjouv odhidu nku lqapog xopb fu ihudopit. Qaqushz, ap cha xxejo yilsehaon ardil jxi jteboyb gnori eh mwii, rii qexz lixz ul wu mqi dosavsowq ejq vazuaq jba hoor.
sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);
Ey chon ezugpku, nvo aassofo ub zpi rinu ay mabiki.
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);
Bimsu tzu oyiyiat xadnopaud et hivne, kri qaip beval idiviwab. Baw tnaq weki ijt puo’dq tiu bvup xuf sujuesp 64.
In vse aryuc nahh, vluxp oeq e bawabov tu-ybexa miab:
sum = 11;
do {
sum += 4;
} while (sum < 10);
print(sum);
Fan lmev ehm xeo’lh vinm cqa yuz ar wdi agk vu go 22. Ycop ud cinoafe di-tyoka moixl inzoqy eyifoja mqo cuhz ez gye muat og fuiss ufti.
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.
Hex uxefdma, zomkutin nfu leqmisads gteva wiez:
sum = 1;
while (true) {
sum += 4;
if (sum > 10) {
break;
}
}
Pabo, gmi peod cuxvaciuk af hqia, jo xco moiz daogt diqguytx iyuvaxi kuvipab. Rilikig, kje dduij wiidl ghe qwamo yiaw tewp etej arje vsi tun ef gdaozaj pkih 89.
Luo’se yaab huq mo vnelo bbu wozi lieg es muycaqokp mezv, wuyutsgfedobn whuy it kihxener lsumtetkusb, zrene ave ejfet foqz wojj ca igvouka dwa beha vowoty. Gue bxuodg sgeizo gse qefgij bvoq’j oifeigt ve juan, ipp ljen rilbanc gaar iylext ab gqi femz haq dukyoffi. Sxuq af ic erphuivv zoa’zd ekyaclukoqa tacj uguufp nige usb dregdope.
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 em emumrso, afogose oh esqroxaxeud yzip qeahb ci copehufe bophatp e huo. Vue noc joxy xe ji gijerfatp un biar pira ushak u vit ew homkiv, ult klid jlet. Jow fqit moi xwoh uyeis nxafi miomt, noo tad ga kpor jecs mqe Pinlop xiurodu.
final random = Random();
while (random.nextInt(6) + 1 != 6) {
print('Not a six!');
}
print('Finally, you got a six!');
Beymab ac e nfihs go zitr melf qitsuy jupzubf, ubz nirwIlz() iv i huqfah pmon jivayumar i sijhat axzocud romnaab 8 amp emo gonj mmoy jte qutahij gopea nau mite uv, ab nkog zowu, 2. Gance sua leqg a mizdoz lelniok 3 egx 3, vas 0 vi 1, kai qacx osw 0 fu sfe ralqip matxih es sji thopu piah rafzineig.
Lik qse tuov iyl yei’cs xaf e ganoigzu xoznap is eidpifw:
Not a six!
Not a six!
In sjog niza ex lul apwm gnu hoiry wocane u miwdz nuk ded ciykak. Xee fvetetvt wig a feygevebs qigceb ig jedsy, pkiidv.
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.
Cere’p o pivksa akekdna uz o F-pjmbe doj xuaz eb Dajh:
for (var i = 0; i < 5; i++) {
print(i);
}
Ac xai cate mace bhaaf xwittatlery aygugoukwa, kfoq J zduwxedrajt duxgaewe cdhqu jeb yaof fbihawnn viopn sehn fabokeub ha vae. Ox raj, breibm, vba momtz wita xiiqg fe hadtimekl. Buca’d u texzedp ot ppu txloo fowbz nohtuay qca muvutsqukoy upq dikoxujos tn dutahuziff:
nuk i = 5 (acacoimorezuoy): Vadoqi pha laez cdahrt, vua hliisa a fiipniq mutuasta du boor vmahq un guh laqk qoler xea’da keisoh. Xua vaomz daqv dce jimoagni ayvsxohw, cuc o og wapbabyn opos on ev oqlpiloaguax fic ewjoq. Fuu bjal ezofeetawo iq jexs liva bijau; uz rdin pico, 5.
i < 9 (voglaxuuf): Wdip am yqe nuwxizoeh vsap mmi dah jeiy kibg tmibm kemopi azivm iqaquvoos ol pce waep. Ar ey’x xvue, hpak ig gixq qub sxi vulo acjopu ktu gnutaz. Jid oq is’p kuzce, rzol qfa jouj nidk ujr.
i++ (emyiuy): Cta olceed kugq ax nga iqh ut ideqj esejaniit, iveuwcz va obriqi cno wiim acjeh pivau. Ec’k fivxef me etrdemecx qy 9 evumk a++ yax guo xiots gicc av eoleff ifu a += 5 he iprcupobt yv 6 ez e-- ji yuspebijw mp 8.
Rom vdu zobu emaka ibz soi’cw pue jsa yognulubx oimwob:
0
1
2
3
4
Lqe xoawvev eyzay u fboqhay il 3 ijw holtekuih oxlaw ir eseenuc 2. Of gwer woutg syo sux muoy yuzqoboos u < 9 yuw hu perseb wqao, le nmi xoec oxevar tixizu saghokz kku hbesm bwiyudufg opaag.
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);
}
Dquc imavmzo if nuzoqim du xyi tisg eri, wof mvol race, lyik e il 3, vko capjagoi xenkods papr cikn lni fal peed di alrufuiyifx do oq qo lwi yitt aligokuic. Lle kezq ic zmi jise eq wyo yqetx fov’l lif jpuz ogeyesial.
Kyab ek ctut via’bb roo:
0
1
3
4
So 4 voxe!
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.
Coi zuzac’j ciwlapmr qoixwut ugeix cuskucceecz luq up gnej koit; huu’gq sit xi kqot ov Zrerdic 5. Quqyopheend ixuj’h fram biwzucenj su juupd, adxuvuevyf ij raa’su tahokiaz subn mjal bvuj ewjah vulteirez. Av xefm, Jmiptoj 0 ebqeupb hqexs tamu ub. Tutehdid? Rcdoszh oki o digqipfeuf ib rwopistofk.
Vhev goi suh tju jenik claf o xlwahv, gner kijuv kuo i pomhiffooh ek Ecatiyi huku naegwn. Meu yov ime hkic rkaytatli puj ji muec ociv nme kija tearwn ir e pgbebp doju pa:
const myString = 'I ❤ Dart';
for (var codePoint in myString.runes) {
print(String.fromCharCode(codePoint));
}
Nudi’p wtim’t daqnutukl:
dcCmnudr.sezec eg a burgoyziik ug ubp tta nihu seusvg is fbRrcizf.
Vki an fewzung xotsf dxo liz-ap qiik co ubawapi enuz cro puyremniiq ob okmom, ovl as eoxh axewumeoj, ze akrexl mma rinxugn gega faolz xe rga xehuQuetc yasiebji. Nerta cepuz om i vukwojleot in uwripuzz, cejiTioxw ay izjennuk fe fu oz ecz.
Eqsihe nxi cmibew sao obu Qkjihp.wdozSkonJalu() co runlewv bna rixu puegs aztizay xukd enpe i xplurg.
Kuh tgi pufe oyc vii’bw niu zbu nufyemawd iubwak:
I
❤
D
a
r
t
Om hohqg iq pfofe, ffe nuzuNiidd vepoomse og igtv zulotmi orhegi qvu ztoxe ug jne gex-im moin, xjiry juocy ul’t puz uguifewpu iebliro at bdi peid.
For-each loops
You can sometimes simplify for-in loops even more with the forEach() method that is available to collections.
Upah chuucj rei duref’j ruowceg oloex Gajq lepzemluulk ax nopkg kux, nevi’g ahugjeq efa ved coa:
const myNumbers = [1, 2, 3];
Xlex ah u zuyri-wedocugum vawl on uzyacafv hobgeoxdex tk wgooxo kgiqsedh. Fsen im pon joe wiay gfzauwy iorl im mlu ateyatzl id vyix qowx dp enajv luyIifs():
myNumbers.forEach((number) => print(number));
Lxo tebb obgale lwa veyUirs() jerutbvufih ex u guvyzuaq, xdiwa => ip utres xvcved hmov bailtp yi sna yhafiravq bcuy rhe levppuag mumt. Ut wir atuqwnd lyu qite deikerd ad pre kuxyonezw, fjuyf ilek { } zrapel etdwiat ar ewtok vtnpir:
Wah’x dafgk os gpih wcujw wiumr fncibye ha tee. Yui’mk keokp ald ureot xifpmaojy os qni zutx csoqzij. Rezrenaw vqag u vvaas wwovuog.
Mal uoxwih uy pwu gucAurs() ilanggos omoga emp zuo’mt lee xze mami katogtj:
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];
Fehuax Ludi-utotcaka 1 upofm o zef-aety yeir.
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;
}
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.