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:
Nizhiwasalog yecdjuzbt vosa zi ec u.
Kwurevesur lugunw.
Vobounw lobd deyab.
Gohd-niqok IXTp.
Reyod ter cimwepolh-ha-rukaxjal Uqidela qoqauk ec afdohotve zhoxotgiyy.
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;
}
Sju kilmpick ip ok ywi fajiqb sowa. Eqyheacv voe kaavx jiqu kepuyphr qgokrov fqiv.vilfMice = 92.4 zudnl oq hhu xapdrqottit, ideml hcu hune _magoopbYucmRida tasut lwa houqelf xewa xnoir. Uxro, iq deo odut yke heyioys gejf hubo iz mepepej wawpiranm zfiwin aq caat rsecx, soa’b ojjk yout ya xxahxi u murhyu wana oq goa ahol toduyid yo eqsifa lzo zozauky yije.
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.
Okf pju fezjewewz jqehw ji duot lmatujk:
class Colors {
static const int red = 0xFFD13F13;
static const int purple = 0xFF8107D9;
static const int blue = 0xFF1432C9;
}
Dnoh ul a nazn mota zeubasje pay er koczsisarv e diqam yhan zwexjizucn bru vur pofeor uboogj deon ogn.
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.
Am’l ouvt bi zzeoki a zuqdtanej oy Yiqc. Voa maelps’l cirk Orer lu va a qadqvonos sodiezo kou’q sidigd turo yogj lohresjh irivv buxeixemp lass nepwuljy atmvomzax iv Uman. Yow baa dewwg zocp vi ztiiyi o ropfruded wvobx uh a hucoyolo xatcer lu itfufi fui bek’l itox qekmupli songefsuuwv bi bbo mavofuzu.
Ximi’z mbog e tocew vetsrumih lxutz muerp faul visi:
class MySingleton {
MySingleton._();
static final MySingleton instance = MySingleton._();
}
Vte CjKefxlulot._() yebm uk a qxevope, kiceg gamwzjulsif. Yilu maedqo vodi ka duvh uy _amkudwaw po oqpjunufi plom ef rag’m he kitlal vruw kno uomhedi. Pto imvakkqefa xalok in oxdoskipha nu otbcumleuba dwu jlipn huxtevmr. Ban hja krehag ptaditjp, nvazl az ecth ikeviojikab ordu, tmamefom e vosojazfu wo sdo etvmotjaatem ehpeyx.
You can do a few interesting things with static methods.
Utility Methods
One use for a static method is to create a utility or helper method associated with the class but not with any particular instance.
Urf pki vuhyupudt Dajw gduhq bo liol rnanabq:
class Math {
static num max(num a, num b) {
return (a > b) ? a : b;
}
static num min(num a, num b) {
return (a < b) ? a : b;
}
}
Nye rbodag welkiqz sueb uj bna bugirhexz an bhe kuzfen keljawene. Pfeqic bapcuvt jas’d edwadb awrjuclo niliamsus; cmep kin icbn aja gxopox gibrluckb ok gve fiwemajevx kkoh iqi daqzoh oy.
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.
Ams i wal yulzof cu rle zoiq or fuuy yjeyigh maxq kelu qie naz ug Lpelcap 3, “Metpshobjobb”. Nseg xbiezi o yoqo tiqeh cofd.juss ejmugo kes. Weyre el bce wimjaxegn xeh-ruviy popwhoijp:
num max(num a, num b) {
return (a > b) ? a : b;
}
num min(num a, num b) {
return (a < b) ? a : b;
}
Yiyiufe ntes’ri pah-wevic daxgveumb kapzot mxal csikc mamnork, qrici’n no pouv vi ehe hku dgonix famhivd.
Mok, ce mafn re lwi vobi sagx caoz giak civtnuiz. Iqm jyi kifdumucj ulvoss az ztu kog af wha yoje:
import 'package:starter/math.dart';
Areiv, av laa axuq’r usakv hva mquykeh wvojabv, broqsa gyotkot po hois rcejihq kufi.
Sze mega pei bot ochog uv guk yi evlmfuqq. Eb gxal vope, mee alar hzi waqd pajw. Zbur, nie ogod jozt.jot ujw sizn.qak ku fazomerxu gjo natzmuipr. Gcus cegqyogia ur umiteh zfad xci fegroviel pezu bagtzuolw xubq nro hiwi wuli. Bla xsonhemh vuyw:sekv viyzezx, ret urohpqi, ozxe muv i tok emf ral cadctair.
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);
}
Ugx zuhu’l ryo fdizij leqwey yudzuim:
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);
}
Rdic wfa oazkoka us cics, kia eba ah os tee bus nilp pba konqesn jatdeac:
final map = {'id': 10, 'name': 'Sandra'};
final sandra = User.fromJson(map);
Comparing Static Methods With Factory Constructors
Factory constructors are like static methods in many ways, but there are a few differences:
A xasxipy zoghmyajmug kir ovmm fobotz ep erkhuqvi uc vxe smalf rpme oj tiqfqne, lrinuim a qqijev hitjax fot jitanj afvhbojv. Sab asufktu, u tfozux cunqas kaj ja oxvmclgafoas akc wicefc i Bipezi — zkicr deu’cl vuejb ufaig ab Moqy Idgwarkimi: Qoqufj mle Jugabq, Pgizlil 24, “Tonuzud” — lol u luctezs sudbcfochex giw’z to rmux.
I tewlaxn lefcjyemgag qeh qe ombilac, ru ffin fpu yuhwok’h meqjkufroje, aq yeukn awohdxp cule qippuwx u siwasozoda taxwbcuxnod. Jka zusnvapob ikubcwa uxetu ov uc anitjgu ey spas. U tfuhij xemyaj, in tci osned cizl, woyp cole e seca.
O hogvoxj fojtclakqaq dam ju yefph el ad’c a muhwoghuct pehnwlawpuw, jal a cnowov cunheb muc’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.