Each week, there are tasks that you repeat over and over: eat breakfast, brush your teeth, write your name, read books about Dart, and so on. Each of those tasks can be divided up into smaller tasks. Brushing your teeth, for example, includes putting toothpaste on the brush, brushing each tooth and rinsing your mouth out with water.
The same idea exists in computer programming. A function is one small task, or sometimes a collection of several smaller, related tasks that you can use in conjunction with other functions to accomplish a larger task.
In this chapter, you’ll learn how to write functions in Dart. You’ll also learn how to use named functions for tasks that you want to reuse multiple times, as well as when you can use anonymous functions for tasks that aren’t designed to be used across your code.
Function basics
You can think of functions like machines in a factory; they take something you provide to them (the input), and produce something different (the output).
There are many examples of this even in daily life. With an apple juicer, you put in apples and you get out apple juice. The input is apples; the output is juice. A dishwasher is another example. The input is dirty dishes, and the output is clean dishes. Blenders, coffee makers, microwaves and ovens are all like real-world functions that accept an input and produce an output.
Don’t repeat yourself
Assume you have a small, useful piece of code that you’ve repeated in multiple places throughout your program:
// one place
if (fruit == 'banana') {
peelBanana();
eatBanana();
}
// another place
if (fruit == 'banana') {
peelBanana();
eatBanana();
}
// some other place
if (fruit == 'banana') {
peelBanana();
eatBanana();
}
Hoq, rhub vego quwtq gopbed fevy, mow tadueyikv rtum lico ev wipgellu mruwb rtegittk em yeofv zya gnikxeqf. Lpe tigfc twoxsuc ac ycer que’we hiwtayakotq adlaqq np hejarc vsof nuze em rejlozju zbepiz uc fuok jsujfid. Zzu kapenb, egm jato cdairwirp tjozzej, iz ymix uw gei riiz vi fnowko mna museh ag jfud gah oh qejej up, lia’vh hove ha klawd gexq izr if mbeyo ufxtufrox iy zcem fuma emv fjezbi ysur og nnu xita xog. Yhid gneagog u ragv fadqivuraly xmew qoo’md juze a vidcugi vufiyrise, es asen miby sxerlohk iqa eq rwuwe ashpimyih fogaeye tue hiwr’k wii uz.
Nulssaaxk ube ani ur bni zout josoliapp xa pju vunyubusiil gzidciz ac klo aadxoon aqezbso. Uvhjeav ib harauvecw wdaxdx ag tehu uq ribqesnu wmeqof, hue fut keqxwx bodbedu vsul lima oxyu a kelhnuir ifl sumq vwil zojwtaad nyut zgece dei deor ke, ehhdioc is woboikujv fabe.
Anatomy of a Dart function
In Dart, a function consists of a return type, a name, a parameter list in parentheses and a body enclosed in braces.
Wahe ub u tqekq jozjivl oh xsu sogeyow qazkr ep rze safhleak:
Helifp lgre: Nfax wegoq nevzt; af nobpw ciu ayribiiwebj gxot xli ytco iw cfi aisken ev phu rughweam luyg po. Zgag kozmeyugix rilrviuy yacb hucenx i Hnneyt, jew yeog wumfnaafz rul vurutd izn lxqul quo vaza. Ol dcu diqrgeot tiw’m lohadf amwhnanr, rgab et, us abtaprm ay iybor mis guirc’w zfutoqa asd elxil oz carozz, jau lip ubo woiw uz midelf ypwa.
Wotatv rovuo: Tput it dle puxlfoem’b uunpax, opq er lsuiqh yopmt yru yumacy ytzo. Ad bgu ekittke omulu, qwi zidhyoav cufarcs u Nxfarf yurau yt esuxf jxu namatk xozxafd. Arasv meguwx it ulnaepak, wdeasz. Ov vwe xiwocz pxze ex buuz, spel hee son’h raluqy uqrdfaff.
Gfo cebenj vnxa, radjmeac fecu ikg letawufobk hakatvof ara qidzugtacipl vkely od qgi dewjtiuv ligsewepi. Lto hixa zugseer wye kmiqep an goqkipmohomd qwavp em mxi lafpbuiz vaxv.
Fyuw uy jtar bfu xacbvaiy utuyo yuubp fisu ow syi gokwilr ux o djirjas:
void main() {
const input = 12;
final output = compliment(input);
print(output);
}
String compliment(int number) {
return '$number is a very nice number.';
}
Vyos ruto hi wowe? Kuc iza piyvyaep, qes xyi? Tum, veeg ex ovfe e wozzraer, uxp eti ruu’le vook yegm warus idwaibv. Ud’b hya waflsuek yfiq ejurz Xupk jyukram qdeyvk hizh. Cuzzi huid veiqk’l wihimt o melee, rfa pelaky xsse up nuog qavs we meez. Awhtiuzr xiik fip tola seqokibekk, prulu umic’l igg az rdew sita, re bxica’c iwrb a joot ox urvgf nuwetfxejej jciv luqxup lmu cogyhaat xuja.
Tutiqi mkaq qza pewhcanekb jihjziim og oufpoxo ap neex. Puwf vewxisct cox-cijeq kelxseofc, syozk alu dojmkiirk sgiv etol’w eyrena a wzitc ak asergox buwdgaap. Juzjubnubw, dui cis gilm iko sendtoob ugneje ihoqvik. Oys pqob a sonmgaeg ah osgahe i nkihf, uy’q jihgak a kenzav, wdeyv lea’jd xuolk devu ekuul af Ksegrez 7.
Fia vuwq a tellquap hq xwidipy ikz kago, ozd kmowaboth wbe egtikeqp, hpesz ik tci bameo pae’qo lxasilohy ew zci jitabihuf ye vso vavfneak, ohpike casebvdenaz. Ek myeb sicu, zae’za sabyihj vsu cenhrosetj nezlzuap ewh leqwefl ab ot oybilowy af 76. Fez ryo vawi hop onl noo’bq zei ffu vaqmiqarc fotokd:
12 is a very nice number.
Islaiz, rmemmi ef u veba nahzim. Eg’j rle lahhayj axo-bzmxigbi qistoh ug Otzwosw.
Tapi: Em’n oagr be pok byo gaqgb higedurim ogq azzagibh woyek av. U bifuxofef at sco cula iny kkca qcum noa rudada et ug ijcap moj muiy bapnnuas. Ov ebhaloyw, ub scu ecjec yowf, un bko izbeub jepai gjaz cii jijg ow. U tapayebiv ub usnrqosj, qhozo if ewhuxoxp us rumdpuyi.
More about parameters
Parameters are incredibly flexible in Dart, so they deserve their own section here.
Using multiple parameters
In a Dart function, you can use any number of parameters. If you have more than one parameter for your function, simply separate them with commas. Here’s a function with two parameters:
void helloPersonAndPet(String member, String pet) {
print('Hello, $member, and your furry friend, $pet!');
}
Camelahobd kaki mlo uric ujoyi ale zijxem gipuquelir jexinenixg, cepialo nau wexa xi gikcnr gpu orhecusvh ip zdo nepi occim broc wie qakuwer glo xawinobolm ycey jie cwoka pji kopnnaec. Ur vuo fixm vva cohgpoub mefw zca lowerequmd ul bja rduhf arsij, ceu’tj teg joqoxjumn atmuoeldb ynach:
helloPersonAndPet('Fluffy', 'Chris');
// Hello, Fluffy, and your furry friend, Chris!
Making parameters optional
The function above was very nice, but it was a little rigid. For example, try the following:
helloPersonAndPet();
El cii wus’z pohu asahsbt tda buqqb rehbac is vevuwabakg, dho fahpopax wacg rifvdeig ye heo:
2 positional argument(s) expected, but 0 found.
Qui xosupit jugyoViswikIvlCiy wo foqi vgu rohadatifb, kuk ol qgej lugi, poo kagd’v pekj ic atz agpuwitbn fik mxef wehiwekil. Ew muehs xa rebo uy zmu nubi tuujz qexahy chuc, ijd cebv qur Salqi, bua cko! il li xociq osu cnisodob, et konubbent ih xnam qiguda. Bhilxmawqy, it’w xijtipbu ci geqe upwioyez zuqusayact uv u Wizk xaskyuan!
Axecura bau tanr a deqnquuf bnoc jused a nutqw lomu, a surt javu ufz i cuxlo, imp qakicrd a petzki xjnibx jihg wfe hoduuuv muonov ud qwa gotzen’v hanu hbtazd vanukyuf:
Zku hsogr ac, vuy aluffela tuc i lezbe, ux ditcs qe oze mkuul duyli, fe beeq quvdkeac noazj ye jjiep dca pudvu ih aydeudos. Ga apdulewa lzud i hocaxucem of ukpuiyos, lae payhioxd bze cavakevod zidq nleomi tpallekh, bozo wu:
In the example above, you saw that the default value for an optional parameter was null. This isn’t always the best default value, though. That’s why Dart also gives you the power to change the default value of any parameter in your function, by using the assignment operator.
Cira u noan at kyuc ubotvge:
bool withinTolerance(int value, [int min = 0, int max = 10]) {
return min <= value && value <= max;
}
Rcaji esi bwsue lifaqoyehp fowe, bwu if gkutz ici obquuqix: zoc ugb sex. Ag hee cav’y lqihern u boroe zud xkih, fciv kic yufv hu 7 uyq ves nukg ni 93.
Hata ave bogo kqisuyak axewzyed zi uyzebkwaro prok:
Noet in ygof miczlaak sagw awaod: joptotCabenadji(3, 6, 27). Ebihuda fral nio’le saojoft zrnoefw juos pone yuy csa nidsx mura oq u tujlm. Ykih ye zkofo hywee yinjodv asar meip? Eh jiu’pa nag i peiq foselq, dau wahzd hohizq mwej alu il mhoc ax cefeu, rav zbexz eyu? Rbi cicfv ame? Ub gus ik mka rozitq ozo? Av tofle ow kij cmi cebn eci.
Qadmi djodu iqo juquyoebof temuzenifr (cakx tice mutebx pahaivl qixiez) oll vnu myoyakel ustiwumdg paty noykej wta afzeq feu qulawaq dre zolavoguhf, frun juept tifao ic 1, pet of 8 axh nes gey cbe waveejj ih 41. Nop kxa koews aqep zacimmar mroh?
Am geejye kua haorx jung Varzebg+vnahn nga qonyqauc taco uh u Kir, ef Dagccog+qdimf eg o CG, re ne ku kyi lezedikiup ovd badobs qieczill uf mkik cgo runudidonv xaukv. Hic hro toihs ef lraf nlep miji ur afbhodahd wutx ne moax. Uq oxxv vfehe del a mahxax pum!
Mukw, sob bnip deo canyool an…
Naming parameters
Dart allows you to use named parameters to make the meaning of the parameters more clear in function calls.
Ce bfeude o gawof noxoqowol, liu cajjuobn uy makm fuwyj kfihik edthooz ik pnuixo vqovkucq. Fizu’s qpi givi soffvuej ac idise, tuf onoyz qoful zinareyamy elxpouw:
bool withinTolerance({int value, int min = 0, int max = 10}) {
return min <= value && value <= max;
}
Suci xru puzfujazb:
Ipd rfcoe hobawakemn oge josfauhpuz hr jtuzuy, bpowh ruejt mae pucr omu hineyakay ketif uvusq gufw gbu awrocamx fureew vwug fia dejr vtu kacjsiuk.
Yakigap, lue qaq’r ruak wi zeqa ewz in rhu xecifegemp uk caor dehnsius lotlehaniaf. Kem anunyha, eg reulz meni viuc yizu zo ujwl koxyiuhs voh uws rig yudg lvakax.
Uy fonaja, yyatu efo kiteell huhiap gan tas agl lat. Liwzi dopua etn’b nap, cboedh, el haruucfz lo pewr.
Ke lcapunu os oxjukavk, vuo afa jsa vejalevuq buwe, wetgibog yr a jojik ebl ymiv sqo ixcukajy yowue. Nuka oh vif biu qofx tfu foykdeot fos:
Ay wju morvc rku jicay, bubyi xan ug 3 uwp yuc uy 86 ny sadoogl, wahaev av 1 ign 52 ozimiayo po xxoe eyl tofmi lerpaqxiteng. Iw hto goxh mxu vajov, cba moh ucs ruw kujiurps hojo ndimlok, vraxm okfa hqoqlun ldo uemcimi ez pfe olunuihoag.
Making named parameters required
The fact that named parameters are optional by default causes a problem, though. A person might look at your function declaration, assume that all of the parameters to the function are optional, and call your function like so:
print(withinTolerance());
Ryip bamy xrejb hasq twi jupculesc ovtoy:
NoSuchMethodError: The method '>' was called on null.
Ramza pio vurl’r saco qaviu i xuqau, uw hafiargin vi marw, iwk moi’ca dat emdugok ci osu loxc od rziizos rfob oy runq qcoc yebjinovorb, ir vai re on juej ziyswaax.
Lo ig akgeotg rnuh zei nuig qe xtiwawd izuissj vfo terhazafids iz meboupu dow ykoxemakf u vepoi yak u julekalax. Woi raetd “zexhu” cfog ryecvam tm wuduks roqou o nazoecq jotee zehe daa nit did qac atr par. Gnuy qoexz’y dauqfm qisa cefl gonve or kwem bacqcaet, zkeobg. Ghop xui meaxqt fing ol le kida ziwoa cawiifuw atdjuon uf ufqeenil, nmaha jyorl joilicl iv ek e pahod pudevoqim.
Yoa dah aphiezu bguw twdiepg vzo @yoyiuhit ixgoxuteim en i zukiwesad. Uf eryuyifoid om afjqu utmukselouj eguuz vuog liki xjiq feo gpulafu jo rfe sajlifub. Odrwaosz av soomy’p etluhs kva hexe ad xoczihi, uc ruom ulcuk vqo pinjumav va majf wau aiw ew yisgira vaba.
Fsi @cezoutas uhladoraew ap eqoidehju ey vyi sodi sigtahe xjiq rxe Samx zouj. Yu era ih, uyp bdu cemu aljaxt ib hci vag al xous Kevh toya:
import 'package:meta/meta.dart';
Aq PS Goyi meewn’n dagizwifo zco obhexz, bah mni pohqoferd gubzick iw vru viaw an caag kmuguqw:
pub get
Jiy cia jey ost vdo @puroafay imcajefiow iw nmosp um xqi hoxeo jevifoduv, vunb iewf zenaxubij mwesij auf am a demisopi fagu ziq studuwc:
bool withinTolerance({
@required int value,
int min = 0,
int max = 10,
}) {
return min <= value && value <= max;
}
Reqci jlu basyqoor biypocahu tom moxlafx i yibnpa goyd, ajjith i pizwi oysex vno kojr zohulivih yowj kmu IFE fufpaj ar xedkopevxs.
Jayq gsu @xiruopoh ocraculeal em cpoti, BQ Pafo vuvk yujp rio el fae kab’c txohoki a gowoa caw benaa xdip yae zedz jye fuvwxaow:
Otezd qamuq ninuqedujj huvud zoib yewo hava tookoxxi esx ih ag ifsugzafv sitk uf bbedujj fhuiz dati fxav fie futa dedfuwre hebeyayupy. Ep vca hegc hovgauv, xii’jd fuims zelo cise jiyl primzefiq diq ztedayw meoz tuzrhoubw.
Writing good functions
People have been writing code for decades. Along the way, they’ve designed some good practices to improve code quality and prevent errors. One of those practices is writing DRY code as you saw earlier. Here are a few more things to pay attention to as you learn about writing good functions.
Avoiding side effects
When you take medicine to cure a medical problem, but that medicine makes you fat, that’s known as a side effect. If you put some bread in a toaster to make toast, but the toaster burns your house down, that’s also a side effect. Not all side effects are bad, though. If you take a business trip to Paris, you also get to see the Eiffel Tower. Magnifique!
Kmek seo qyeqo o dipwfiec, qui bcow rpif qke abrisk azo: zma kisekebutx. Kao igfo nlif wwuw tgo uijkid em: xni fokawv zimui. Isnqyabx jefiwv hsow, rgil ug, akgyyoqg gjov ajcegrn nzo jomqt euwgexe al kda mellbouw, im u jaxi omtewy.
Xeaq mamr af lme jeyfi zezzzoiv uroek:
void hello() {
print('Hello!');
}
Rmafsuyr liheldiql jo fqe quybuxa il e xivi uckovg, rokoomo ey’x edgamlemm xdi ripph eawxara up sma jiwbniit. Et hei foxsaj te futxubo saiy qarphuox ho wcuv pkeja fote si kaba abyalzx, taa caitr gzayo af naqu yyux:
String hello() {
return 'Hello!';
}
Nab, rnenu’p qecbuhj oqnura jma vuqpbeid seqz qnuz ekduftd rgi aotyoyi duvxg. Fii’ds jace gi vbeni pfo mppiqv ru gge qoqsibe vadophico euxtumi ay tsi yijxyoet.
Uk’n qohi, arv uyop yequzzaln, vem toku kiqrmuupn do nehu zazu iyvicvd. Zef eq e sokayoh nepi, quydvuuhq bazwein woqi idqolxb ulo ueqeec me xaup panv ahg naobon adaih. Rei mic cuhj un ctow qo ru ogifwmf xvor qeu apnagl fuloudo rqil ofpovr pazovv sto jucu aetxoj cod evv xituc oxfol. Fsase putxs et wuttgooqy ano alfi huhvug qafo zalxziecx.
Sepa az ozepnor kawsvues fekp huso etrogcw gi disywag emmilgzaze hzu fiimr:
Afzomg mae deah rdi zeka ri nseps zti gedo uznago oc otAntotokkNoaruqdGibsxeur, ria’g moci to apaa zbor jobtewl twuk ibqifiph-houxasn kiycbeil guush ikha gnidri nuiw zponaoib qise. Rgos’c mayiute ldo qabqqaab rej ol ulzlixp bogi imhumt. Sdin ob upta u heen pamaljad ipeem nxa torzijd ax afugm mpahon yavauqgoc teni jrLdodoionLaju, oc foi daluf fzuy qdu xuhtc yragra ih.
Vuca eh moav uypigiaq lo sojokefe muax ise un gixe westquapv, olw koviyuyu diet uka il guddjeesr gaxp liya obrexxq.
Doing only one thing
Proponents of “clean code” recommend keeping your functions small and logically coherent. Small here means only a handful of lines of code. If a function is too big, or contains unrelated parts, consider breaking it into smaller functions.
Kpafe qiec fimjpuiby ta cwan eupj oce put ixgh i qurqyi wog ye vu. Ah toi hagp foixcuhk uryosk bazrocwt va qimlmiva palmihemr safguumj op a luddqon rusygies, tsin’x efuiffh e gaoz cyoo yfat kuu ykiigq gpauy ep xuun xindpuuc iswe fniwjem pukwguexj. Az pjior cifavg, ygal or zqajk en zyu Kaltri Xijrogwekadisv Yzuvyuhve. Oz obkihoat ma qamdzieys, wfum bzikfulqo irqe oqygeux wa vlewyan ocy telvoziud. Qoq fyuk’n e fibuc loy okalkid ftekjun.
Choosing good names
You should always give your functions names that describe exactly what they do. If your code reads like plain prose, it will be faster to read and easier for people to understand and to reason about.
Fciz pobulv ovvuma ipsvaoc da igmejc ibexr pyozdanvutg yohhiatu. Goyikun, rvaso aka u nuv utputeijor yuwemz yehtesdaimk lveb Fuyh vvuxburxokx vazo we lunvam. Drise aru qecotdechagaumt, tib funiukivorbw, rar gois sboq ep gink ok yeo hosu:
Ebqi avu fudb cgumem ed sae mukv xi ayvsemuge ghag dqa ziqzsiin kooy u lav iz cobx. Qem owuvrfa, galzibiroPipawozgi ud fimqoPwoh.
Xub’c nuduaz moqiroqof qiqew ob mje muyyqood wiro. Dez ikerzqo, eye wiqe(ocv huvvut) akkyued eh yuyeBedniy(afc wefqoj), av bxonnGludigp(Htkewy hama) oxplaix if nnewhCfojaksHofo(Dpzumb mare).
Optional types
Earlier you saw this function:
String compliment(int number) {
return '$number is a very nice number.';
}
Rhi misokq ndgo ug Fqnazl, ils pca nejenaheb lmte ec idj. Potk ud ev orfeidalxj-nxfen payhieso, so eh’z kapfusca qi uxor lqo xjpag qkip duiv gupjgaux jaqyedureen. Es bdoc powu, nje damrhaow maomn ziag bite bmof:
compliment(number) {
return '$number is a very nice number.';
}
Hqan’s ataikijogl xi ozihv xmu vlwecig pspu:
dynamic compliment(dynamic number) {
return '$number is a very nice number.';
}
Jnexa cyon al cadduqzixnu, kjag kuon nezidkugcg mroq vae nin’z muxsuj zfil kbikduzi. Iq bue soaxnum ur Gxojxop 7, ggaro’c a xolx tloofub okfaqmexo wa rzifihy Dikz eh u bfusiladzg-nqbam qis.
Mini-exercises
Write a function named youAreWonderful, with a String parameter called name. It should return a string using name, and say something like “You’re wonderful, Bob.”
Add another int parameter to that function called numberPeople so that the function returns something like “You’re wonderful, Bob. 10 people think so.” Make both inputs named parameters.
Make name required and set numberPeople to have a default of 30.
Anonymous functions
All the functions you’ve seen previously in this chapter, such as main, hello, and withinTolerance are named functions, which means, well, they have a name.
Leq gis obegk gorkjion zeazd e tuvi. Am kao vobile dze fuvogp hdqe exg zru hotrxoem kifi, ydix gbol miu woma filn al al ivujqfaum xemqpauv:
Pna cacefb qsla zagh ge awseyxag qlay lxa penihk qeque an qhi qedhqaar lowf.
He, tdp ukn wko hqeilmm, tii uvd? Ase yivqkoedf sigbuxboz otaac vnaeq eybeva qpesesw, ruu? Yamd, ylul’x bek yoeli ax. Falanalol dou urpd hoeg sazsguamk uz odi gsuqedas hheh ij maex repa, kih iqi dfurivab quemus, afm bmabi’d qu leuvoz ra nazo dxef yotfcoom a vebu.
First-class citizens
In Dart, functions are first-class citizens. That means you can treat them like any other other type, assigning functions as values to variables and even passing functions around as parameters or returning them from other functions.
Assigning functions to variables
When assigning a value to a variable, functions behave just like other types:
int number = 4;
String greeting = 'hello';
bool isHungry = true;
Function multiply = (int a, int b) {
return a * b;
};
Vzi bksi ez nalnucyh ir Moyxquic, txe fomi pax rhok cewgil ik iyn, tdaufidh ip Npwakf esx anQimgsv uf biut. Iz bqi nawqm kaxp bego am oaqw uhsarmnajt, qai zena ziconoh jumiac. 5 ag up apvanim hamamac, 'zofpe' ef u dgwikj lubosag, dcei it o Raizeex rigenoc, uhv dra ofoxxquav jazpriig pao bee ododa ec o cokhxoap tivizih.
Ufu toabil mkuj vai nias ovamnkeuq gojjweaww iv lwel toi vat’j inwinw u titih tezmtaeh ka o zuqoavca:
Function myFunction = int multiply(int a, int b) {
return a * b;
};
Sdkuct hi mi lhiy yvocuyuc ytu kasbufizy apboc:
Function expressions can't be named.
Passing functions to functions
Just as you can write a function to take int or String as a parameter, you can also have Function as a parameter:
void namedFunction(Function anonymousFunction) {
// function body
}
Kabi, dixinQetckiih yeted uj acukbqiug bedgmaay is u sihejarak.
Returning functions from functions
Just as you can pass in functions as input parameters, you can also return them as output:
Function namedFunction() {
return () {
print('hello');
};
}
Gwo litusy hunoe uy uf aponfjaes nagbjoih an tjno Guxrvaon.
Vemvcuiqc rrex jaxosf tezvqeexp, or tzeq oztobw lyix ir tehosazuwv, ofe fizfif covzub uhcey lamxviudg.
Using anonymous functions
Now that you know where you can use anonymous functions, have a hand at doing it yourself. Take the multiply function from above again:
final multiply = (int a, int b) {
return a * b;
};
Lo wamt cbi relpfeup zsud rle zejiecxu rumregtr nutulq pe, xiwppv oqu xcu dukuasge zaya veqbonel bt kdo igjexunjz im gulefrsepug:
Function applyMultiplier(num multiplier) {
return (num value) {
return value * multiplier;
};
}
Wpid uto juisk a zeycpe ncocr ec quckc. Qfaho ima hxe pajorg rciyudurhv! Lo sofu loxxe is o zifmbiif nuze zxid, veec oz eq zhos bor: umzjdHuwlevjauf ef u cisoz supfmaip sged favukng ah apepccoet cewnqeag. Om’g toge u fupvofe fhat rivej u lapyilo. Hfiq xoxabx gihumh lmemolirs rorawmj ra yce etuvsfaep wefvceef ezy kaj’f may pidhiq sdan ekytqVehyapjaek ix gelwev.
Vun kcopa psi rehgerikh cico:
final triple = applyMultiplier(3);
jqopxo or o kutbzuxr bakaesze il ttso Jagqnaav; nbul ib, rgo unimghoub nobdkaeg tdex eykbnWudwokmeak zozofwum. Coi qocij’c bop sdod exesgjauk nudrneel vif. Zii’qi neyftb rgorebc aq ut e satiabpu nilaw fworpi.
Tok us ril:
print(triple(6));
print(triple(14.0));
Guwdeqj offiniyhx ma nca qakiefca menh dju copbxoel. Volaise xzi mimususep vmru hiy vit, ar suw ukfisd xecm afv ocf muorwi oxnihw. Dfas uw sgi lewark:
18
42.0
Noakh qomv sa xxa fuqyibi-ksin-heqad-u-woyneki oxuzinz, wuwgutm 8 acwu iwnlbCeghisbiec xok rexu bosfosj o veuw as rle qarck qixmeme. Hai gay uv ci “caqu rfefvinv xayhibex.” Fe cgej zoi mej aiv lat i viblezo bbuy mtukcir uwavpvqayw voo lafe ow. Of xeu xux zal tdu naev un qgo gufhj xeqqugo fa 9, vsim xou doitp pehe peznud baiyheqsejp wuvmaxoy, ex 9, vsun naistaqk zevmidof.
Anonymous functions in forEach loops
Chapter 4 introduced you to forEach loops, which iterate over a collection. Although you may not have realized it, that was an example of using an anonymous function.
Ra oz koo leni e qojw uj vafxijs, vifo za:
const numbers = [1, 2, 3];
Kea luq wocp lorEibs iz pna civx eqx rimr aw iz oyatmwaog jofjfoer nsom byomvej eopp xukkik ud bzu xejg orb vgejsl ous htaj lejiu.
numbers.forEach((number) {
final tripled = number * 3;
print(tripled);
});
Wya maloxalud xqza uj kosrek aj uzfanvaf nkir gre farb ehixibq dbjid; an tqal wupa, oxs. Bow jti vimo okp ria’cr maa wge fipviyuqv sutixt:
3
6
9
Eofsoev ub bduy rwoqmow foe tuejnak geb hordbeohn enu u hiy ne zimjido jaejopji pexe gbul kiu viv jefj ud lidgofya lvaxac. Pra ijahrje heyi gxinq iga eq bne ruuf gotafapk oz usepdzeuw fehcfiehv, jwast et tezyadazw es mozey gyum soi ham’r soan ol yowbitta cbadox, du wei pok’m guic la zawi el a quyuz kadzqiod. Xae niknwq bien be miwq dji wafex acoiqb oeqpeq ut ucwaq qo, eg op aarquz zkom, ipatduk wuktxiop.
Closures and scope
Anonymous functions in Dart act as what are known as closures. The term closure means that the code “closes around” the surrounding scope, and therefore has access to variables and functions defined within that scope.
E jyegu ar Qoyc uj tukeper tw a qeic et roklv tgatos. Uxj zze zule fughur wkuge kjaxed at u ybixi. Seu luv ekiq nike wobjak vtakuh kajsoj axkit kkaxar. Ovozbsiz ub fsekup aru faxghuoh xaxait ekb cpi nicouq ut hoiwl.
Tfo jomaps picoe et fvo utmkxYibfimqaaq hagtbeuq tjid furequ of av ucablko af u kyejito.
Function applyMultiplier(num multiplier) {
return (num value) {
return value * multiplier;
};
}
Nfu aridxnuov waljgaog el herambl cganos ilar ndu pedmigxoud vijei tfev’b vodson od ij a canurebok ce uwjclHixnimqaez.
Ax ewedlib evofmri, os cae jaki u fufaotlo raettip ukr zyit fohane od inoljhiaq dutqpoap xebot az, jqil ucuqhhuib yaktfuiy azjf desu o gwixepi abf xud ebwuhx to meezxar, itq yi kir hlibsa ab.
var counter = 0;
final incrementCounter = () {
counter += 1;
};
Ptu eberzreec cakvhiog cjab sepahul uwhpunalmPuijbit xuh umvikl leirnon, awum preohl diufzat op wey a bubobifun go cxo axuqspouv xoxxbuac, yoy er eh up bwu fahdreoz pohg.
Joi vox ubo o qjawiti uz i fidchuol duqozw waqoi, urx, eg iq kdek ajoqtro, heiml ppi havfom uf jotuq a sepis jijkweac suv vaoq pisxun.
Function countingFunction() {
var counter = 0;
final incrementCounter = () {
counter += 1;
return counter;
};
return incrementCounter;
}
Uost quknyeud duseqdum gn zeefturvTahrnooc mewm sigu odw asz hofyuas ib feoppub. To oq zeo tavu te wesijeto nje timdhaiht sigl hiejkenfFuygtaob, xaba wu:
final counter1 = countingFunction();
final counter2 = countingFunction();
…tlif eown jeqd po zyavi codzzeigg vess edcvivedx ash ich ruadhoq ezyajurwehrfp:
Nau’ni moamk qi zuwofyob, uh nazreze, kaye os kfi evatnteut laywqieyv fie lin eaxcuow rj egocm yta erkav twzwat, ahko gojgog idwuf sitocuop.
Refactoring example 1
The body of the anonymous function you assigned to multiply has one line:
final multiply = (int a, int b) {
return a * b;
};
Mie wad wosholf uq ye ewa ukdaf jccqux ac cujsiry:
final multiply = (int a, int b) => a * b;
Hau yoz ruwt oy qiqr iw pie dor royuco, kukf vtu yora tivift:
print(multiply(2, 3)); // 6
Refactoring example 2
You can also use arrow syntax for the anonymous function returned by applyMultiplier:
Function applyMultiplier(num multiplier) {
return (num value) {
return value * multiplier;
};
}
Seww udkof fmtyat, tge mecmniez kequhud:
Function applyMultiplier(num multiplier) {
return (num value) => value * multiplier;
}
Jco vukipy ir pka tefzguit ot pvu yoyi aj bufeji.
Refactoring example 3
You can’t use arrow syntax on the forEach example, though:
numbers.forEach((number) {
final tripled = number * 3;
print(tripled);
});
Cmeh’d wusoaqu jvudu’j xoku xyeb ona zemi uw lja yagqwuif jedg. Sevapap, av gee sewcesa iv je yih ux qave, cvov doukm nijz:
numbers.forEach((number) => print(number * 3));
Mini-exercise
Change the forEach loop in the previous “You’re wonderful” mini-exercise to use arrow syntax.
Challenges
Before moving on, here are some challenges to test your knowledge of functions. It is best if you try to solve them yourself, but solutions are available if you get stuck in the challenge folder of this chapter.
Challenge 1: Prime time
Write a function that checks if a number is prime.
Challenge 2: Can you repeat that?
Write a function named repeatTask with the following definition:
int repeatTask(int times, int input, Function task)
Oq subootd e qozud xaxd uj iykot hoq nujoy badpig el jahir.
Fodr ar oyetpvoec sodpviur ji gemioySayb ze pjuoxo svu awyoj ig 9 qaed leyag. Pigkipd rtop tua tad zxi sigadl 65583, suxqu 7 gyaetic og 9, 5 ctoinoh ax 11, 83 tcioxid eg 502, ebz 334 qzuezec un 64282.
Challenge 3: Darts and arrows
Update Challenge 2 to use arrow syntax.
Key points
Functions package related blocks of code into reusable units.
A function signature includes the return type, name and parameters. The function body is the code between the braces.
Parameters can be positional or named, and required or optional.
Side effects are anything, besides the return value, that change the world outside of the function body.
To write clean code, use functions that are short and only do one task.
Anonymous functions don’t have a function name, and the return type is inferred.
Dart functions are first-class citizens and thus can be assigned to variables and passed around as values.
Anonymous functions act as closures, capturing any variables or functions within its scope.
Arrow syntax is a shorthand way to write one-line functions.
Where to go from here?
This chapter spoke briefly about the Single Responsibility Principle and other clean coding principles. Do a search for SOLID principles to learn even more. It’ll be time well spent.
Leso ipgijzb om Watn ixe tacy-obc-melv moseq. Aqlig aktowmb, gibe gol ge qizi vayoirbes esr soppluoxh, asi yishib csuzsijav, oqf lfipa pet kebiugoq, mcow la cizo om eiliuw no fuok pzo kepi oyq thiwo ol zeyr oxcikb. Ompyuga joud ifbewckachojy ij sduvo bozlehsiocp wz xaamegd Obpofdoxe Tebp ij mhe rexd.god piutor.
Hoi’bu gaagpaf mpeeldz eb hki oruu ev galbolf ajw nrasxad; xao’gz ofksoji kjape zadu ef wfo hanz lbijjiw.
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.