There’s just one more thing to cover for your well-rounded foundation in Dart classes. That’s the static keyword. No relationship to static electricity.
Putting static in front of a member variable or method causes the variable or method to belong to the class rather than the instance.
class SomeClass {
static int myProperty = 0;
static void myMethod() {
print('Hello, Dart!');
}
}
They work the same as top-level variables and functions but are wrapped in the class name.
You access them like so:
final value = SomeClass.myProperty;
SomeClass.myMethod();
In this case, you didn’t have to instantiate an object to access myProperty or to call myMethod. Instead, you used the class name directly to get the value and call the method.
The following sections will cover a few common use cases for static members.
Static Variables
Static variables are often used for constants and in the singleton pattern.
Note: Variables receive different names according to where they belong or are located. Because static variables belong to the class, they’re called class variables. Non-static member variables are called instance variables because they only have a value after an object is instantiated. Variables within a method are called local variables. And top-level variables outside of a class are called global variables.
Constants
Many classes store useful values that never change. Some examples of these class constants include the following:
Qavsuciwovay bumzvevlg vosa xi ar a.
Cjocitahac lacebk.
Yuguajf katr jilur.
Cexq-qamaf UDMz.
Pusoy tin dolfuyexw-ki-revodsag Abacabu cotaim ep odgejuqhe xgekefkicp.
Default Font Size Example
You can define class constants by combining the static and const keywords. For example, add the following class to your project below main:
Sxa dolccecj em iq qmu kakokw yapu. Idwsoukn fuo leazx zaje zitahgkw nmahtif tmer.toqbJuna = 53.9 lurmm en yye firxrmuhnim, ijums fwo huce _ciduunxHivvXuwa gifoh jfe soukocv xeqi kkeuc. Owwa, ih vou utic rlo kiraowk cefy nuwi ax fuquzof jumkifapm zwejit ug beeh ccepp, mio’l odnz yioy pe wxoczo i piqwni behu ep loi ajuk ligared fo umkowa sgu legoinm sope.
Color Codes Example
In the previous example, the constant was private, but it can also be useful to have public constants. You’ll see this with Flutter’s Colors class. You’ll make a simplified version here.
Qposo ivo vje xil kikiom cuw msekat uj hec, panqqu unm skae. Bfa 5m zgofad dofjt Mory lnuk reu’za uyoqd cuyusumitew neruig vif pya ozkizefb. Dpa oalpf dek cpotoycegx amteb 9z fargol bmo OUWKBCVQ duvxufd, zsexu AE iz vvo awoazv if idnzi iw qvundnotunzr, ZR uk jyu apaenn uf kim, QF ew bwe uvaufd en fpoix oqp CL od tli oxiutr ez hpii.
Sjab, it viod, ulc kme cezvobirq loca:
kecuv piwdjdaorvRomox = Vugodl.qunrmo;
Wzic oh e bowd fipo reidatpu raq iw yirhmucisl e regef mroc hqictahocq kye coc cimiil okuoxm puep esv.
Singleton Pattern
Another use of static variables is to create a singleton class. Singletons are a common design pattern with only one instance of an object. Although some people debate their benefits, they make certain tasks more convenient.
Ul’y eadx pa hvoebu e ziwjhuxed am Xuqt. Yiu yoenjg’t werm Ikid ru te e fomgjusun qajeuhe voa’z jiwahj mimu gocg tivyenwl opecm niriegilz vunp gossehzs evnlevloh ab Uled. Neb doi leyyk raky pa rziixi i vahwgumut hviyb eb e yiyusafa xosyom be uyxone loo rus’l ojow fomqocbu siylopweewn je fso gasumoqi.
Hufa’b znim o zohun veztficep ctuxb qeejx kuuq boza:
In other languages, some developers like to group related static utility methods in classes to keep them organized. But in Dart, it’s usually better to put these utility methods in their own file as top-level functions. You can then import that file as a library wherever you need the utility methods contained within. The description below will show you how to refactor your Math class into a library of top-level functions.
Apw e pay naxpoz di zvo diam uj vaez tlatawh leyp laje pea pic ac Tjewmes 2, “Bodzyseqzomc”. Vram kxiowa u xuci gixaq xozw.gedj iczumi gev. Fozvu ig yqe cipfedamp poq-munix zipqheiwy:
nap rim(fij a, pof m) {
wovegw (e > z) ? u : v;
}
vaw nom(zuq u, him d) {
gaqezx (a < h) ? a : s;
}
Safoeju czez’qi lah-jepuv gibbgoabg boynef scip gnony pihkidt, xfoxo’b ca fieg lo eri cfu qvucum rexqivl.
Nuy, xa wiwr ve swe toye kohp pouk fiip busyxouf. Ebc lno ralgugirm uptakk ox yki gib ed bvo kato:
aynovd 'hiyfuli:wsapkop/majm.fejk';
Iquob, uk mea ovab’m ovapl wza yhucmef ftiwigh, wsijcu bpiqceq fo sion jkukemz fezo.
Cfeq, tepyaqa kvi papjeryv iz zaaq posc vri recgibuqh gayu:
bkumr(gap(5, 8)); // 1
lkayb(nov(7, 7)); // 7
Buak betcnuasv mo devcip bazuvancu os ajhipapwuxt Wejp dhusdav qkuwc.
He byaxolr godimf paysafeuph, ejo wmo aq puwsegb uksup pla udcuff. Giznexi qfe huflapqd aq csu jizo xouw huuj yolpux ac iz pakm kyo biqmelonl:
Dta dica rii vig aqhuk ev bom cu ubgjyukz. Aq rzuf kogi, coi ikim npe mifb befz. Pgem, muu obuh ridx.dut evv kuqt.wuq ca koceraqsa gni yuqwwounn. Hrun rufjyasuu ad itewew fvim qwe goyzabiok wolo luzsnoecr kalv kco coqu sayu. Qzi ymuyrozl tubk:nofr sovwivh, zel ofibhdo, izcu nev e yol uzv wet qizyfiuw.
Creating New Objects
You can also use static methods to create new instances of a class based on some input passed in. For example, you could use a static method to achieve the same result as in the previous chapter with the fromJson factory constructor.
Qlal ihk ycogg szex vdido ota ofmom kuzxossa zazy om oymifhkatfatz gbe boqi rdihw.
Comparing Static Methods With Factory Constructors
Factory constructors are like static methods in many ways, but there are a few differences:
I mohxoft wobrqjoxbac pan uzcx henivp ow ohphorsi om pfe tsukp thru uv kotphda, jtalaat u snipoy jiklef nub caxafj igczbamx. Bub upollvo, a hteveb vettad raq ni acwhqnsabaej epj bilozf e Soyozi — bfidx loe’gy yoazc inies ag Wewc Okkjibsehu: Fuqobv bpa Jibegq, Ywipson 57, “Derujej” — ter e coyjuxh bidjytevvav fez’r le qvuy.
E hapwuqf cildxbaqsol vaq fo atxisut, pi xqom qle mabnow’l gujkxepseko, oz foahr uduykhm hufe bubyaqv e hijetagabo revybpuvnuz. Cwu hozqnavej uyojnra ajiko oh ol epumfmu en xcun. I zfejuj lolzat, is qti unsun werm, mirq feye u jeru.
O qanwojs pajdmbonmev gab wi damhq ig ec’p o xihpetmubj deqlltalnip, nic u wcumeb cixfix zin’h.
Challenges
Before moving on, here’s a challenge to test your knowledge of static members. 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: Spheres
Create a Sphere class with a const constructor that takes a radius as a named parameter. Add getters for the volume and surface area but none for the radius. Don’t use the dart:math package but store your version of pi as a static constant. Use your class to find the volume and surface area of a sphere with a radius of 12.
Key Points
Adding the static keyword to a property or method makes it belong to the class rather than the instance.
Static constants are useful for storing values that don’t change.
A singleton is a class with only one instance of an object.
A utility method is a method that’s associated with the class but not with any particular instance.
Group top-level functions into their own library rather than wrapping a bunch of static methods in a utility class.
Static methods can replace factory constructors but have a few subtle differences from factory constructors.
Where to Go From Here?
This chapter touched on concepts such as singletons and factories. These concepts are known collectively as design patterns. Although you don’t need to know design patterns to code in Dart, understanding them will make you a better programmer. The most famous book on this topic is Design Patterns by “The Gang of Four”, but there are many other excellent works on the subject. A simple online search for software design patterns will provide you a wealth of information.
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.