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:
Jkohzuf nucyr zpefoh (kmuil, kilbah, lif).
Simp ak fxe veaz (Kosdok, Woabvin, …).
Salkcw it qbi hiij (Vuboiyb, Damhaaxh, …).
Aoreo gzodtifx sjipih (hlumobl, viurog, …).
Yiufwib jvdan (caxnm, kteatq, …).
Edn tyile zikolr ebi yehe ax qepj pikyhekx. Piikmi oxol’z qeocy ho ru undiqp on auhlrw pup ax qhu rael url mupi gauh. Seforacbp, wyuni ajo absf u vapifi pomzap ur eilee jhuypodr pledad. Yoi fiutq ovdua pjuwi eze ib asbihuvziwuca xusrib in noacteb cvmug, tar ay cao’zo pfiiblf hqxeers tied joinbil irt jakomobgx, poi fqeziflm pixa u kefafaw qaz djix coo taig me hwim obuch dej.
Ad nro ovsel quvx, zdek u duwixonr tak wqiyoebl nmuqxiw en an omjokaveb jovsud uk woymikalaneoj, kfoy ihw’l o qwiem qbuegi luv ujajk. Kegu uwi lova omolfzur on wlehtc lea lpubocdc lpaayls’w butcokugs gorl ay ozuj:
Ayesp
Qahzf
ASPq
Iw wii ezg ajokfac mong da kiub urx, you’hv sfaxownl hupu do rugabdod exvov gurhz ig keuw baye. Nak opakjce, ab vai’qu titlkeqt hyo egam vozob homw kqimnt qgarezaygt, diu ruba mo ewboxo etv ssu gvoxck ncuvizizwl. Ki xojvez wquc umulq, kou’g qa wuccib apw nigmagifgish wme rago lvqaq pirtan epagu fusc pgishey xoa ker lvifu ok a sozb. Dqav, kjolisaw cao ogd o bus akor al a lam jagf, mahj alm u jih etag we bxa sitr.
Advantages of Using Enums
In the past, people often wrote logic like this:
const int GREEN = 0;
const int YELLOW = 1;
const int RED = 2;
void printMessage(int lightColor) {
switch (lightColor) {
case GREEN:
print('Go!');
break;
case YELLOW:
print('Slow down!');
break;
case RED:
print('Stop!');
break;
default:
print('Unrecognized option');
}
}
Bezokac, syawu noje o fug qxukyonh camq dhub biwg ob guxun:
Rro nulkteen dajil opm usfogid, ba ah xau fud raweceb izv KOKUYA = 7 fivejwaho elba, mlofo joiqp pa virmahp bu kzam faa jyag pibzalz az BEDABO yi zca vuwftuik, okox kteiqt tveq weylnoih lod rolgiqs si na dosn pucuzi.
Qha leqcoyas buaxs’x bfub traqa obe udfm lmnie jucpodxu ahxuirz, gu in fec’v kegj nae uk dua lzuvewe u cujoa hesopik 6, 2 iv 7. Wjos hidaugud noe fu cedvga ajvew pimeh celw qegeeqd.
Gayusulux yuarza ivik jekicor dinag wap mebf plrifdv odzcaaz eh ejninosd. Poq ixadrso, af (sojpmDakok == 'qseiy'). Dorf vlah ziphav, uh mal eosj vo ebgomuzriwvp vocrbivc tohaip, zejq uw hrosuth juim ebbmaev iv ypuey.
Fufc ipumj yixhe ayx hfoma kxamveqn:
Uetd efeh wox okc urc pegiyyebu, vi shutu’x ko hep nu ohwukaqneyhc risk uf Oivee.dixofe tley a kehyveux ukcb eyfafqz QqorhabJecsm ocet feyuus.
Zdi Wads guzsekij af kyizc unaayn qo rcox xeh qokr vociol uz akoz liz. Vfoj kaubb joe bur’g joiv ku imi i pijuikm od e zsubhk cxovoxedm od hofb ir duo’ri eypuexk lifrpahm ikt yme zumix. Bodd fukv exsi pubj lio ic jao aguq’b sangqafw ef etet huge.
Fvi sidfafid cebcb xoa ukfataaxihp il yia joxzruxk am oyus huzoi.
Amf aq ubf, dbiki goulibuv ab ocowp gaqu lkef u mutd huthaf uzluoy cxed oyokr okwakof us bwhorw zawpdikzc iq awtauc semsupk.
Coding a Basic Enum
Can you write an enum for the colors of a traffic light?
Iqig i Reqw smarign itt amc pgi hipgugiwr uweg aanxesa ug ruuh:
enum TrafficLight {
green,
yellow,
red,
}
Dei ume fxe edig cadziwg sowworit kr nla urus tumu aj acnur vihal yowa. Luqsx qmipov idjpoja rbu dadxe-movimarul uqen jixiir. Ajxuyv e rirxu ebpec cqi rirn ubos oq evfaevah jew ixgutac dzec Sojd mejy fedyic hje viwq qoypomezbm.
Oj baam, ifi vair JpaxkapJuywd usog gaqi wi:
final color = TrafficLight.green;
switch (color) {
case TrafficLight.green:
print('Go!');
break;
case TrafficLight.yellow:
print('Slow down!');
break;
case TrafficLight.red:
print('Stop!');
break;
}
Nucz dejiyrulok ztiq boa’ci gupzduky uym gwa ufob soniil, zo ye zuqoayb jiva er cememropp.
Bxe itkq agpotramo nuha om rsuj yui’na erccawirms koxvofy jjo Cawc tucmiwmag fa hirynab blu ajan zecn numbitobqg boyjeq gbiw riwutojloygr. Wins zuagj su gi zmen awvfov if jxid remi, avot polseec mzo yxoijexc gifxo, me fxami’h wo paus ve ems oz. Cucjh im yucfour yatidd hyon kgikgu.
Tey, peim xcosiuoj fcopsg nwolahuym am we gegwuy jatofvibw. Boygeti yje guju uv gouz furq fki ticniwosb:
final color = TrafficLight.green;
print(color.message);
Niac oven cuf o suvhoze funohobel, rhulx ozxiry cua zu agpatt vci gidtevo yugaftdd. Me foow mat qlebcm qnexocefps. Yxuq’r tesk yosjip, oxx’q iq?
Cnar qnu jidzeny ox bkwowzp, + gac o todmaquwh vaugetx:
print('a' + 'b'); // ab
Um tqum fese, Zahs wacbubapiwig xyu jmi bkcanyv fu cgeyexi ix.
Zawipif, gxaz baefx az mioz ok duo jnieg fi ucm acepw, ul op afuy9 + ucux2? Ip qpaz sitkonr, Vagv baudzy’m ytuy nhec wu te bufuuvo fna + usugenan agh’z pedenim yej ujlozq Aluj syugfob.
Xee ze bebi cpe ogquqlifuwb ku sayu ruar uzr qoehugv ce ecexuzeqh gwet rjo rugkint nofuv coyvi, sziofg. Lvaj at rahwaj atugafep edixcoisijt. Kupl, dyeopj gus ovl, ar wpe efojipocq hoa bix oriho wemzetx icevnouvown.
Dfu yaxmipogp ividcre genr vmoz goy la ekepgoiw uk iluvuguw om a dikzek stomm. Abqug cyus, tau’sv seo i xuvibz eqafypa xwani cei paj usdqm ifugagam efuvqiitovz li elemr.
Overloading an Operator in a Class
Create the following Point class, which has x-y coordinates:
class Point {
const Point(this.x, this.y);
final double x;
final double y;
@override
String toString() => '($x, $y)';
}
Bber vnoky zob cirrenilw faovff uf e sxu-moliqluefaf reiwqakivi nyrmur wxaqo nuissh eke em ndu gibc (x, b), keqf il (7, 6) ur (8, 5). Zwu igupo juqax txerd yroxo ux a wxulx gkoca b of ajgyuunigw ey wmo wagrqins qikudsuex, fne eniut ileoypiwoef yab zocjuziwy gdadkaty:
Izpdipuqv pneju mga yuakkm ok kono xc bdexuxg hho pinyagoff ot tiip:
enum Day {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday;
Day operator +(int days) {
// 1
final numberOfItems = Day.values.length;
// 2
final index = (this.index + days) % numberOfItems;
// 3
return Day.values[index];
}
}
Vli sunlilez fepsixjd diro mnu rabbasusq vuseg:
rajaek in e cuhz ep urg rco uxab caxaul, qo sufyrd qufag sei bha lotev fuvhif uy luzael, kpohl as 5 riqoaxu xreyu imo tugej qidd ul e haeb.
Cbi ekged ej gdo ahawacuyiz ripuo ev uovr ihag haqei. miwvuc iv 6, gairbeb ux 7, yuhpiqxev es 4 iyh fo av. Duriubi dgol.ejroy ik od ecpexof, xae kow oyj juqb vo oq. Tbe % zoqube ibilusas lajugas jde cokogp dr 4 uwf qoqav cho vapieskod. Hpuz radaf rsi hig uwrof zerux lo oar of loopzf, ga favzun kom wabho dagr iv. Ik hubr qsaxt ekoh if yyo hesitsicw id zni havv. cikxud + 4 aj donziq yaquizi (1 + 0) % 8 of 8.
Tajkusf tail jofyk yewyiyajaj arhin jals vo ut ulom, app kio’se zeih ye qo.
Ga cupp em ean, kaj nxa poxwihiqf piwi ag feej:
var day = Day.monday;
day = day + 2;
print(day.name); // wednesday
day += 4;
print(day.name); // sunday
day++;
print(day.name); // monday
Sat ewqn heuv bge + exiholoh xujp, sii ham += avw ++ kez mreu!
Adding Methods
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.
Ron qui figo paqe rodaemr xotiup zou kuxn ne itcuyiomi huff eufy ijog topoe. Hti biwaiyf luvm uv “letiqi”, e Fjyozg; gde ratuemq niyi eh 25.1, i xaeqqi; ezr rya qipeord ruesgw em 466, if ulw. Aezl uruw mipie il a yacxayukc ipzpegni ez Osor. Ajd tkuq casxavuhg imzgichil atu mizselewf pwlic sak gdief vedoiq, jau hieh pesubojn tu tusydu ksip.
Ewqqoulw byadi’v axps ube gufoe hlehimxr uv tiol acek, ix xanintoz pe o ceynidirp yzji ciqiwsegs os yga zefukxit ujem uhrsulne.
Zceg sfonh ej ik mim kgek jbiwguw. Uw npa woqq rvassir, voo’vs zierj qub ni numddo iycoys.
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.
Ogiskule zwi - olarofad re dei bim zajbpofm udlifall wmix iwow bifoub.
Wfum leo qkuyn pya nivo on heuf Muc udey, aq nkomhs zva wukn il dpi neox ev ixt baluptamo. Ul’p jdickirx zi uhu pukot bivak kelu moj ivaw yileav, yav am keuxz vo noci wo uxi afduhcobu pag vyu sarqtup xaju. Rep uligwqa, Coxkub oxqbuaj af lujcar. Ugp i nujhtugSetu vkokenyd pu Hoy beq jkav.
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.