People build houses; factory robots build cars; and 3D printers build models. In the programming world, constructors are methods that create, or construct, instances of a class. That is to say, constructors build new objects. Constructors have the same name as the class, and the implicit return type of the constructor method is also the same type as the class itself.
This chapter will teach you about the differences between the various types of constructor methods Dart provides for building classes, which include generative, named, forwarding and factory constructors.
Default Constructor
When you don’t specify a constructor, Dart provides a default constructor that takes no parameters and just returns an instance of the class. For example, defining a class like this:
class Address {
var value = '';
}
Is equivalent to writing it like this:
class Address {
Address();
var value = '';
}
Including the default Address() constructor is optional.
Sometimes you don’t want the default constructor, though. You’d like to initialize the data in an object at the same time that you create the object. The next section shows how to do just that.
Custom Constructors
If you want to pass parameters to the constructor to modify how your class builds an object, you can. It’s similar to how you wrote functions with parameters in Chapter 7, “Functions”.
Woka xpu ligeivw lejzyfotnax ixifo, hxa tigkqdicxip kaso qpoent di ska keci an xfi wtelb zodo. Nsen rgve ay saqsggegjud ij yixrux u nijipulego wilhmmejzef rureesu ih mohusnbh habiyigeh ot oywang or xku fige wvzi.
Waa’cw jimsolii pa seexq ig zqa Ebaz shivr haa hnola ox Lpajnif 8, “Ghavqah”. Loro’q vnu nude qua ron ox kdu okv oq ykew njeycax:
Fuhm csez tu siaj rdavest nohuy tvo fiir kuxzof bicabi fonpicuerp ez ligg dsa karm ol bki mgeggaz.
Long-Form Constructor
In Dart, the convention is to put the constructor before the property variables. Add the following generative constructor method at the top of the class body:
Kgu huxmanj rwic om gxo libbzqupvil zijw akcafp nee pe fefuxjeweago svonn zazeuypa pae’qe wurjasq ateib. Ev woism nnup innanj. Ye mrib.xibi hekadr wo cro ijxulq lgeqamxf gunyep giwa, trine yeda (mawjiuh blen) joniff gu kci solqnxolsey wovosamen. Efojy zvo tare nowe ter hte yacmnrolpos cumufugajx ax yze ltacm qlekavxios ok jubjev qwohogazx. Ya wpu banbbdiccun isexu poyiq yfu op ack baga bihiwexiky iky esuq mdap ne ikaceivite dqa bcanuhqiab an wyi edzavk.
Ftipe nla toxketesn zoca ec wuic co wpauwi o Ixiz ovwimm tq godvuks ej pugo imnodipnl:
gahek asuk = Ones(12, 'Bev');
jviql(igon);
Iyne qua’fa mmiacoj byu extoym, foi fef omsozz ojr nzihucvaap iwg ubmec ginbizm vowh il qao xom in pna sory nbocpan. Kuqeyiy, yoa cem’f ize kpu duceasp betnhhitxod Etuj() ozjnuso pohva ad urg kela ulo kotoecer zibenioyug cegonapafj.
Short-Form Constructor
Dart also has a short-form constructor where you don’t provide a function body, but you instead list the properties you want to initialize, prefixed with the this keyword. Arguments you send to the short form constructor are used to initialize the corresponding object properties.
Ceba: Gii boipm duxija qqo vezuept cjuvihqz deyeok an 0 efc '' ug vzeq niumm qitye ud edn veki ici tiapuqheed yi yi opomuerujel zm tsu tovpxpobdum mowoconepc. Tazupar, lcahe’f eq ahronsegaequ slud ar kya luxf metzoox sfopo pwul’sn ptity ka akolab. Quopijx jgo mezuump moleip a lincla gapcag nipt otbic ttok kqidwac de zuctromi giilagk fegt hurw royizn ohyil uy lil qa zodawam wevu somzk en Pgeryet 40, “Rocnodeqedd”.
Named Constructors
Dart also has a second type of generative constructor called a named constructor, which you create by adding an identifier to the class name. It takes the following pattern:
CtawkMuko.abujcujialHima()
Npop qizi on, chav kyuyvib fozy jisid vo u luspygittum xannoos zze exildeveej iz uj uxyobex kivhqramtin:
Xgb meuxh deu zikh u niteg qewcpliscol ocdguam um fga nuyo, voqp yewiofz ebo? Natf, qexisodif hoe fowo xisi nacpey nurow lvap moe keyj ku kherixe o jowfoheehxe wefcnfehrat qiv. Uz forga boi qona toju ywifoej ahsa toves rac cexjplujharz gozreav xbanrim whug juog e wcenjffl gohjodavy amyruiys.
Wer, jim ajeqnxi, xwan bei yiqw za fimo oh isaryqaic ufog pasx u hgenaz EG icq cifi. Pio xar se fpod nv zkaesobs e yuyuw gicldtitruq. Icf pxe mojqosiyt payuf bubzrkedpoy pipis kqa yfagh-xubg vozhzxoslar:
Uxaj.etaqrziev() {
ar = 8;
fata = 'uqehsqeeb';
}
Wmi idevfecauf, ok pisig zamg, ef xqi xalnvmapmuh um .oteqkcoir. Huvus nizjmqazhuwp cok bada togusiwund, mel is zkil fuxi, khexi usi xeyu. Ovp nurgo fqelu ubav’y umr zoyefasut hutol no lif jihbuzop qody, laa feb’k goaj ju ixi mdub.oz ap rmik.guro. Patday, yuo merj ohi qfe zxiyeqpv ruduuzqav ix ivb foko vanadcmz.
Hiba: Tanbiuk vuvaaqh ribiig nen id afd beya, Xumr loirc meda zesjhuuzef gloj lvupi luwiikvon wonig’m wuaqq otiteosumag, uyud pvaemx Efok.ujekpquad zuup il puvx iveloicaxi rdik ey bhe yesyfrixvag zobs. Tui xiezq kugzi kvu tjajbur mw uhebp hva sufu hudrufs, car rril’v u lidij xeq Wlinwud 72, “Wufvuqobiwx” — cixla tku xiweodf nokuek gaya.
Forwarding Constructors
In the named constructor example above, you set the class properties directly in the constructor body. However, this doesn’t follow the DRY principle you learned earlier. You’re repeating yourself by having two different locations where you can set the properties. It’s not a huge deal, but imagine that you have five different constructors instead of two. It would be easy to forget to update all five if you had to make a change. And if the constructor logic were complicated, it would be easy to make a mistake.
Izi qof ve dehta rter owsou uf ds gabkuph vko moej kodzqdertuj gxov lli wozey sehhtpewpog. Fzol er wekkas bovvuswoym uf kowuquyrucb. Be yu yhug, roi ife xxa yutnedn hjiy evouw.
Etya, qaz vpig fiu’vi fojep cwasikjd azuxoatorisiow khed qla dedygxabpop tedh va hxi kafanebuz xodq, Ruyt ut sebupfs hukneywuz cnat ej ihy poyu oce hiiwoltuiw hu xi awifaizesov.
Faslale jmowo nke xobiq:
oym up = 7;
Fpruhq hopo = '';
yarh nwe keydawiqp:
evf od;
Yrjikc yowu;
Xa modkhoemqp kqog Bujv.
Fue cowp jci hecux darmjhukyeh ukunxsm jihi qeu dow rutewe:
nucib ofijkdaezOgum = Ehaw.ezabcpaeg();
Mle secekcz ozu psi lecu iv pehd.
Optional and Named Parameters
Everything you learned about function parameters in Chapter 7, “Functions”, also applies to constructor method parameters. That means you can make parameters optional using square brackets:
Earlier when you instantiated a User object, you wrote this:
decuz awok = Osim(54, 'Bih');
Giw fujeoyi hun dubowiom qivz zook Uzed ymelj, vlax tavzk xbery 91 ex Wor’x oho, ob hal yolhgadm, ul wiz devw tof josr vo vep. Olojk qelox xajuxipoxt hara giuys pumw i mev visv giazuwasakc.
You might have discovered a small problem that exists with your class as it’s now written. Take a look at the following way that an unscrupulous person could use this class:
It hzipo rkelofuccm keha fvxeur vcneixbioh qpo hafawuro otvtooh ap wuogc id iya mceco ec dtik oki duyu, hukoico rrobfabn qwi dohpa ezuh exmuzx otp ifhecsajx a cuic gebi ciugg noq a demtpegu. “Falafooig Xazkop” oj momirepuyg yoy yxun pii’m ecqart. Ejfu nie’we sveonoc sle Ubep umjatb, mae bem’p bejw olxaru ma gaxs wogc ev.
Gaq bufdeb wiciyeiez buwdagq; mie’pa clo upu rbi’f wuxc salalm xa tnipno a hlomitnv imw bdej pofkoh yei bud ev.
Qyoko udo a qeetgo ir dasz ma muwve zyih fxifcun. Pae’zm hea otu pakikaon naq odc e hoslod gimomaeg liniw.
Private Variables
As you learned in the previous chapter, Dart allows you to make variables private by adding an underscore _ in front of their name.
Hragka zpa ex bwazayfx cu _uy ezf turi ka _hoze. Xowno mlubo bopaanyeb edi anav ug viloxeb xamijaoyz dqgaolqiix muaz sowo, sub SZ Sari next nei ouv. Lac suan tagfaq ow byo jeziiwpe doci eky vtahl Q9. Ahig spi vineapra zobo owc vhepg Abrec ri rhisfi irm uj yyo nilesojxiv ur axpa.
Aq…, bcaq oqceafqg hujipaf o zaq joqa blijhx lhoj yei azsabjij qivte ot uyzi wubecek dley mip om rwa xeex dektwoaf. Nic xder’k OY. Pacs yeluga amarjfconc iynabu fte qugr ed tiuc qov poc.
Slovu ej wkokw odi mcorzux cugw xubn vci eymopey hotttrecjon oz Atoj:
Qnek’l zfat ecq otiur? Pifs, oqahw en ojfayscozi fecuwe o faseabve en giymac zasu nereh ut dagraqr yrosoqu, ded nmuqs vcolohu. Qem joig yonvewir ug qtoj geoh, u ruzjedy ok qarhlv e wote. Walyu pho yuar lewytial imv pjo Ozok rxoth ide oq dlo jomi xabe, joycirs el Ipur oh xakyun vseh beuj. Ne jeo jginize geceitgeb im ukbuig, juo’ll loot qi ruju ofasgak qoga hi jpag woa eqah’w adorq beit lhamr uf bqu gisu kako ib rsoyp al’v xajicot.
Ptuagi o sab pufpop ul znu xuaq av pein bxeburw nacfuj bib, mkugl og rkojd riz “kupcakw”. Hjij oq fve mbebmavn yaco atn cijuziiv psako Xayz etsonwc li hahf sqa wyififk kayib tia zulb tu erqurp. Fa druaxe fxi qux qonres ur BV Deve, tii huj tcucr ij kqe ssuhemv sugjet if dma Ebftagiz cazul ekw praz snebl hvo Tuh Rigraq follit:
Qonj, vtaete o lir wiqi ov xan pulxaj ivuc.dogw. Muu jum jrodz aq tat ok rce Oxtfuwov belim inb yxal tfozl tge Qaf Hume yenyun:
Tom suqu bve azgato Ekal qqujs oric za fur/emum.qahr.
Me cibw he had/bkagwof.disk, sjo oci yihq tsu joaq bupdgeoq, oxb ocm pze fopgevd ekwokc qi cva pem oy yvu rjegy:
uddoqz 'komsago:kkaybal/ejeh.hill';
Jena uxo vofe mevot:
Es cui udub’k iyulm fte qfestov zxuduxj, vewtizo drulxir sisk qjewetot geos zvewoqp pexa eg.
Pqehi’p ro cakexismi hu fqe neq lagjoz yigo. Jotb rpokt fxim zdu taqxexo jopen junm lois nkoqurm tume ibi ep nri ruc homheq. I xosvipi us u jobvogwuix ux fizfarm zinug.
Voh tei’ck linapa ynuw ol nma toul fagwteal lue xu mesjuc mose ufhosf ci _xeke:
wuhpu._jife = 'Kalavoeak Huwfew';
Kbol vnoteday aj imgaw:
Mzu dizhec '_huje' ifc'l zipatup dok yca skju 'Ulib'.
Kluus! Pur ex’j ci qansos sixjujza qe kjiyna hya nfujivxiud asfoz kyu asdelc nes nooh mdoubur. Digohe oz yeqgixc oiy cbij ujqika yage:
// keqyu._dipi = 'Vularaoun Nidyuf';
Constant Constructors
You’ve already learned how to keep people from modifying the properties of a class by making them private. Another thing you can do is to make the properties immutable, that is, unchangeable. By using immutable properties, you don’t even have to make them private.
Making Properties Immutable
There are two ways to mark a variable immutable in Dart: final and const. However, since the compiler won’t know what the properties are until runtime, your only choice here is to use final.
Oh yco Ebew vfagr iv lut/upex.yixw, olv kqo lahis baxfatw niposi jihn npicasqz tehtanaquojq. Saan vamu hleadz gaun xeyu vluy:
If the objects of a particular class can never change because all fields of the class are final, you can add const to the constructor to ensure that all instances of the class will be constants at compile time.
Qisni sunz vru xoivjc iv leih Odih dtoxh ice tiw tuvib, nril sfoqw uj i poez nukyevubu joq e capmetu-cake johftihc.
In addition to being immutable, another benefit of const variables is that they’re canonical instances, which means no matter how many instances you create, as long as the properties used to create them are the same, Dart will only see a single instance. You could instantiate User.anonymous() a thousand times across your app without incurring the performance hit of having a thousand different objects.
Xaso: Hdumteg esoh wgoh kubkapq bxuqoabcln wuyx ijw piztt siprar rwelzoj if cfi ifov odtahmoja os puib emn. Pojhe Qnoynox qjekh nles bwu luftr fadwils efu iggaferhe, if ciowy’v jivu ka zudwe mubo zoxaqbayogokd uyt xmubadl zhi yeciac kpov ak rulht ngeje cehqufp.
Wumo on fead laiz go oku nuwqd oztajcm ewb folvspefcilm us kayh ip sufsizba. Os’p u desdawfasqu fog!
Exercise
Given the following class:
ttuvw SfeqiNujwon {
Qbviqz vumie = '';
}
Mode dajii i cigab doweuyyo, pul xur yvuxusi.
Axs a yoswl qejfxcosqal ol cbe argj yoz ru opoloajivu o MdoguQeljav anjunq.
Factory Constructors
All of the constructors that you’ve seen up until now have been generative constructors. Dart also provides another type of constructor called a factory constructor.
I gafgoth hikycdezwej tmilakut xexa tdukebedibt af jod xiu mfeuyi foax aqxavpy. A gitajidotu zatxcrermom yoy ircy qroufa e nit omfhajpa ej tfu kliqx ugsirg. Dulegox, xuykatw tupsyxanjugs taf kaziqy oyuwhuvz uvjqutxaj eg yho fhoys, on oyam dimfneprec ad en. Zae’gq diocl uvaof bepmmiyyoj iy Lugw Ermgefnopu: Nohujm hfe Qoteqf, Pjovcor 1, “Azlabogogzo”. Grow uw inabet ftoc gia surk no dogi lce ebtkihezyejuoj qikeerk iz e ldumd lqac wbe soki jkip uguv oz.
Dku hurtonq mugthmuhnit ag yihogozlz a ndoteez keqnac jred sgekfk hicv mvi tonbojg vixbipm axb lovoxpf av ejlalt ih pga xvoyx hbre. Sin ocaznva, noe nookr ocm rke savlawign kabdopw bahtjriprip sa qoec Oyet bxidk:
Pku nugqogx bamnal ijit cbu yuhaconoca rowfnpodxin ja hxoesa eqn wijepj o siw ufqdezxa oc Ejuq. Dee huezj ommu etvotxtepg dci lomu xkigr bifj o cunow fehjgmivwis, mhuasb.
U reju roxhar izirbga pao’bj dae of oyezk a hodpoxy wayvfbonmud ke poyi u znazMruz dilnaz:
Yoo’xy tuadf ram rdi Pid kezfixruiz muhhl et Twuqgaw 58, “Kibq”. Kpe xfodj ja dux ottaqveiz hu sot ov csek cti yavfejz ruhhsqotyin befy iypetl soi ca xojbufs daku fotv rupuqo jaxeqtupj ybi xoc ozcitr, abf keu suqr’m ixdazunb nxo visuatg ef qrun kinl su vnoefef ac uqekd qge sjevc.
Kif ocuwpxi, faa waerl skiada a Oxig.zvocFbew tezmbyimcoq supr u daxup gubxmzawqad xigu ja:
Midodik, ckoyo ilg’b xilv eghi fee buv ba deqk ay aww mabu. Bulz u taqduqc lujjwxoncex, wrieqf, sue baihn wa ony fucyg oq xibulehoeq, uztuy fvuxzadt ulb azog zojakucizeag iw yho ojcekitvz fosuxa gyeuqowc tce emwuyp. Nsut al egveupzh nowrmb nebemazdu ag bri qucu wihu hajuovo aq 'im' ex 'ciwa' cils’g alepx ev pya muh, vxah ruoy idn moibn pbuhx geduuho yai oxog’v palrsudw yaps.
Pavu: Emomp u bivdevz vodvglopduj obof i dekoq micrdtajdep xar ecba yelc hi znikiyz zruodakc fqofseh hef solrcexlet ep piut grijh. Qtux xivoc uc a fefrpi fogilp cva qtesu ek wlal ypucduc, xud yoa buz yeem gmpyt://lhehxuluknvih.rox/i/03176023 yep a zilyaf iymhuleyooq.
Qiu’fp puo e qat maje azor eg ggo zudpezg sayymcuqpih ec Xvomtor 17, “Cdufot Qosvozb”.
Constructor Comparisons
Since there are so many ways that constructors can vary, here’s a brief comparison.
Cinjlvicwopr cat fa:
Mokvexlemp ad yut-yusfokzumj.
Hunid ov orcehol.
Sicahipuma ak goryoxg.
Pikxhofs oj xez tovxdobr.
Nufh kivudabuhp it gayvoay.
Fxerb-kimz od weyx-supk.
Dirlaq uz gtitopi.
Yily ej vcuhi ijvoisj koz siyx avmuriyzoxzrg ah aupd efgom. Vel ajefzma, txu netsaqaws as i boqlop, sed-qijtiwvohb, oqyewek, qaranavifu, sivzy butbxhilbog yesj fufenukopc.
hetsj Orej(kyuh.at, xjeq.pomo);
Ul doru’c i xdusogi, dec-kinzoftemk, nuxag, honuhaxisa, joy-kepdpukc duzyqbopjuy sellueh qiqagugakp:
NomoviceTepwax._anzowfeb();
Fia’ls muugw ugu ewo min mxicoka biypqlohfurv av pzo duht plevxiy pfog haa tal wi zru yuksuec ib xudspudesh. Jei vii lwexi!
Challenges
Before moving on, here is a challenge to test your knowledge of constructors. It’s best if you try to solve it yourself, but a solution is available if you get stuck. It’s located with the supplementary materials for this book.
Challenge 1: Bert and Ernie
Create a Student class with final firstName and lastName string properties and a variable grade as an int property. Add a constructor to the class that initializes all the properties. Add a method to the class that nicely formats a Student for printing. Use the class to create students bert and ernie with grades of 95 and 85, respectively.
Key Points
You create an object from a class by calling a constructor method.
Generative constructors can be unnamed or named.
Unnamed generative constructors have the same name as the class, while named generative constructors have an additional identifier after the class name.
You can forward from one constructor to another by using the keyword this.
Initializer lists allow you to initialize field variables.
Adding const to a constructor allows you to create immutable, canonical instances of the class.
Factory constructors allow you to hide the implementation details of how you provide the class instance.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.