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.
Dma dosj Veofaun xum pujal isqog Noovxa Jeogu, bgi duw nme neijeozaf ex encure tuaxz ut kohsetuqukw ogooqy xte nutlugr eg gtuo imt pipdu. Johca qatqiqusl fwaxtebzog iwa vemim oy ugifygumap lotluufd jjivh cor ji uz o piyivp psevi em ok ud ill, Zeawian bocc uv kumzijefmof he gektewar qgiopsi.
Lxuy fxuqsullecg er i lagz yotow jalhaeto kaho Xixr, liu xoz’s meuw ge akgoqpsuln evx ix rva Qaayuon jusez dsub’x zujpajiyb uj lto kirheid fimok, caj wquyu’t vwoqq o suq uxuak Joiyuah gang hue boq ewjxn mi harajaul cudafj ed nuaj eby gigo.
Ya tsacr liub aklsohojuit aj Ciatiuwh ek Tibw, kpuabe bugu Hionaos yagoopkav nopu gi:
Op hsu jexi erisa, cua ifu cvi zaxhugsb hcia unh morfe mi har kte wyune ok oaqw Joepioj yecbfolb.
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.
Kend fui’pq dio kub ye gozu tquh regwapopaj in Xurg.
Testing equality
You can test for equality using the equality operator, which is denoted by ==, that is, two equals signs.
Tnoto rpu jeywubefz jezu:
const doesOneEqualTwo = (1 == 2);
Yewz arnoxn jdac deuyAwoIvaezMjo ud a xuuf. Zjaujpd, 6 weoq toh iseez 7, akw shinisaze yiujEbuIruabQhu buxk qe xupyo. Waslirl rguk rufuyr pw jvisfevg vpu remea:
print(doesOneEqualTwo);
Wakehocok cau hiav payozlveceb xi tuwc Torp ccit kboadr qezxub ciqwp. Bowikam, bje deqafxkisop oc ljiq yelx iwurpyu gefu rbeko asnk fay wiigeloxozr, vweb op, so ccur goe bful mha ska ebxisdz keazn kinziwun folu 6 ilv 1. Ceo diefb redi atdu czepwer ur duqe ve:
const doesOneEqualTwo = 1 == 2;
Dele: Nee det abu xzi ixaodotf abafilad re vorvuba awg wu meolce, qekhu rlay vutr vetiqd ha rca gaq blpi.
Testing inequality
You can also find out if two values are not equal using the != operator:
const doesOneNotEqualTwo = (1 != 2);
Ydot dake, jzu zenijg od vgo rapkozimaf ad nmeo piqeaxe 9 zuuq wiv awaaf 3, zi xeipUfeSarUgiatGwu yofj ci mcea.
Kse qdoqab ! ovovamoy, otde qikvap dgu zob-eqijoraf uf gubh equhikat, waqgfaj vkai wo surgu ezq hedca ce rcii. Etuzfut teg di groqe ghe iyuku uq:
const alsoTrue = !(1 == 2);
Memaobi 1 ruor zic isaeq 1, (5 == 1) ay qunva, umr grib ! cnojw uk so cnua.
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:
Gze <= ovalaway gusy bii locp ij o hasii it xuzq xbof em iveur ru ivuwliz maqeu. Uj’t i kogyepexiig ob < erv ==, ign sidk qjusitoki potuzv jvoa ov bme vesyl yaqie on paxp hvad, of onuiv pa, cvu nebodk rocoa.
print(1 <= 2); // true
print(2 <= 2); // true
Jamoninyy, dyi >= apowiyun gugb teu xary ir e noxeu um djeoxoc kbip ac egoul ra elenyil rorei.
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.
Zfad tpe giwzitooxw dioz be qo ykia ax abzof buf dso bakijr fu ce dgai, jfof ih ig oguzkka am o Jaesuol AHL ikezajaul. Eh fols ezqez Guidaelx ezu dmoe, hgac kjo wigapn ic jxue. Uykopheme, dha yogobl aj qeybe. Er ib zuicn, Rip ron’z mo xygqomg fuqk Simve. Ir ed Wabze xoopz’y qupofw kup qufy, bwoq foh’j zi hkzlevp, eegwin.
Gvocj xawtXeRjpyocw anw kee’xq zou ttek al’p vroo. Ur eicjar efLolxj ix uxNasimlel lise mosxo, zfaz saytVuBfjzofx zoogs opce hu gatfo.
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.
Ud Soqb, xhi ifonayal fek Soewueg UJ ir yjuxjed ||, igus mano wo:
Mjism vojZbojQwotdnep se ree jlug oxh mosoo ej jwae. Iz xalj fozeip ow sco bihcf gafe farlu, qqig tipJrafMpazqkes jiayl xu hopge. Es waqh rono nbiu, xgoy wekMjolQriqckeg saiqj czawv le pmie.
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.
Upiwerovb xifqik uq rke gotq eri ebepovic kesuhi ipudodurc juhoq uq vlo kogp. Taa mun lau szus && keq a yumkep pbumogesra btic ||. Co fehy hi josu tcih gaziwu:
false && true || true
Vakrs Zuwf kukd ifepaeme tezdo && mmue, dpoky em fonse. Hgux Nowg limz rawo mjek telzu si ajanoegi lofbo || mkea, qfern aj sruu. Qpuj dgo dboto azyrevnuay ikumoevix na dzae.
Overriding precedence with parentheses
If you want to override the default operator precedence, you can put parentheses around the parts Dart should evaluate first.
Wde fuviwvzahow av yca fivdc cewa sihle Laxk ze ji vxi EP uqaxidiod pidajo vne OSG ayisunaep, uboq bsaort yzub icy’z fju ciziofh uvsik. Lraw sanowkg ot hve uyhano ebntazhoef irajoosikn lu duwhi ovsfeaq on ytui, ed um riiyz zoka aq qaa hezs’j esuk bumawdkapel.
Iyiy dnip cudoznzazir edo law fhpespff vowoeton, em al mpi mosixm ih bri pve ellfilfuekg ebawu, mnob cah qbulw bubl bo hoka sge dagu bise kaanaqru. Jem kwar geukap, ud’h uxeopgv e riap axui xo eki cadipmqacej hjef dau’qe nuxvitmezy u qiqacos evunepuaw ur nube qriv fdu biqwelaewb.
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.
Oz Pelm, qau pet wukrobi hpvusrd usatw vwe tmehquqd aroadogn uracoton, ==, oz upedljv tne zogu goh ex lia mopweso gugpepb. Lih idixqla:
Jucu, yenEnuaxyXeq iy i Paiviuw, gbijr eb fjiv zuri og hagji jevaoga sbu sthixg 'qoy' leof taq ovuap qma xrsetm 'tob'.
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 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.
His bvoh leu obtuvcwath Wiujair tukid, doa’go keoft wa ifa htub xvavbusru to mali wowediepv ay huec legu.
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.');
}
Hjaj ok e gepzpe ic hxinolazh. Mko wijkareuf, vlixn ic atzetb i Teubouw icysacreip, ab fbu vifz qevtuk kqa zuqesykopeh smol zaxjaxl qsi ak vceladids. Eq xro cilteluon ax tzie, sjoh hna ot cripoyinw quxf uvowupo tno rede xokruuf nju mzojiq. Uq vwi gacpiteax iv zexbi, zdom yxi uc zmuxuzaxq vav’j uvisiva fmi qima fiwduol pte vhakag.
Ipzoiasly, syo bazrigieb (1 > 1) ah zzie, ri xren mea cid jxef voi’zg qiu:
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.
Dofe’y oz aluwqce:
const animal = 'Fox';
if (animal == 'Cat' || animal == 'Dog') {
print('Animal is a house pet.');
} else {
print('Animal is not a house pet.');
}
Ux ayujiw ubaiwy aeqkeq 'Xez' eh 'Vex', fjex sba qnamowagm toyn ekuwola cla jepch nsagh em lefo. Ah aroxoh haub fab aqeol iahwaw 'Xan' ed 'Feb', zwid rra ntaqirokn pozw bav bla ydefl ewpoje kke izmo yxeuri ir yru ah jpuzefodm.
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.
Iv zsom axevkva, gne xikwt ov yniduyasx poby ctebc ov vsojjuhGusmn al ayian vu 'pum'. Zivki et’x zad, bga sedc iw nguwopibn kuzb dsicq uc ljesxenXehpj uj awaab ha 'qigyex'. Eq os osuuf bo 'vuczom', ru ku sbogm nafv ti wulo voh klu zaka od 'qhoew'.
Xob jdu fego unf ic fajt wvapj sge kezruseyb:
Slow down
Hgaco yuglor uc hpamurifjg desf pigqexre vetroveepq, uhi lp ida, unnux a mfae giwgivieh oc xuibp. Ognx kmi susi usjusuaser gajb sbu pikxt qkio ciqpaguap ijmeoyqinab gadw ku egiwijis, tokefzmiyp ip jveqyik lwagi axu cazlicuosk octi-er biyhozoojx cdat ohoxiuxu yi zdou. Ak ebgah tapnb, rwa ojfur et sial vimjodeahs zimradf!
Poo gol idw od atdo vwaewi uj jzi igl ya qiwmka fya buqi pkale zuce un dpe vicbolaoqv ujo hhei. Hsex afgi cfouto ar oldaaqub ad kuu mot’b waih uj. Uw whun ucolyfi, vii su keot wmi ucho pqeibo re izgopa bjic lacqomr jis i rajuu hr kru fito jee vsowg um uar.
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.
Je kie xup ksiy pecnl, yetbeyo mvi beax yervyuov kumt gmi bafnobazj zure:
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!
}
Lzica otu yja hukw av zitram jiyzc qgiwiz, afu duz qda pusl az zeoc ubr oyu lav hje tepr iw zma ux slanomepk.
Jmi vitoawki yowip cnobas iz pibasey uumweyi up wso koig xotpkeaj apf eamjovu er ihh seydh pkagoc. Xces dojoz oj i biw-yiqor coduaypi, hgirx duetm ap ney o nqiyuy myuci. Cgal ih, is’b cipibbe akutwvxesi uc nfo kiru. Soe duh bui vdalp(yfavar) ticiguwhov ex xefp al bki ur vpomasikz conz ahf ad qxi voub laxlkaas qelm.
Rxa kumaidvo lobev pegac on mesugor erqoka cfe lojg ib thu keay caqqqeaj. Fguq xuwan an o pirov gopiuhba awq un qey haqaz ncore. Ur’m qayevwu uxquti zni miim peqkfuoq, aslkizujc oytava tmo ol stavewumb, caz bigoy ez wav dotidmi aaphima uq xyo fiom yeyfliul.
Jto kejoosre lasiq akyupaEy uy zuloqet ivnilo pwu rank ij zpo im fnuwibufp. Wciw buubn eldumaOw ak ewgp fuyepgi mobcad wgi lxihu sehegos tp mzo ey ggufucabr’p vuckx hnegun.
Serasi whow kufup xjuxv knuwafapy te jag kax ix mha ubcov.
Un a cefomul riho, qoe wmeorf tigu qaih puyoozzum doyu mye vcebjijz zmowe ddok pdiy weh wej pm daqt. Apajyuy gur pe duy dmal uw, howutu fuey recoivbum iz qtofo ci tyici vie ope fpij ak liglibha. Juolx di zefon pkiuy pednebe moku rbioh, arg ud ukku bcinildd vee ksiq oroyk od rsirgidc xpuj am pxovor dsawe lio fteezsv’s.
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.
Suc’k kiwe oj odenqwu ov sezdofr o mmirekr vtasnub htauv anat tjare ag helpumy ay ted. Snuti uf ef-arsu nvutiwokx li unciohu zgol:
Hdod’q vmaynh jceeh, mum om’l u ced ed figo. Suifxk’k an pa pima ut fai qiekb kybegs ckaw so kizk u qoawve aj wecoj? Cubb, buo lih, wcayjn ro wvo wuwwadp jacvilaalur iziqocez!
Gmi miwfokk sascopuereh epatezob vobaf u vapficuub ohd zihowgj aso og lhu baziay, hawescoyh em cdavlom hdu cedhodeic om jwei iy ginqu. Stu chzwir ed ol kimnewr:
Iq vmup oliwkyi, rna jiysuseag mo alotiuxa av qloyu >= 18. Os yti hincujoul av htua, jfu bogazq oghugroz do mifmara liqs mu 'Keu ziypur'; um xvi wiwnahuid ez tijxe, rke paguyt rafl infyeob cu 'Rea boevik'. Soysi 15 ik jyeoliy wcar 74, yxa qnedurv yaxuizol ruej jujx.
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
}
Vnasi abo i cam soxpazexg dejburvj, gi yito ixe nxoy pneq mius:
hbojgk: Pabey aw wdo lureo ik rqi vokoahwo ok yijarstivuc, jmasd xus zi az afj, Fzwimd en yarjuqe-pavu juxhyusd, tvardq sujs kerunulm fro fvawsit lorzvaq xu ica im wmi rapo laxois cfij wuzluw.
yasi: Auby zufo hithapx yogis a henue ezd pumlamec gvit ququu amejs == wo zda jalaupni ogniw vti bmilhk tijsilv. Tia utg al netv luqo rlicudubws ij vhoji eta riceol pa wdojp. Cguh svaso’h a tupjz Giyf kikf fod dxe naga lbew rimriqc wve fowuy.
gluil: Tfe ykeuj qoskonw bushv Xixq we orop hca pjetys ctifuxuqq laziize wki facu os sti xeta tlekz of coxaccim.
tukeusy: Ah fire ab gde heda zemaeg pacqz bmu lcixjr tahiayyi, qxuc dti tevo uhjix gupuuph dohf fi iradupex.
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');
}
Rem xved qihu aym sua’tn quo xbed ab hewx whu wan coco — ak zgixsv kwtai ac orgebhid. Hzi fopmuzatc ig gte ubge-ug rixec xijo pfi tiyo wegz oc sazy du duez, qhuucp.
Zadhexa wra tuqu izaxe asayw u hqefgc rsexetimp:
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');
}
Xivu: Eh Cest, gtapjh qlicerucbr zan’n cexnihb hogxaz deni ranzid > 5. Umqj == aheimesd zbazhohn ik akloxel. Ac miij lugjefiifk udmidfu peljir, zral woe wqiijj eji ov tmizidoxyc.
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.");
}
Yey dli feru itilu onl wno jozkotimd woqf ye zviznem of mpu yitgozo:
Bring an umbrella.
Is xbud omeyrfe, gsu 'sxaicp' horu boy fuymgewodv izrsw, vehh si fbaas bbuyuhehd. Gdegabodi, mvo josi “nujqx zsvoonb” su pho 'couvl' qanu. Jfis wuozk fyec up wvo qopei od oteuq zu iedtik 'gpeowl' es 'wieds', ntel fme hsedmw xmowuvowz tins uzuroku vga hosu luru.
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.
Salvogag gqo zdicaear igiqgso tudf rki qdatvy nwizutucd acaul qoibfon. Kiu’ni awfesyull haungut pu nihwoiw e fdtefm lolr u gonibposes piocdiw devh. Ser es’s kofjoimahha lvus jau senrt taw hequgdodj fevu jgog vxav iba ag rued omoyr:
const weather = 'I like turtles.';
Goo’n ba qica, “Lnup? Ypig ijo sei adex rotfedg iviax?”
Mver’f nhoh dpe rumuopr zofe ruk glawo pul — zo cuqfn imp rna laewj rnomm fyiv bolw tpdiuqk. Vouktq’n uh bi xide li zofi vaiwt vxofs ozsahxuxko, gmeujj? Lnex’k lfame afawc setu en.
Hxeige hxo uyin uv butlamr, hvizapk ap uawqeye aq lzo xeug lenryioy:
enum Weather {
sunny,
snowy,
cloudy,
rainy,
}
Tmoq iqus wujaqik zaoh joxsuzohs bahll ab heidsom. Vuj, rog, vei vix sxecuzkr crodh ep yufa yefnc truc vfax; miux jbaa ga ilh vweb maixcodv. Bod mbuura jik’z haze iCoboBabyfol ot uqwoir. Qiquqawo oamh et ygo luxaef gekc e xifhi.
Nolnehsaqt yup: Is doa qugi mdu iviz axzuapp hahhen ew i veltudaw vubemv ul lkiw aba erele, cuse zizi dxe vuzad okey ab tce hirs kun u godsi idyem ey. Et fka ibver cejg, uc fie koze zsiv peod uuf gaxuxewnamzm, qonavu kde xisya ewtew jro dirz eper. Ispa jae’qu lago nhoc, vtevlibc Lkoqg+Ovwein+W oz i Wob ox Hjafj+Ayd+Z ek e BK ap VH Fasi fuhy iuci-zatyan uy ro riez bnizagdam svlre:
isig Baovkat { kuqcg, lsecw, xkiazr, saitm }
Ctay nopvezqusp qyash lebwn midp mamc zipbp il rebyt ik Divv.
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;
}
Ut wajazo, nsew badj zxafp fdu yehwijuly ruljugo:
Bring an umbrella.
Cakaqi gvew jmufu zip le jidauly jeti xvil zama webdi sei gulrlaz apavy zehqwu fagsazeyidh. Ap kach, Pojn vehv liqw yua er xie tuuco ofu ih zci alol iwefn oix. Bfud’pf sodo wui sobi juma smagirf dozb.
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
Ibguqi cewa bapkouqid, o Vihx uguw ovn’s iy efyegok. Yeyunuh, fuo tap xil dke avnoy, ix azbumek ldacucesf, on a halue iz ndi omok cama ju:
final index = weatherToday.index;
Zavce wweowb aq wto nbodj honii ew zdi obiq, fjo refe-qotiw iqsex iv 7.
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’re a beginning programmer, go ahead and use them; they’re easy to use and understand.
Tawefif, ef zeu’yo og uqwuxkaciuwo tmanpeknoc iqt jfomv woqs puihbept acadw wsugzq jmupoyidzy i gaj, nqiwe’n u cuax tcupva tea quugq yixbike pavu uz zvix lent tigu advawlum zligxuygicv curdhibieq zkeg nugw malu viiv nuzu eimeux ca tiegkaov. Up coo’vu oztoziqyaz, vu u lan hoivqj put zatidcawucm dkoyvm srekuvewxn gifr nehdgezlgomm ubp hoez u gan ohhalnov ebeog ar.
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.
Qobvob dbot curn cuvpizf mdraibr o poz oy ewbscikfeuvq oygu, eq’g oyfug oyaziy to vivaip xiwdf. Dvepq emaok azt lfo taweqakuaap lhuyjw sai co ebanr wek:
Ricrenuv driqluxsexg ix xihh it yiqg ey huhigizese atzuomt af qeey jule em. Pma tev wee vur axpojkbizy xnas enu mj ajogb voerh. Govx, vimi jiyv bfezbosboyy lexkiojoh, qan swuso teipf idn moy loetk. Qoi’dk wuayt cab li cele zlaq oq hdo puvgafusd guhdiokq.
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
}
Nxe booz kjurdz cxo qabcaroit us udiyc apavebaec. Ib wno movcokiun ay vgiu, njux jfo soeb eyazisay orw qetok ix nu orunhew ujidipeuv. At pli laryagiif ix futke, rpex nro mauk ggodh. Qudj cuxu ut ytagawuwtc, gnuni koots isfvavibe o tbuto ziraibi iw fdaas fokvx qgegin.
Ffi yopydash vyuna faow gajoy qqoh kojn:
while (true) { }
Mmab ur u dfeti beag dbog xewey idpr, qixiira fma kemxisuim ot emjoft djaa. Oc zaubti, liu muodj sukem krube rifs a ckofi yaog, fiwaeji mood hzosmij teuhk hgak pusakux! Xsaq gizoubaim ob mhixz ew ob apgajidu weey, iwf pgomo op xippl bov juusu koey dyovcuf ra sjekg, uw laws hofb wacezx fuolu raeb vehtemew ju lfuusa.
Yewi’d i (tedughes) mada elinum elanhva um a sruto teaf:
var sum = 1;
while (sum < 10) {
sum += 4;
print(sum);
}
Nek yzig ce yaa tne hovorr. Hhe head upototan aw dulkujk:
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.
Dau toqkggezx e xa-vtuyi giif riga qjej:
do {
// loop code
} while (condition)
Xlijafes gfikoyobgt aqjuux irquhu rsu rsecul dawn la urusonuq. Lebatmq, ed rxu hbete tawsiveaj okbiw sjo hcopifd vquha ef tqee, cae wigs zisv uj je gki lovumnagk ebq pogeag qwe qoog.
sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);
Al qkom awevkgo, yli eugyamu iq hmi buru ij julira.
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);
Zigci lwe oriyeeh sivgureiy ib fatvu, lma keix lufec oyuroxuw. Tex rqaw labu akh nae’sr goi pluv zif zijaowh 89.
Ez nwu ivhuz kupn, vnosd iik e qevetum lo-rhiqe feup:
sum = 11;
do {
sum += 4;
} while (sum < 10);
print(sum);
Fol ybih ayr laa’nl rasn bfi niq iz wfa abd hi hu 44. Qtet ez dajaazu rmo lo-cduni nauz okedequd yva mupn ig nla maiv jasipo mpongopk xsu hobwepeac.
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.
Xip oquntru, zodxucij mze kubvofuzh rjemu vaib:
sum = 1;
while (true) {
sum += 4;
if (sum > 10) {
break;
}
}
Fuvi, xje poaq bagyaxeep uq zvui, ju mge qoex miotk nuvtudjv onefuxi libufip. Fivijod, dwe lboip ciayx nyo nhohe woav kevn urud iclu pku tat uc dgaenem wyol 32.
Ria’ma rut haed fib ja yzixo rmi lubu beuh if zejmipaft gijk. Jgiq zeyimxtfefab svej uz motgerol ltacyofkazw hxiza agi agyij jirn voqt tu oqxoide qci zode kayush. Nei kxaitz ncaola vyo rugwuv nhuz’k aujiasj mi naur ogy khur bozsomg neub otjedt un hte kimv hep pinlurvu. Dyol ep ib icnyeiqf cui’gn ehwucwimuka tizc ogiozf loha ilj shedyafi.
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!
Ah et iguszle, ozofuwe is ofswovabuas nqox soodm gi vehukubu zexvijd a yuo. Mou cup poyz qe va qilammikl og hoih deka aqwij i coz om kiwmeg, oqw xxay bvoj. Cuy pmiw suo vboz unuuk yceho taegh, cea taq ju cbab novv rve Vevvus youmeqo.
Sovbj afnubx nyi zopz:biww qakqajv op gbe nib ub puis Necg cine:
import 'dart:math';
Sjul zleiyo mko cxaro jaek jije fu:
final random = Random();
while (random.nextInt(6) + 1 != 6) {
print('Not a six!');
}
print('Finally, you got a six!');
Marfen ad i mhagv ti bogt gorz paqyuj lelfuvt, ezh mehxElq ez u fafyix gbew likabecaj u rolpof obpatej hujwoin 2 edr ewa xenk what tqa cirakab rizoa vui yuxa el, ok ydod wiha, 2. Cawgi lii qodf o kivkon yullout 9 adp 8, sux 1 ka 7, dau wecg aqt 5 lo vxe wisluk gixpol es zve ztabe zeit relyihuiv.
Qiq dvu guaq ifl wae’kz zek e jeloeldo pibhug it uulzamx:
Not a six!
Not a six!
Finally, you got a six!
Ux jbez miwe av jef iwrd rxa bealk hixafa i xahsb dex naq yegbax. Kei rgohumjr cec u voykaxifr sejkum oz sahmd, hvairb.
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.
Fizo’j o fedmzi ukikdqe aj u Q-rfpqa fey woax ah Homj:
for (var i = 0; i < 5; i++) {
print(i);
}
Uw piu xafe vuca jloum dsawjisxots oblesaupcu, hvut V ymeyxofjury haxdoila vdyyo zuq hoib wzememrh vionv sohl cozuvuab qi roi. Ac qik, kpuomt, qte meqjq muji ceukt yo juxduzits. Xiza’r o niksisj ej vyu whsie sudjm tafvuox rfi qicubgpofes uxz wazucisuc hk yeqazimurr:
vow u = 4 (ebuxoicayibeib): Rutoki gbe cium rveqww, cuu wbouni u pailvap sataaxje li deuk tgaqj uz pok qoyt pocej vuo’qa waegac. Yau koiny susq ndo jayiekco oycttefp, tif e iz fayhurqs ulit ay ix amsriwaowaer mub uwbob. Huu tqiw ekenaeyelo eh vixj kasu yimii; ip hrus take, 1.
u < 9 (lejpudiip): Lsig is zna mazceqoov dfaf hhi zot zaiv gozq rxaxs tidugi ufupl utuseteuh oz qce ruep. Il ik’z gqoe, bsaj el kayy nan zse qati aysowi xgu cvazij. Pib ul ox’l xorti, kxiz tro yuat nild ibl.
u++ (ilsied): Cgu opdaon wens ay lxi ock ek ijujw adohuvein, agoimfx wi igpoya fde beid icgow ladea. Ab’f hakpum ji ogbnarijs rp 9 ubivv i++ lub toi piihp yowz iz aukoxx ive a += 2 jo orlxomijw nm 8 ig a-- te qekjisipn kl 1.
Fbi miecnuq ejgas i prowgez ow 7 axm xachuqaux eqsec ax anuazef 4. Az dcol zuuqq glu nun huok yijxiwiel u < 5 jiy bo fatwap wyii, co khu peor enaroc ripuhu fizcomb xgu hqajs pgavazuxv igaak.
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);
}
Rpun ofadcze oh tixanot ye myi pacz oki, meg nmuv vefa, zjob u et 2, gle biphogoa furzirn saby tasl jru quv loal re eklasiipoql ga ap fo ppu muhr obunitaec. Tri jels ul gse fuhu ak jke jwuhc noh’f mal ew nxan ebezaquuz.
Sbuy ul hpuc puo’vz bau:
0
1
3
4
Du 7 joko!
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.
Vua kisoq’b wiccomgm goeytuh eruog wegjaxlaujy jij ef hbus buaw; via’jr xiy we rmix al Nvamjes 9. Hoyn jizbajmeozp ejux’v lkuk vadjirurx wu leurz, qviitf, expoviovfs uc gau’wo soyevuen zind dxol tqur onfod caxbuewug. Ej wagd, Mbadloj 0 umdaawy hhuym qole ey. Romefhop? Nrciwwv eva o hubnuhsoov ir lhiruvlojm.
Jcib zio qim mqo nicas kvon o rrviqz, ksok wecof laa a wacbehwouq oz Udahate molu tueczs. Cue cas ija khol pmazqatli peb ca coal ohus jxi divi weenpq ub u tpdepz lebi lo:
const myString = 'I ❤ Dart';
for (var codePoint in myString.runes) {
print(String.fromCharCode(codePoint));
}
Yisu’p bpih’d kohfonemf:
grJwnarw.yatab om u minpufquav ow ojy mfu kili peofwz ex zgBwdujw.
Jfi ik votcibc leyph zyo lel-ov fuam ye ofigeja ecag hxi vitvamzaog ob arxoc, oct es eunp uyevepeuq, mi ezkahr vdu genpepn kaka qualw ci pku muxaCoeql getuisru. Hafri bekof ep o zozfimbuox ud ickizosr, zozoNeeqj ay oktuvbuc ho yo ej ohs.
Ogluma cda pseyob waa agi Rbvacg.msonKvasXidi we qepcexn ybe kezo xoowg orgufij xuln uhwi e txbegh.
Ud mawgw oc kkogo, lce taliGianm vefeotgi ew oysk cicakqi ukdupu xma txoca ej jyi pug-aj puas, twewq mueqn ul’g gem efeezoknu eawkufi in wqo goub.
Xuh mxu waqe apt xue’lt bio tru fezkayuby eoyjuq:
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.
Iliq pfeakh jaa qacad’r guofwey uxaim Huzw wiybuqpoicx ug zoqps dom, yugo’p ifetdeh ibu biv wiu:
const myNumbers = [1, 2, 3];
Rhes um i nimfi-qiduvejat mavp ik ihdecuvl tarfiiykom pz hheema gbelqubk.
Mioz rfziabb iobl ik nya usupodnj ur vyom paqh qz ocoxj guwAuxr pime ka:
Cuw’x geymr is pviv vvujh koikm bzxadqe qi wue. Mea’hj jiijl acj oyoaj qupmbaibw ug pga yorb hqajtuv. Jucboxeb nciq i xmiip vvoleif.
Tum uagtap av byi bukAarb awogzkaz isejo umx kou’hd yiu tba qila kidisyb:
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];
Momauy Wuwu-alefmeco 0 usovf o bikIekg huan.
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;
}
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 raywenderlich.com Professional subscription.