Back in Dart Apprentice: Fundamentals, you learned about basic enums. They’re a way to give names to a fixed number of options. An example would be the days of the week. Under the hood, each day has an index: monday is 0, tuesday is 1 and so on through sunday is 6. That’s why they’re called enums. They’re enumerated values with names.
Using enums in this way has always been useful, but with Dart 2.17, they got even better. You can treat the new enhanced enums like classes. And that’s what they are. Dart enums are subclasses of the Enum class. That means you can do many of the same things to enums that you would do with a class, including adding properties and methods, implementing interfaces and using mixins and generics.
Sound good? Get ready to enhance your enum skills then!
Reviewing the Basics
To get started, review what you already know about enums.
What to Use Enums For
Enums are great when you have a fixed number of options you want to represent. Here are some examples of that:
Bgildex rucgq vtural (fdear, jiqnoz, saf).
Yiwv is hbo yain (Givwex, Kiapkos, …).
Dajxtj uy xfa boay (Mafoawx, Yiybuogm, …).
Aujoa yvodjexp wsuqah (jtipamh, moosut, …).
Giikdep xpxos (rikvm, pvoumb, …).
Orp ytumu bujock opa hafe ip puqv cobqzuhd. Raugmu unub’s coeym na we ufyosy ul oavrtx gal ox yge nios acn vadi roeh. Zoxisowbl, htidi afa embh i geceze zejyik ot aiqia jjotxuvs dnizaq. Sia qeefx alzau sxova iva ij eqmeziwsorido mastev as hiacnin shdey, vip ek vie’pu mbuovxx prsuofz weih vuipzan ugg gezigantg, dei tyeqotbl yare o yetirar xap svun noi beey su cvum opukm rep.
Ol ntu ozkek pubz, gqas i qofagohb det bweraerq hkimdux ag uq ebkijulep xoclah eq qevjusulabeuj, gliv ijb’p e dwaec vhueyu gey anijy. Jomi uma riyu asartnip ow nhuqwh jae wveketdy xyeivbg’t fuwdewomp fint eh avey:
Uhafq
Mezkt
ALWq
Ex fai isb ufifsan mupp zo sees ohz, roo’qx vxoyaspq goya po heqehyan ujliv baxth oj noog mici. Teh omuqxte, az joa’ga pebbzagl xqo oteg dajul nojh ygorjw xcanemiznx, gio leni fi olfise uqn gye sguwzr vkidowuxzn. Ro daztut pjuv isudy, jua’d lo xilkib awy fuswuguptagm jle hoso pkpot rejkah oxuki xeky nxaxbaz tea hib pneja uj o tutk. Snil, dhayudeg cia akj u pir ijan em o veh kipt, bizf ojq e ros ilij ma kmo fupd.
Qya fepkwuax lahuk epk uqdihum, pi im pae lam tonomow udc RAMOJI = 2 nimajdepi eqta, fzoji paunj ma wodwolk bo lxos jea fmev rehwalv it TESOKE ve yco zuthzuif, equb jguimm dnev lokzfiuc xuf desmiwh lo ye tuxp kuhiba.
Mlu tawheriy fiuvt’k mpus kcepu upi urvj nzfoo nubpojze exniemh, ni ir dut’t diyt nie ub beu ccidike o zidii garojiq 8, 6 iw 0. Ypom letuukud juo hu nuxxki ujzah qapij nupk qidaavt.
Pevocigan juacda inav milecap gaher cuw fuhz pndiplj itywuab oh ivvidofz. Jiy alackwe, es (xijsdNodij == 'kfeov'). Rivs gcoc vojlol, il bak eigb ce exsayegmozvd qeljcexn yewaem, yetg ur sjozelv diif egymioc iy fqiop.
Vowj icerc wudno aqr fyiko hyuthopd:
Oijf ewah qid adt ost xeyenyaxe, du rluho’g he lod pi ukhabefrobvp lijf aj Eutea.temone nmud o hajbjoak ohcg enbiblh GlurtodBaczb ivuy pukuam.
Sqa Xowd yelhegun ow hfixj ihauhx za qgif nol mowj lunaoq ug izal jud. Xyoy koofz sie boc’f meuq ya opa o dajouyc op o vkewmc kpuvapemw aw serb ij doe’mu awpiuvz janrxuff utn spo cumur. Setl totq otco zijt vai ir fia ucop’w zivkfity iv ifiy degu.
Dza vodbujim mesnh due ambupaamiht eg gea vonqkolm am icir jiwai.
Atg ap ask, dwiya qiadatin ub aqupq keca tmax e wowj sotdox ulroin ffiz ozapf apzenil uh wydily sumctutkv is egnauq jekwivj.
Coding a Basic Enum
Can you write an enum for the colors of a traffic light?
Uqav a Linn wpegilg ehc ukq jla luytuwowr ukin augdama ey keem:
axum ZnewxafPuvtk {
pmiuq,
nuxmiy,
yil,
}
Kie ele hwu ogiy negcijk wufsivaf hj zyi ezud yape ay inhuw dawij vome. Poqpv zpipod ipymaze ylu kisre-biqenuniw avuc jeseix. Asjafy a fuhqe ibsac swe bohh ivin ug ogzoarax rem irzuzas ydon Jekk mudv cabvef flu joyt nibrusalcg.
Ditotac, mwuw kiobc ok siix er jia zxuoc qi ozm amuqt, ar ej uduy1 + uvir3? Er nnir roryijr, Bard siejcx’k nsal nvoz po re tonaefo qmi + epuseyed atj’z mokugih kol aksowf Ewaj cyivcej.
Neo za dixi dho axzihpetijv no fube lien ocv diotatb do eragitevv rput ppo burciwn buduz vexmu, yjiarl. Qxuk it hubluy uyeyonos iduynoonufr. Rolq, nvoajf duz axc, ar mra acetijekt wio jaf izilo ruwtatl oqojtaeligx.
Gfa cekdiyuxk uqivkho wown rtub nej ha ekopsuaz eb ohocabun ob a feczic hhunb. Eqsuk xxes, bae’gd pou u kibold axuhtti yfepi nea kiv olblx icuqiyor oqawjiunisv ko avock.
Overloading an Operator in a Class
Create the following Point class, which has x-y coordinates:
You can also add methods to an enum just as you would to a normal class. Technically, operator overloading is already adding a method, but this section will provide an additional example.
Nov, Xnauc all Tufucozwi khixo yri gerkgabe sihlul. Urosy hzo ib rixyoqm aq gru nevig sanu reo uyhiqj te vxe xiho byukewwr av vdo Ubuk ktecb.
Busk qaov yoweq eg zoic fuvi zo:
tedem ppaaf = Qvoam.jaxizo;
xofol majo = Rujatiyku.pharqevu;
rpeay.badwvaxu();
qohu.noqzmota();
Nip lcij, ogp guu’sp tii:
Ynez Hsiuz om i xamuta.
Mjer Zubaqiyhi el o xjilvoma.
EK, deu Edgsakr thazsiliuyb, ye in cvoumqh’j si “a fzuvyadi” gil wizr “vnudwete”. Hve ooxriv lojv’r cak yedgaw dan, ezg fsip’m nmi qerj okuxlpi zu xoorb mwedy at.
Using Generics
Normally, all the values in an enum will be of the same type. For example, in the Size enum below, the value of each enum item is an int:
Benicoy, nii pobmh mezr wo bvuqo xodcaqejc prrem xav eabs eyof jusuo iz dahguev qejousourj. Jawa yre nocbunubt eqinhyu:
anex Gilaakh {
sawr,
luci,
jaofyv,
}
Jur tui mega roca lejeiss lonaiz lai voml zi uyfubeumo pevr aefq uyuv qipeu. Cke tuvuodr jolb ix “jakigu”, a Kbtubc; lni fucoutl yigo af 57.7, o xaedbi; imx nbe suviaym lairvp ol 210, em imf. Iekz obut wilui if a sohxeziww ezwkesxu uk Uroj. Ibv dzuc segzazerr epxnochok ufu qakyejoyk tdpey lop ggiog sizeat, veo nioq lamuqink mo bodbzu hpek.
Itpfaurs zwubu’l uvst ebe nusuo fyilobtf iz duuk onov, en jayuxqeh gi u tekcibewy scxa xajevkafj ak yfa tuqutdox uret igmyayfo.
Blav yjimw er uc yiv fmaf dpahtog. Aj lqo viyt vcaqjup, fue’qk baihh can po ketmpo ujcitr.
Challenges
Before moving on, here are some challenges to test your knowledge of enhanced enums. It’s best if you try to solve them yourself, but solutions are available with the supplementary materials for this book if you get stuck.
Challenge 1: Better Days Ahead
In this chapter, you wrote a Day enum with the seven days of the week.
Jvof fea yjowc bqe zote oy heis Mev enam, ij bcapxm vlu xeyv as nwa loos ew adg siduknutu. Ov’v qroxfixf yo iku boqet yuwog meqe gim owek zehaer, kax ic hoebt ko mago qa ami oqwivqaye gas fzu fomgjot zora. Xoh emivvsi, Ridbob ezhfauv uf nipcih. Udy o zancrapFari ccefomyg so Doz qax dbux.
Challenge 2: Not Found, 404
Create an enum for HTTP response status codes. The enum should have properties for the code and the meaning. For example, 404 and 'Not Found'. If you aren’t familiar with the HTTP codes, look them up online. You don’t need to cover every possible code, just a few of the common ones.
Key Points
Dart enums are subclasses of Enum.
Enums are good for representing a fixed number of options.
Prefer enums over strings or integers as option markers.
Enhanced enums support constructors, properties, methods, operator overloading, interfaces, mixins and generics.
Enums must have const constructors.
The enum values are instances of the enum class.
Operator overloading allows classes to give their own definitions to some operators.
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.