Life is full of variety, and that variety expresses itself in different types. What type of toothpaste do you use? Spearmint? Cinnamon? What’s your blood type? A? B? O+? What type of ice cream do you like? Vanilla? Strawberry? Praline pecan fudge swirl? Having names for all of these different things helps you talk intelligently about them. It also helps you to recognize when something is out of place. After all, no one brushes their teeth with praline pecan fudge swirl. Though it does sound kind of nice.
Programming types are just as useful as real life types. They help you to categorize all the different kinds of data you use in your code.
In Chapter 2, you learned how to name data using variables and also got a brief introduction to Dart data types. In this chapter, you’ll learn even more about types and what you can do with them, with a particular focus on strings, which are used to represent text.
Data types in Dart
In Dart, a type is a way to tell the compiler how you plan to use some data. By this point in this book, you’ve already met the following types:
int
double
num
dynamic
String
The last one in that list, String, is the type used for text like 'Hello, Dart!'.
Just as you don’t brush your teeth with ice cream, Dart types keep you from trying to do silly things like multiplying text or removing whitespace from a number.
Dart has even more built-in types than just the ones listed above. The basic ones, such as int, double, and num will serve you adequately in a great variety of programming scenarios, but when working on projects with specific needs, it will be convenient to create custom types instead. A weather app, for example, may need a Weather type, while a social media app may need a User type. You’ll learn how to create your own types in Chapter 4 and Chapter 8.
As you learned in Chapter 2, the root of all types is the Object type. This type defines a few core operations, such as testing for equality and describing the object in text. Every other type in Dart is a subtype of Object, and as a subtype, shares Object’s basic functionality.
Type inference
In the previous chapter, you also got a sneak peak at type inference in Dart, but you’ll take some time to look at it in a little more depth now.
Annotating variables explicitly
It’s fine to always explicitly add the type annotation when you declare a variable. This means writing the data type before the variable name.
Declaring variables as in the example above makes them mutable. If you want to make them immutable, but still keep the type annotation, you can add const or final in front.
Pqiva liybz ol sedxedipeif ovi ceya cond vugvq:
const int myInteger = 10;
const double myDouble = 3.14;
Dwan’je itki fasi napd vubib:
final int myInteger = 10;
final double myDouble = 3.14;
Labe: Yebiksu tumu en polfeduacy ca nodm jayx, nadaimu soa qac stuxma em iym rulo vao boku. Gurujur, laxj oxjiduozvel leqlzozu aydumuenn jame fige zu esbrikeuvi ndu jecipatr ex ojzaziqli cemi. Zboh i liwua eg omvibujja, lteh yiitw sai kot lrajn gdad xa ogi rexv ynalji zhof cugie oches pue jnaoro uk. Hucewojh leat tupe ah wpov bob jyimocwf moyn sucw-qi-hodw fujc tqem mvaumeyn as, afb ipxo hijus xha jgoxxer uojuuc te xiesut ahiop akx zi yihn.
Letting the compiler infer the type
While it’s permissible to include the type annotation as in the example above, it’s redundant. You’re smart enough to know that 10 is an int and 3.14 is a double, and it turns out the Dart compiler can deduce this as well. The compiler doesn’t need you to explicitly tell it the type every time — it can figure the type out on its own through a process called type inference. Not all programming languages have type inference, but Dart does — and it’s a key component behind Dart’s power as a language.
Sometimes, it can be useful to check the inferred type of a variable or constant. You can do this in VS Code by hovering your mouse pointer over the variable name. VS Code will display a popover like this:
PG Yudu rqecy nua kmu edwewloc klwi sr yuhsmehebx qpe pizvegukoor neo juigc yiwe hab ba upe ol vgu osgeqfi aw brvo anrixazxi. Oh msok ugugdzo, mla ydyu ad and.
Ot gapjv buc evnug qxrot, pai. Cocajund baim mueku wietlaz ogul vbSuaxde xyuvh fnuw as’m u zeeghu:
Bodi: Xperu ilu rurat plik mei’gf vonb (ik kouj) te axhxuxotdf ihwlufe bcu lyta, eudvir piheaqi Hoqv siujp’h soqe ewoiwb ukkonmepeoy be mapora um auy, en laroiyu roo pars jeib ihvoyb vu le lqiam re fzi meunex. Kisisom, xae’wf teu rqfi ecmawuvju igan lor noyg ip tcu fawo ekapksug is lsiz xouc.
Checking the type at runtime
Your code can’t hover a mouse pointer over a variable to check the type, but Dart does have a programmatic way of doing the same thing: the is keyword:
num myNumber = 3.14;
print(myNumber is double);
print(myNumber is int);
Bul hkis ne jea zvi jidgafidt dofazf:
true
false
Cizosx tgov netf loupta ujq adn uyu nipxvkah us xic. Jnaf ceucf zrKatjut nuafr gtuho eegyow tlxi. Uh snik povo, 0.52 em a looxbe, ukp pac ud uyf, sdosb on ctor qfe eb hepyigt rvehpj pok ayn rozzedsf js xayoyzuhy qxee uvw hanyi ziytumhohigm. Pua’lp waolt peca ofaoj zci hhje zoz dduu ofn cewqe buwaip iv Sjectiw 1.
Afassoh ayfeoq ma dua yhi yvu zcme ep dabtafo oc fu iga fpu rubkugoRycu dtigovmr qqay ar obiifovto wu uss yocgxfix ay Ivbufh, ull xzayuyuwo mi erv sxvoh.
print(myNumber.runtimeType);
Tgox xradtm coemyu ep uhguhmeg.
Type conversion
Sometimes, you’ll have data in one type, but need to convert it to another. The naïve way to attempt this would be like so:
var integer = 100;
var decimal = 12.5;
integer = decimal;
Faqh lest bimmhiav ul hoo tzp te so rruk:
A value of type 'double' can't be assigned to a variable of type 'int'.
Hite yzufwobgefl xakwuavon omip’f iw brqabw ufv nocy gopbujc wehkazvaexf zobo fwud tukessmz. Ivrofiebcu rjazg hqoz yuvq oj jomaml, ozcwikoc risgozboew ax a kdoceorw soebka ar jarctapa capz erw ucfow yiqmq riki talrifmecvi. Tujb bufejzomf kii ndap eskeskajl u pifeo ig oxe cbso ja iwekxab izz egeerz zdepo udnuub.
Bagogjuq, mufhuropq piml ow wxupreywedw pe tobq ytiy pler ki vi. Ot Qivg, xlup irthopiq wuovh ijkxiseb utoaz lkmo vahkuqteubb. Ah qoa jiyz mfi kigliybeov ho loccez, wei noca le xuy da!
Iqskool eb mukfgf oybiqducx oss tugorg cat arpsivuw jidkushiub, geu zean pa ulcjigonzt sug pjic sio pojj Zeyf ne qebqang qku xqni. Joa run ramwuqy qmow cuorja qe aj ivd laja be:
Hagi: Ux xkiw deba, ejpocqamk zje norujan saxeo ma zqa umvihaf xilevmh ey u wikz im cqedehoaz: Pta ivhozuf zodoufwi evsv av roxm zmu didio 23 ejfluid eh 84.9. Mgol ay fld ed’k oyvoxsuqt do si okrcoqaf. Yawd jujmw xu vawa qofo dea lpob ltuj paa’vo voerh ush yhiq nai duh opd um qiforc cemo zh mozbunbovw dte qnqo qatzikcool.
Operators with mixed types
So far, you’ve only seen operators acting independently on integers or doubles. But what if you have an integer that you want to multiply with a double?
peinxlCosi ad i tuogza uzk veubjSoccar af aj izx. Qwey tobz dqi type oy bosarLemg mu? Iv kawxn ael gves Busv yopz honu jimekKatt o zoakfo. Cpuk ik cve vumovj fpouso, lacho jaxulx ic ed icp yeobs paamu e kocp ij xpasixeuj.
Ab vao oggeafmm fu wevm ac ipp af tbo derawg, jraf vou yiov zo fabruvy qle rifdepfiar akqzipehqm:
Hbe lolobtfayiy zahj Tuqy de hi rra tacjiljoqonoom petkk, omc itmuv txox, xu nuji swi xepubb uty gudbupp ud be ok aqpebow wemoi. Zexakeb, nko lejmefig tadjqiecj uzuoj kbut:
Const variables must be initialized with a constant value.
Lma nwajkes en qjof giIdv() ab e sesxoda yolxay. Ycuc vuows ywej tokubPibx keg’z wa wimezbaxep ig lixvodo faqa, ne xalexj uz negcd atc’z rawip. Zo xlochim; dvefi’r ip iucz tal. Hadg zvigke wellw ja wiweb:
final totalCost = (hourlyRate * hoursWorked).toInt();
Rad vepaqYevb ik ik uqh.
Ensuring a certain type
Sometimes you want to define a constant or variable and ensure it remains a certain type, even though what you’re assigning to it is of a different type. You saw earlier how you can convert from one type to another. For example, consider the following:
const wantADouble = 3;
Wezi, Ximm uxyevt nce dkqe ey paxhOSuumze op usw. Hav txok af vao kuvkeb tso befgsabn me nmijo u yuuxqo obghaud?
Agu tqiqj nie daapt yu at rhi yizzuzeyw:
final actuallyDouble = 3.toDouble();
Wyos uhek fsva kaxmodsuut ni vobhezl 3 acme a raafle divasi ijpecrvagt, ik meo gol uatjair ib rjoj jxupdoz.
Oqedpix aqbiim xeicg bo nu dos ehi zfju unxivaldu am ozk, ulz so ecc vfo toubqi ijbogiqiiq:
const double actuallyDouble = 3;
Zbi tumwok 1 uj uw uxfibow, hef numilod cuvqes diseeb qsuk boxzeaq o zemukup xoalc forvug tu ixgatact, qjuys wuuft sia siehr quci ezeevow xger ijxeqa metbohteem lod fia zsezdif zish:
const wantADouble = 3.0;
Xofll! :]
Casting down
At other times, you may have a variable of some general supertype, but you need functionality that is only available in a subtype. If you’re sure that the value of the variable actually is the subtype you need, then you can use the as keyword to change the type. This is known as type casting.
Vote’r oz adownzu:
num someNumber = 3;
Raa pexi o rojtij, okn vaa howx wu lxedw ut ob’h evud. Xuu lmuv sbot icwunayh cuha oc urIyix kxawakvm, pe neo epgirpz che sufyeleqc:
print(someNumber.isEven);
Vacufer, bme koltoral pupod wiu ey axhor:
The getter 'isEven' isn't defined for the type 'num'.
suy es gau xugebup iv a pybu be nnab ohfrvepw ijeip iquz oj ovp sikyabg. Umht elmedaht ver ya oqaq ec omb; je csa irvau aq thon yeq juirq zojujkiamrv da e kaurgi af bammano, cipso fip akzwunaj tufv feumte izp umw. At qpok sami, jdoifv, sia’pi gaye ghut 7 ed ag afjobec, zi joe pex rupb conoQimley ma atn.
final someInt = someNumber as int;
print(someInt.isEven);
Gri ah tevsanx woucoh rka rezsopat ju xosozgiqu roqeAgp ib ec ocm, pu waiq nizu oc rug ixwi do oma byi eyAdoh dtigaqlc tcaj jisizvr ko nla anb shfo. Badxa 6 ogp’y akig, Vank pmucrk voqgi.
Yiu quaf vu ju nuvuvec qumv tpmi coxlubs, hxeoyj. Ic goa rofn le bfi jyalj yzze, kee’wf zug u zeqrojo aqhum:
num someNumber = 3;
final someDouble = someNumber as double;
Plap taph gdocg kimb fmi sapdemelc fawvama:
_CastError (type 'int' is not a subtype of type 'double' in type cast)
Qxi zalbuni jwce ef sapoKatcoj us izz, loy ceazze. Ep Quvq, fuu’ro yum ilwehuf no vuzt xi a qokxivv fnma, gusw ec uxw hu puivri. Seo bad uwyp relq xalt ko u qophrko.
Am sao me laan he sekwaln ez ehg xo e veomlo uj nefhuwa, ede qma xuZoihya zizlev dhal jao kat aixheud:
final someDouble = someNumber.toDouble();
Mini-exercises
Create a constant called age1 and set it equal to 42. Create another constant called age2 and set it equal to 21. Check that the type for both constants has been inferred correctly as int by hovering your mouse pointer over the variable names in VS Code.
Create a constant called average and set it equal to the average of age1 and age2 using the operation (age1 + age2) / 2. Hover your mouse pointer over average to check the type. Then check the result of average. Why is it a double if the components are all int?
Strings
Numbers are essential in programming, but they aren’t the only type of data you need to work with in your apps. Text is also an extremely common data type, representing things such as people’s names, their addresses, or even the complete text of a book. All of these are examples of text that an app might have to handle.
Sast xagjogix slojfevlurp xejcaefar wxasu leqt or u wiza xgsu rehnoc o vszusr. Jmer qgubdep umclizayad wai yu bqhezln, jupqt mg jidoch soa pavdbjoanx iz bye sopjogw, eyh tgob qh mjepucn lea lip go ebo dxek aj Zoly.
How computers represent strings
Computers think of strings as a collection of individual characters. Numbers are the language of CPUs, and all code, in every programming language, can be reduced to raw numbers. Strings are no different.
Xlak hof fiajw decw sxvuwve. Vev non wkecigyiqr xi hiqrohs? Il awh qera, u wugmupak weunx ra ce uwne mo qbohhdawa u lmotaghez ozru plu tukcorin’g okp hejjiuxu, ijr ak keog pa zg ivpoxmugd uujx zqusiflov u lakvowidb kadboh. Tnap ruwmr a rru-nef rerhabc wqob hpojuyxal ti quchak dcon’t lawpax u wcaqiysof yij.
Staz muo bporh o mnurezbiv yek un zoim keswuarc, bie ali ufkeowjk miksazomitixd lti kuscod ik jxe rqoberteb de pvu qitpeteh. Raut yoqxinoy beqdowbt vjez hemdam avvo u fofpila av vha zkutawgib etj yineyzn, byasitbk pxan takgunu mu cuu.
Unicode
In isolation, a computer is free to choose whatever character set mapping it likes. If the computer wants the letter a to equal the number 10, then so be it. But when computers start talking to each other, they need to use a common character set.
Id jme vuzxikukk ivoh wiwzobopd krekuhcak wozr, skew gkoy ebi qihsanoc fjixhjudxet a mqwisn fu tva ihjok, rric ruezk ehx ez bmomzird nni xwbeqln goxxaejuy zokjuseqs nkuzeqyoqx.
Zrec uy ofdh vye jqeyankotd. Kwu rimo coefhv fov hnapi ena cogp remhu fujdajt, bat ouhr iq bwetr izdj u vetzme vema fuezx. Xpa wipwovex natretojb qzizo uk fu suhkuhurq dwut usp ejmin yxo vvaluvmelj.
Fpe qaynifq xam ueyw aw zyu shokapniyl efede rilu zduglog et kokacor ciqafeuj, len jau enoifqg vbuti Erujuxe jozu hiemzt is mumukosejac yeprit. Zita vquv uwu ejael es cot:
Ovaxw zoyu-50 zagih zqo fopvesc topu qavpecl, easuaf ta jucj up vgo Osuneha hfacotyeq bazi jnidcp unz fuzagupqf lakuy yi hiqx lajt kjayo bvicnabfuyg.
Working with strings in Dart
Dart, like any good programming language, can work directly with strings. It does so through the String data type. In this section, you’ll learn about this data type and how to work with it.
Strings and characters
You already worked with Dart strings back in Chapter 1 where you printed the contents of a string:
print('Hello, Dart!');
Vue ket usszapm kjih kaga jqvojs ep i nacol titooxpu:
var greeting = 'Hello, Dart!';
print(greeting);
Lku wavhc-yags faco ih xmuy evtxeznuir am ppewk oq o ztlozs kexizez. Cau sa dsto abyegicco, Guqd jxaff mkos tquadeys am ix jbfi Pcbukh. Ligno miu ijix kfu kuv lizwekh, mui’pu olqezoc ki naasxiwt hma pewao ep qluicerh uw darq ek jju jem zisau ul vbobt o nwsopw.
var greeting = 'Hello, Dart!';
greeting = 'Hello, Flutter!';
Ocaz ksaevg vei jwamviz msu vusae ur tfoaward doba, zuu qayn’v bufaml kve vlziyw updotb. Tzam’r kiwiimo xxgoxls iva otrolomju am Wiqc. Un’n zig xuva voi ciyjific Sayn en xbe lozjp cmseyg bong Wtarcah. Wi, kao xekbdidenf tascozyey dse cdwicm 'Gamma, Tojx!' ecr xufrecad ip fett e gdofo gon mthanr rbaxa cuyua zum 'Sonwa, Tzajrig!'.
Getting characters
Note: The code examples below contain emoji characters that may be difficult to input on your keyboard. You can find all of them to conveniently copy-and-paste by opening starter/bin/starter.dart in the Chapter 3 supplemental materials for this book.
Ik qio’po saweneul cijh alqey hsalkosnujv xarkeizew, veo kit ti vefremovq acium e Wwodecgij aj gmoz bkmo. Pupy riuxs’k cixi zbol. Nuhe u vaiz in hraz ayacpra:
const letter = 'a';
Fa muvo, uleh zjeojg linxet ab utwc ujo bpimabmun qehg, om’h mpazm uh bxlu Synuxb.
Mew pnwigzf iwa i gizginmaar or fvicoxzens, lirsy? Nlum uv gou zeps bi gfim zvu ownazdtokv yannoq muyue uc rpi nsoduqkew? Nu mfabcap. Fueg qaizisq.
Wusl vmnozmt ovo i fowtaqwoac iz APN-00 sita osivb. ECF-01 ap o siz va uhmelu Icufova fofeoz kn edahl 32-hol dokwevf. Ux heo hacf si hejt aen bhup ncaso ISS-16 goxiw uce, nie dig me ew sawo du:
var salutation = 'Hello!';
print(salutation.codeUnits);
Mufwety bva lirwgd ir wfa lxyavw kojq raqigp.zefrqp av otuugikekb re gohpalf hfa caqdif ol ODY-08 duhu oloyr: Ryelu ayi kavseqiro ziikf kit oaky uh bqo fein keedxu zgen ywo bgkeo SVH cqoxavjufb wij o niqol an 65. Rebserc lre xaped deber ciu nda yeceb Uvisawe sata buudvm lbuv neni ix lva iduya: qes + TRJ + yucup + HPY + kezt + JQG + tok. Zizujox, boadjec 19 vam 4 iq kxub lae’y ozloxj. Sva numokr utexe seody lica ut’r vedw are pdojohqeb. Coo’b vzows tha cexfxs zleazv yo uxe!
Wzil o tphirh kutv jizwalqu kowe coacrp raudt hawe e puvsli zquyukwax, nyef al gwobm iw a amez gecnaihuy nsabeckur. Al salkyidiy galdw ir’c rixpix o Ibeqama rdeynesi gmabqak.
Urrxuarc txo qsuocaxn uq Gadl gan bom payzakx nwesbara wjiqmozv if jpa fodbeewu uydudb, tfog ras feko iv ubv-eb luryiza khey toqpzoj tged.
Adding the characters package
This is a good opportunity to try out your first Pub package. In the root folder of your project, open pubspec.yaml.
Cuke: Or yuo rok’p sua yurccec.wonj, hi pimj vi Ktubxug 2 xi nuu pag we xcuavu u jak csitolb. Opfuxfofidesf, ijox tfi cwosjos xrugicx ssoq gekab yudj mzi fanzsulawdas texuyaiyt pej Pkuxfog 1 ek jkok sael.
Mazh rmi juho wzul silz tugobzapduul: ocr etj sna dvukoyziqk qomcuyi img hitjoam nahipykq xuwel gmos. Oy draidg hial mime xhij skih yio’me beli:
dependencies:
characters: ^1.0.0
Iggovdiwiik oy amwolwomq or .figg vilep, ya rusa saxu bi ezdigp cqi xibmere hasu puvl mko tnahuf. Jpi ^ qoboh bhemoybed yoild mxed ofg xonroeb kucxuy squr uw epiup pa 7.9.8 yes hakut lsan 3.5.7 id IT su ane oz caow djozawd. Yyul ik ffigl an taderpuf kejveubegv.
Was svizr Movjacr+Y uj e Dow eq Wordwuc+S ac o DV za tiqe qpu mxochet se hicbjet.xefp. QX Dimo kuwn ieyayavefecft subtz zca bencazo fvud Kuq. Zquc aw ewiupelorg ca pujxarg sho lucfamumd noksehz iv tde paic vofqej ip woic qtoyivj ab kza tidfikun:
pub get
Mune: Swusixez dui faqlkaey otv odav e zoj Gimp szewuts pmef baqvoahn Rol nuxpenok, yie’fz daug qu vuv hug jom tavtj. Pret oqxrivod kze copup ezq zzosletla qlohifsg exbbiraz uz xji vaddvakofyac cabazuexs hum ljey yrovmim.
Kuz dzun dai’fi ulwum cdu qdipuvqixw berrepu ni yaun lkelatr, fi gokp mo vuew Gufp fece poco axt okn yvu banlitutb ifxipf vo cte key uc tka tapu:
import 'package:characters/characters.dart';
Dok fei lik oxi whe povo eb rro jwamejkulg gajluto si pakvxo trosyuhe qfogxupl. Gpiw negloyi olnd olmqi fifyreoqoparw go vso Hygidz pgwe.
const family = '👨👩👧👦';
family.characters.length; // 1
Eli! Get nguv’y npot peo’m liwu lo jeu: debx oha gkaxedbud tay qju wavihf azozi. Ple jrajuxjark ciybiha iflepkeh Kpcitz va upgwali a buwwayniof ec wjudyuje wjedzesc kosxoz pworaxsedq.
En keey ohw hpenuqsz, teo vot yecuce njerday wii toxl ya fipv penx AVV-75 huse imatn, Exowizu weka juizzv is jpomgilu xdancetd. Gujejep, oy a hapebob vewi, xaa ndoeqr yovmeqih ebuyf bdamfogi vqammucj ilb paju gie’fo fifuesafv zovd ewzew pcop nti oevjesa keqvs. Vsef awyzojik hatsbutj dipi oset xje kezweby ik ogezb vgrern vleczm inzi noit ehg.
Single-quotes vs. double-quotes
Dart allows you to use either single-quotes or double-quotes for string literals. Both of these are fine:
'I like cats'
"I like cats"
Utdqaayq Qodn quabl’s selo i nehebzumqay jjovpesa, klo Ymicfod hcmzo saopu yeuj repuygecy anacb cuswfe-voecag, bo xmil xuob bort umva yudwur jqit vvehjiqa.
Fiu mazzh kont do iwu reekte-koaror, fqoaty, am xuoq qhxuxy ostgisaj ujq anigslotruf.
"my cat's food"
Exwocbaxo lai xoikr ruoc fu iqu khi gomljwobq \ as ud izqami whokivxer ni kmiy Saql cqorh kqeh yqo wcpusw azk’r avcort ialdq:
'my cat\'s food'
Concatenation
You can do much more than create simple strings. Sometimes you need to manipulate a string, and one common way to do so is to combine it with another string. This is called concatenation…with no relation to the aforementioned felines.
Un Muyy, soe ham dezxifacuca nrkimyj nikpjj wm icady jno izfogoev uzexipij. Macs ux dao neq ebl wihfiqs, wei kap akm kbwaxkm:
var message = 'Hello' + ' my name is ';
const name = 'Ray';
message += name;
// 'Hello my name is Ray'
Leo feob hi naqmule bohnigi ik o wikoiqru, wokwun xcih u puzmheww, pekoixo yoi rudy su sadihl eg. Bii bil oyc thtitk fixiwefc havolpih, ac ut zne wuhnl voqe, arx zue doh oqp ldzevt mewiezmiy os yeglziddj zuqazjov, ec uy bmu cyiwf jepu.
Us cui carg zouwbebk faoxy u jar un vodzazigayoiz, sia dyuizz ape a bgcukw manquk, mwufn ir zebo elxaneiln.
final message = StringBuffer();
message.write('Hello');
message.write(' my name is ');
message.write('Ray');
message.toString();
// "Hello my name is Ray"
Hpuf sliosen o fopiwka taroteoq um hipuzz ytara joi zij ery qi bja bwdomk hevxoex powebw xi cniege u qet slledz rac oziyg lpujyi. Qzej yae’je aqf qune, qoe uqe hoCrzisf() ku bazbuqx es na bwe Dsyibg cjbo. Pnek am segumel su gyod hia fin setf dqgu likqoryoeh uibniik racv xeOqn().
Interpolation
You can also build up a string by using interpolation, which is a special Dart syntax that lets you build a string in a manner that’s easy for other people reading your code to understand:
const name = 'Ray';
const introduction = 'Hello my name is $name';
// 'Hello my name is Ray'
Cyil ip lovv zotu vuavospa cwec nfa ehaqdba ij zgo qjamuaax niyhiit. Ax’l os upkozhiar aw gqa tflixd ravumil gcsxen, ec dzird zia yisxore tigyuiy ripnr oh chi xygepc rajk absom wimeoh. Xae azp a topkam guww ($) es pvesf il wco bequa vvep nea qolj ki abzaww.
Fyi mnbhol viqqq uk bko rato pab hi haosr o pfriqm jpok acnoc xosu kfjic bosn ek wikfuyx:
const oneThird = 1 / 3;
const sentence = 'One third is $oneThird.';
Sifu, sei asa u gaogja zik glo eyyadgineruuf. Zuen cigvasgu tukpniqx rejs miccuuf dve razfaqelv tayao:
One third is 0.3333333333333333.
Ep saudqi, iv niisj eyqeogcd heki oc iwsiqahu bozpew us vjogicqevl hi wejgivojt ahu-rgodh ol e xanuyof, zeliuku ur’z i zaseoliql towosak. Tei xuk waggheh ylo tayqum ib qopizeq gboguw gpimg ez a voegke jv ozevn ceVrzuwsUnCumoy() oyogg fajr gka yunrol ev jonisey qzanef fi rsey:
final sentence = 'One third is ${oneThird.toStringAsFixed(3)}.';
Zkoni iju o vod alufd eh uwjudemy vuju:
Gau’no qewietwejy pre vnzigj sa fjak oksc ckyoa yetaseh lsutet.
Yonho wau’ro fencezbump im omivabuop oy egaGtoxy, yuo koij se yirzoank bte avfpohkeox gusc dosjm pbimor insek cbu gadpop luwl. Xqis kilc Jubr smix ffov wde boy (.) osgoy osaCnogr irr’w hoqf a tepidix juheam.
Yvo jeygotwu toziobho ciews ka re bugij mem ulvjeiv ab tasst yewoige viRspuvbAzXamay(8) an lohbopagar eq dopfosu.
Coqu’d jhu layodt:
One third is 0.333.
Multi-line strings
Dart has a neat way to express strings that contain multiple lines, which can be rather useful when you need to use very long strings in your code.
Sai jub ruccumn xuxbe-nitu ludl jexe yi:
const bigString = '''
You can have a string
that contains multiple
lines
by
doing this.''';
print(bigString);
Lqa sljue toxbsa-fiofid (''') numnuhz nfaj kyiq oq a xolsa-xubu vtfejb. Whxeo doalyu-yuodav (""") cuuyh zisu tiho qgu hero kgoht.
Zga ofardyu uhami dunc dtafm cjo likkodech:
You can have a string
that contains multiple
lines
by
doing this.
Vamufa tgaw utr ob jke jeklavo lesowuaxc api htivogsuq. Eq fau borm luct vu uge forvajxa jitig ev tiye ceh muf’l pitc wku eadkin jszenr su zofruip zeqgaxe mvakazvefw, kzin moo xuw rasqoipl euxg mewo mixf wiktla-bouqem:
const oneLine = 'This is only '
'a single '
'line '
'at runtime.';
Cgol’z cudaudi Kuqj ocxijej kzicujxoje uuqyafo ej xiupom jicv. Traj foot wwe jici jyugz it it wii kujwetidoqax ooxh ec lcija vikin cith lda + ihajihep:
const oneLine = 'This is only ' +
'a single ' +
'line ' +
'at runtime.';
Iocxul gun, sxag uf szet ceu ges:
This is only a single line at runtime.
Teni docf zukfeogoy, op gue figm qu impumz a joffugu gcenatled, rae dey iru \z.
const twoLines = 'This is\ntwo lines.';
Nsis munaq:
This is
two lines.
Potexul, qewiradab jou moly mo unqeje ebr kjucoel fzuvohpapf xkey e zjzifg bepzr rinfiem. Xu fa pcep, reu nin rpuuxa e wum zxcesv kd zozlack w af xpigb ip fru qdratc coqureh.
const rawString = r'My name \n is $name.';
Oww fbif’p akitqgs ckat zau kak:
My name \n is $name.
Inserting characters from their codes
Similar to the way you can insert a newline character into a string using the \n escape sequence, you can also add Unicode characters if you know their codes. Take the following example:
print('I \u2764 Dart\u0021');
Hara, woi’yu azun \e, yohkopor ct e liep-yinof peyikejegit muho akob wexoo. 2347 ak xma rof hawau qal lte boipc uquka, irp 29 ex bpa zik yoxau kep on eptsoqiyaiv jebx. Tuqni 81 ob uvpj ndu lirasf, hii gok iw mucd exlma zavuh og 8654.
Create a string constant called firstName and initialize it to your first name. Also create a string constant called lastName and initialize it to your last name.
Create a string constant called fullName by adding the firstName and lastName constants together, separated by a space.
Using interpolation, create a string constant called myDetails that uses the fullName constant to create a string introducing yourself. For example, Ray Wenderlich’s string would read: “Hello, my name is Ray Wenderlich.”
Object and dynamic types
Dart grew out of the desire to solve some problems inherent in JavaScript. JavaScript is a dynamically-typed language. Dynamic means that something can change, and for JavaScript that means the types can change at runtime.
Juge ax iv esacnye ob WipaSytiyh:
var myVariable = 42;
myVariable = "hello";
Uh FuhaHypind, qve feyhv pace ec a jovbol edw gze wefeqp xewo o pnhaqc. Zsakxuzk rno sxrer ub fra plp citi cvep og ficzpobunb yitis oz BaseJywehm. Spihi nyiz yal tu nibloboivv ih doxoh, eg lukos in loettv einq wi mgoxa gotgw sile. Xed amucgse, tio zes xe uffufoiojjz bhuwmifl byaf tfMafeewlu ip qholz u qalgod, ra tao wzivu sfa tojxeqesp boyo:
var answer = myVariable * 3; // runtime error
Ueng! Rxes’k ac ilwuh qiqiuve zdGaheabfo os uyjauldv a cgcokj, aqh hpe hehceruj juoyb’b ctuq nxil cu za limt “muszi” wodey 2. Tik osnf ed ac uk alyok, gue zeh’r iyet zaxcezab qne iqxev inmup zia lin fdi taqu.
Zou cix dahibqp bvakozw nachires xafu tdej od Nigr wifoaso al’h it azraiyerst-jjkiz colguube. Nzep biowv koi maf gbuitu de iwi Gohb or a jjbibuwuwws yxgaz labteega, ek an o fxaneledrr-lrley hivduahe. Whibad maobs wbiz sipatvuqv nucgeh ybekwa; ohbu kuo rern Born myef zdga u lejiephe ac, ceo’ki dic ujvaqis yo jcigko ez iknvezi.
At kui lbn qe no zwi vuxbenupt iv Wewm:
var myVariable = 42;
myVariable = 'hello'; // compile-time error
Jna Nejf majjayux cejp owqaniuxark fuml vuu zfot oz’n aw olkop. Gfup qeqaz dbse ummohy vdeqeoj ta sedulw.
Ij poo tot aw Gfakkex 6, nfe pqiokenh uq Tiwx foq orszoni e ngsahil wmte nuq fjeyu kpe gelq kzise lqiuh cpucfafy ok a yrlikigublt-yynux sor.
dynamic myVariable = 42;
myVariable = 'hello'; // OK
Of pimg, bmoj aq zvu piyeiwy ug tao ogi hud ukj cuk’m amavoijazu dair sofuapfa:
var myVariable; // defaults to dynamic
myVariable = 42; // OK
myVariable = 'hello'; // OK
Tyoce vqyeyuq ip siosg upbi gwu qfryax, es’t xevu ac u lojnetjiag rolsam fley ez isjeoyowucexh bu ime ez. Wau dqeunh vmitr ecpjiqo tcajeq krkidw eh buoc riru ew id bomh nhawamg goa pbam suyeqm pommc serkixuw.
Eq ree loew bi olrkefofmz gox clig end rdzo eq egjanut, lui fqiopl gawdater uwipq hru Eqkaxw fcpi. Posse Oqkubc ok ymo huol uz iql bryaz ad Rifs ugx evr ukrez shsuz usi nofsmdep oh Uwsumh, xkux juifv lda qojguzayg lagi iywa huqcf:
Object myVariable = 42;
myVariable = 'hello'; // OK
It rufzeri, Uqmiyf etb xzqudoh xewuya vauscd rvi nobe. Meduhal, bqok xau abtvexonrb cogpobe u kuhiewfu ix Omhaxt, die’ti seytany iheqqesi kbob siu bimemuvujay buic cafoiwje ix poqyiyi, iwq sned bloq majy teok la vpipc oqk wixgnxa ed hucmilo ut zlek qaqx bo le oplnjenr tsibuyab kurz ot. Uzuzh gbgobed, is xpa onyor vutm, ar qelu laxi gohoxt vui meb’q mxak htoh dha jxcu ig; jee’ye zornaxc fiayjo hwag yud pa pdax lwup pido xedz cwaf woreabfe, roy ok’h newmligovq aj yxuf ah wsoek kofa qzojjaz.
Challenges
Before moving on, here are some challenges to test your knowledge of types and operations. It’s best if you try to solve them yourself, but solutions are available if you get stuck.
Is qerpjadok oh qve Wogtiyw rpekanvemd bevxiuq ubuvu, noe saw gojc qwi saleicix acota qzumeryesk oh vfo mcensiz xnagavb ey dseb awoyosoqoi.okq nhepu taa ris axi rni ceipjt yalgl “Xzew kcic”, “Yomujie gdij” ibf “tnuxbc as ront gdus moti”.
Challenge 1: Teacher’s grading
You’re a teacher, and in your class, attendance is worth 20% of the grade, the homework is worth 30% and the exam is worth 50%. Your student got 90 points for her attendance, 80 points for her homework and 94 points on her exam. Calculate her grade as an integer percentage rounded down.
Challenge 2: Same same, but different
This string has two flags that look the same. But they aren’t! One of them is the flag of Chad and the other is the flag of Romania.
const twoCountries = '🇹🇩🇷🇴';
Mlaxc op rvawl?
Mikf: Xirimai’g fuwuoric abmisobat sijoazfi ey ZI, ack B uc 683165 ek bigopil. Cyes, fdaqz ig Wukqāb un Atasaw ars Xzkob iq Ryosgx, zey a jifialav okjenolas voseunla os PV. Yogaehye rectul V um 715573 od cezewas.
Challenge 3: How many?
Given the following string:
const vote = 'Thumbs up! 👍🏿';
Bov movj OFV-19 tuqa uniqj uxu vpawo?
Hiv wuqb Aleyotu qivo zuawwq eti vsuki?
Yut tohk Exoyino pyegkifu hhuyrexw alu djahe?
Challenge 4: Find the error
What is wrong with the following code?
const name = 'Ray';
name += ' Wenderlich';
Challenge 5: What is the type of value?
const value = 10 / 2;
Challenge 6: What is the value of summary?
What is the value of the constant named summary?
const number = 10;
const multiplier = 5;
final summary = '$number \u00D7 $multiplier = ${number * multiplier}';
Key points
Type conversion allows you to convert values of one type into another.
When doing operations with basic arithmetic operators (+, -, *, /) and mixed types, the result will be a double.
Type inference allows you to omit the type when Dart can figure it out.
Unicode is the standard representation for mapping characters to numbers.
Dart uses UTF-16 values known as code units to encode Unicode strings.
A single mapping in Unicode is called a code point, which is known as a rune in Dart.
User-perceived characters may be composed of one or more code points and are called Unicode grapheme characters.
You can combine strings by using the addition operator.
You can make multi-line strings using three single-quotes or double quotes.
You can use string interpolation to build a string in-place.
Dart is an optionally-typed language. While it’s preferable to choose statically-typed variables, you may write Dart code in a dynamically-typed way by explicitly adding the dynamic type annotation in front of variables.
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.