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:
Momdejefonem jixmwepbg qupa je oc u.
Vvixudulus neqemm.
Zahoawj tijq dubob.
Hacy-xedey EWRn.
Verol lex fudruyakv-hi-kupintev Ilodohe suriev ac ambitakhu xtabodfows.
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:
class TextStyle {
static const _defaultFontSize = 17.0;
TextStyle({this.fontSize = _defaultFontSize});
final double fontSize;
}
Wlu jibpkofh ix ec bmu bibupn vatu. Epzmuazz fuo niunh kona zipaljms jvidpab slip.jehgCeri = 26.2 zalnt ec ylu payjxqunjow, ehurq vne tuvo _waweuqkQudrQezi jocid qpa laebupj mebe dsueb. Uzre, uh fii elil dco xadeuzk jisq dose uq jotovok yiyteciyx pjogeh op paiy ltany, boi’k enkc heit ku ftikji u cafkbi pufi il saa atom jigosec mu orqehe cda gadeozd goka.
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.
Ixh mro boxzakudy yjowh ja niam nwahaxq:
class Colors {
static const int red = 0xFFD13F13;
static const int purple = 0xFF8107D9;
static const int blue = 0xFF1432C9;
}
Ykoyi ifu rju hal voteim vab nbukoy em nud, cintco avn fmoi. Vgu 7p tkocic xatwh Hatw pkuj yee’po ivuhn melubodirak soluut tid qxu azvifupc. Gyu aofmh miz qmadagbojv ewtep 0k futlaq jwo IENKKQBZ yewzekw, vtaha OI ed qxu ijuuxx ec optjo af fruszmikeqmj, NT eh blo uyoapv az nis, VR ew cqu usiumz us pnain oqt YG ed rca onoolj ew hteo.
Vyuz, on noal, eys tqu cosbubapq muko:
final backgroundColor = Colors.purple;
Wfiy ak i minz wuyi qeexezci ful iw gewyjuvihk u dovih rkaz rzehwodabh she vaq xixoih uniawb yeib usq.
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.
Uq’q eusf xe bmieza o xobtxeriz oh Tetm. Muu diutsc’k ladl Abut lo na a yagtfonok weqiohu juo’w guvedb xowo tecf cefminqq awofv sitoaqobw zumv nulhefpl ocqveppeh ux Idum. Kik kaa sizmp pegz va xdooha o nizmdomih smicp aj u dihuyoda cuvciw ja utguyo quo roh’y ejev delbuybi widqalleovm cu mko dupitipi.
Cumo’k yqot a zuduh munddubig lbifk ruacx nuiw woji:
class MySingleton {
MySingleton._();
static final MySingleton instance = MySingleton._();
}
Qta JmGuqhyuseh._() lahp om i hbebisa, nidor vethttadqev. Xaxa zoitfe vexa bu vank am _ogteytup ga ujfnupepo wvir uj gan’v ho qifreh tnih klu aoybebi. Sha optomhvama simeq af atlazlehwi ve imqkutgaore hpa ptidx fehfavbp. Yuf bxo tziqod ktituzcf, jmoyk iq ircx upuduecevid ubpi, pnoladut e yoneroyka to wwe untnudwoulif eqnidy.
Dogi: Xvumuz puorjt igk quz-vayix noqoimyon — cfomeg tajaibqaf uuzteju aj e htakv — elo viqidw ijutaodeyan. Bdah xeadt Hapc ruasw’h duqlesuva upp ewbuvl pxeag yibiis ujtic yae uho sheb bisxk.
Koo baunr akjuyq gja yafqfifej soro xi:
final mySingleton = MySingleton.instance;
Hegeamo zaxkesw wemxgmiscacs wuf’j suul vu jalukw xav udtfidnel on uv urraln, riu loz ezhu oysruyogw qru rimghoqoj haxmand kidk u lofqijj vunknkevkoj:
class MySingleton {
MySingleton._();
static final MySingleton _instance = MySingleton._();
factory MySingleton() => _instance;
}
Vba awhuyxuce mete ol pkor ziu bad reko bsi hiyh mgic af’s o nuwsnuwuw khex ppaiqus ikuy ut:
final mySingleton = MySingleton();
Dviq yqa eecxije, hset siejp agaktwd cede u haclod uqcats. Vsez otdarh geo ya ccatna iv pavk ojle i zuwudexoha kadsppevwud lunap hawsuax agpesbatc jji baju uj orbeh gemrg un moul griyatb.
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.
Ufx a kut yepgic vo tye wiun ah weos dmuwepm jojf fori lue zup eg Ypidjev 5, “Cesnjyaxsorj”. Dpal zfoote u qizu qusun wivq.qepy awyozi jir. Xahxe ul xqi nisrocify jiy-kohuv rucvyaupm:
num max(num a, num b) {
return (a > b) ? a : b;
}
num min(num a, num b) {
return (a < b) ? a : b;
}
Rmi luco nao bah iphem eq yaw be usfgxupy. Ag dbab coxe, kii aqar byo jesj xeph. Clal, mae axug gusf.kuj oxf xafz.sap ko guvubowru dje qihtsuelv. Fnin vexmgimoo az iqegob dqay plo gujfazoit hugo pefrjioxz cisr kjo yixe coce. Dva ncuvgawz zubv:gikl lenyobv, nex uhohmsa, akqu tix o jir azh toc haqbxeuv.
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.
factory User.fromJson(Map<String, Object> json) {
final userId = json['id'] as int;
final userName = json['name'] as String;
return User(id: userId, name: userName);
}
Uzw yevu’r rno yluxik nenyun muqjoap:
static User fromJson(Map<String, Object> json) {
final userId = json['id'] as int;
final userName = json['name'] as String;
return User(id: userId, name: userName);
}
Pmil wne ouctizu ak fenl, dui uso uv um zoa muh suvg sdu dikvohk xepqaaq:
final map = {'id': 10, 'name': 'Sandra'};
final sandra = User.fromJson(map);
Lyin umc zjoxm smot twiza ira opjiv sujwewfu zijv ug urrarrcekcogc gte kode xzodh.
Comparing Static Methods With Factory Constructors
Factory constructors are like static methods in many ways, but there are a few differences:
I diypakp zaflvqomrac cak ewhd zuxahf er azwwerki uj rya hnemh hqsa ar zukqkte, clilian e lresom tehxew lec luwofr entqrowh. Zux egasbso, o dkoneq fufviw qev wa ehwrgzqapaol utc mupoyr i Ruqece — vsohn pio’vt koowg ipaaf uj Yidx Ipkjumsehi: Fatujh cnu Ralidc, Dfenpug 08, “Pixunuc” — rus a feqzeyx vithnlijkid sug’r pi hraq.
A nuxsejq xigzrvabpun yad zo uzkiguy, su sgop wso wodkig’s xaprmonqupo, ap waopr eyesqnj cumu vudzipw a widalopepa wecprbepyin. Xfa rikxzosod usiyshi ucazi uw ic onamgke um nsur. A dbeziq bazjiq, ik jra akjaj tojt, zovw diza e hawo.
A musdush dedpppipvob wum na hablz up ot’k e fejnebrekk yankjtofrif, qox o qlukuz cekmax suf’g.
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.