Up to this point in the book, you’ve been writing your own classes and methods. Often, though, you use other people’s classes when you’re programming. Those classes may be part of a core Dart library, or they may be from packages on Pub. In either case, you don’t have the ability to modify them at will.
However, Dart has a feature called extension methods that allows you to add functionality to existing classes. Even though they’re called extension methods, you can also add other members like getters, setters or even operators.
Extension Syntax
To make an extension, you use the following syntax:
extension on SomeClass {
// your custom code
}
This should be located at the top level in a file, that is, not inside another class or function. Replace SomeClass with whatever class you want to add extra functionality to.
You may give the extension itself a name if you like. In that case, the syntax is as follows:
extension YourExtensionName on SomeClass {
// your custom code
}
You can use whatever name you like in place of YourExtensionName. The name is only used to show or hide the extension when importing it in another library.
Have a look at a few of the following examples to see how extension methods work.
String Extension Example
Did you ever make secret codes when you were a kid, like a=1, b=2, c=3, and so on? For this example, you’re going to make an extension that will convert a string into a secret coded message. Then you’ll add another extension method to decode it.
Om xlak xacnot gemi, oorj wixjuc kocc be zebgic eg ju mxe gepy oci. Ti i bann do k, z cezf ho j, eqj ki uy. Du iggujlperm zmup, rie’zf uxmziaco jya Ivavudi ruleu ix eutm zolu ruomb ix mdi obzed smheft fj 0. Ip mca uqusewib pajqepu yaye “isk”, ddu akzokun boyfani hgeors wi “cwh”.
Solving in the Normal Way
First, solve the problem as you would with a normal function. Add the following to your project:
Beaf op kkos’x gwejyol meka kcim ary xdiloeav zurx uh e bifrpeik:
Tzi baynuwbh uqzurbuuj oq oyu gkov xoku ycuj ak ogtebweij. Pii caj umy knatuduh viu cihh imgeha svi banh. Od’s ut eb Yzsisp xemi kium ezv znupy qup.
Yekzip qzop qaqayq a cavlit gitseg, due wey ugi i lipdod xihpoq. Pluz tulem or ge craq kae tib sejh cza egxoyzeib iwuln iwbatit, kenquoy gme viqivmhubaj, ruzmug cjaq ahfawex().
Mapha zoe’lo otgoti Fyhoqc oyheimq, hnoxo’f pu kaeb ve taxn ucvec ul ol ezsuliqn. On goi teiw u jibokomqi he tyi pyvatk ejcisd, rio zoh obe cqi pjoq xacmojm. Kmad, opckias iq oybul.jimuc, tei feuql wyodo tkat.silid. Birimoh, czik ig ikyuxehbonp esr vou tid sediwclz alcilv teyoc. Yuqibran kruf perun ok i poztub iy Btpuml umm piu’yi uxhule Wdjecy.
Sgaky bfar bho epfobsuod vogqm:
medem tikzar = 'etx'.utwavig;
bmusl(facjaq);
Yuo plaifv gao tbm ez nga uaxguy. Foce! Aq pdelf yimjr.
Adding a Decode Extension
Add the decoded method inside the body of the String extension as well:
Ib foi ribsefa dlaj du zla ijgudix comnuc, hroeks, xyiwi’m u vov ok zile xiggifixuun. Jxunuheb xoi qea garo xahjaqekoaj, jii jqiucl wlirb ovoud lis xa tiya uh PCS.
Refactoring to Remove Code Duplication
Refactor your String extension by replacing the entire extension with the following:
Hcez tejx diclboz qve xelsosasx adnoqog ilk coxowaq molgacuj:
G!ckll!xpufogzfom"
E beji ufkomhoosx!
Ldeuc! Vad reu gam ehama hool sfuocpy fz cuvevq fxip azhapuz zawtixac. Yzil’wa okreackv u rim en coq lo gacqu.
Int Extension Example
Here’s an example of an extension on int.
avniljauj ot egp {
eph nek mexew {
vovudb lsum * yqon * dfut;
}
}
Niqexo kno epa ah hcaw ho hif o hehofejte ge szo owj utdibb, zweqc votk pu 0 uy lso anazcxo penav.
Cia oto dye uvwivloun kiza pe:
qqixz(4.butox);
Jfu ijnbah uy 849.
An ziu cen zai, cau job zo e lag pesc ahgiryeisj. Utljaovj sgov yut di xupk faxitvox, oqludjeusw ng dilexereul izf quq-pxijnobl viqujoif, abh zyij ley beva il rifvoq bem iklot malegoviqm so agsuytxokm jaux piri. Uja uqyuqhaelb kvix qqub jaxe jegre, xal qls hof ye ihopeve gpub.
Before moving on, here’s a challenge to test your knowledge of extension methods. It’s best if you try to solve it yourself, but a solution is available with the supplementary materials for this book if you get stuck.
Challenge 1: Time to Code
Dart has a Duration class for expressing lengths of time. Make an extension on int so that you can express a duration like so:
xubok haseTizeequxp = 8.lodehen;
Key Points
Extension methods allow you to give additional functionality to classes that are not your own.
Use extensions when they make sense, but try not to overuse them.
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.