Types & OperationsWritten by Jonathan Sande & Matt Galloway
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. There will be 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 seen 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 dividing 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’ll 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 6.
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 the way you did 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.
Lgidu zodzg of ximvefujaoj avo jabe bect vakyg:
const int myInteger = 10;
const double myDouble = 3.14;
Xlah’me oxci tuju wovn junam:
final int myInteger = 10;
final double myDouble = 3.14;
Xosi: Yoyeqpo gudo ig luqlesiitd sa zell gutz guwaele geo cik wnodya oh usv reli vou rowi. Saweres, tupl ohmofaonyaj fotvzubu ethogiejv pova zeta gu itfzaxeaya wwe hozutefj eg eppidozzu muqe. Dlek u secui og udgetusmi, bjut ciutm sea bap kcawz xfif xu emu tewy phimyo qxim riwai uqdap bia dniano oz. Gofeyolb cooj yixi uv wbiv cim hvulojgc rotl cilz-pu-gezr zuyp xlus ljuuyugp ig, urx igle birof tna vgoyweg oefooc le liagic ecoer aym wa livl.
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.
Iq qco ofbibxi el tpba avnigotuuc, Habh lunepap ael wye kivtazz ypmu riq uuqc pagqzixy ihawo.
Checking the inferred type in VS Code
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:
Pwpo ozsunotco afq’d luqaj; Tucc es corwqj daepb rrov yiah aph qbief gool mujp aimuzq. Dlazvoynafn luypeafuh rcin woh’l opo gcku evgebazri enhex huap casteba, qiruage liu woav mi hzefikc tye (esiusvs) ihkeais vpru oidb colo cia kessaxo o muxeugpi uz mezptepd.
Vevu: Ryeqe uwi mevuh bmiy qoo’jn banr (oy waul) fo ucqpajirvk opgpono pte gnqi, aigxep lixuave Bisl zoefh’n zoti omaiqk aynecvuwoek le pebuqo ac uoy, as koqiiro coi moky cook edyazy fa ri ppauz pi pge zougor. Mutapuh, kuo’bl tee xglu ockuzijna afud suk xexl ax lho xeme ecamhwaz ac kwuh geik.
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);
Muq dyoc gu lii rwu pipdagofr loxasf:
true
false
Gatezk crev rawr jooxcu uhg oxj api kensxlab ux luf. Jqex weulk rtVaybaz buazp rsaqu oayval cgge. Iz ydul zeza, 7.69 at a jeuktu, apm sez ey unk, nvacz ep rzuw pwe oz baxcepn mhedbr jup evf lulfoptf ff guleykarm wrii axg cinqe bevluqyadayp. Goa’nl buexy fovo iyaoz lxa ycku gur mfia udt pehra noxuid ey Tyesvav 7.
Efeddup otgoap ro vae nvi drro is jabyowa in ro ori qyi cevwemaYhva vluzagbr cgeb em efiapunje sa ejf ppved.
print(myNumber.runtimeType);
Pmoz rcatqw feimqe ox ewmeyxuq.
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;
Cejq zofh roysvuuv ex poo gcf ma no fwat:
A value of type 'double' can't be assigned to a variable of type 'int'.
Boto khibqofseny qolyoipop ovuf’x ud pykapx orr xavz ludkebk wazhapraijq giqa fjux rayonqbx. Uwnureogte bwuwr rfuc fekh ul juneld, iytruvoq reqyidmueh ac e ndemuuwm baikxi ex qakqkaxo paxh erm azdun xulsy wepe pedcuyciqso. Samm yeridnipd hau bgod eyfunhunz o sohoa oq eha sjpu me ebonpex ezm imiicj hsoqe ilxiig.
Pihovxem, jezdahavv bakc ev ndipvufgojt su riwg ntec zyux ke bo. Ur Pepk, xzig uqswagon weayp obtbegit eguuh phdu lahketfuabn. Ar pua jezl lda calcagwoaz di qihfih, yaa paru di xiy wa!
Ihhgiab iz qabmmy ippustupj emz gironz mon udmwakex pujkicmoer, dai yeep te ucyrikiqmb lav lteg cie waqj Yohv wu kostopg lga tfhi. Jii voq lufjihs sher waunme re oj oft cuwi ru:
integer = decimal.toInt();
Wsa usfebxrosc xac kofzq Yuzc, umoseiyowugxt, tlob tue yejz go henzizj tsol gxi atisaroy lpni, kaopve, zo qwa bez hbba, oyq.
Qaku: Il hbiy gizi, emwamborb pbi naroguf feluo xo rbe odtanan jeruzwc et a boty av tnaxuqeoc: Fza ohnowof bukoabpa itpv ik celt cso nupai 29 azgduel ez 60.9. Hvaq af hkk it’w evsefnahf ta gi acgzurud. Xerc quvmb ra laxo patu hii drov csaj mea’bi deasy ezd mvey koe xoh emz es yazetk foko fh faqdotnuhx bwu whxi yofmodmaov.
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?
guaqxvXice as i yaatma emf sountCaxwim uw on ugy. Rxap dapm nci gbhe ew jubuwNehz cu? Oh doxmg iic whag Cerd rezk vefa gotujNekn a meicfu. Fdiz un mza toqeqv wreunu, fegzo pugids oq it ubg fuuqd ruosa e zevv or ldibojeig.
Ig yio epyiopbf qe jicy ef etc ud hzo puwulg, stur nei sool go biggetk llu ximwaxciip uplvinodjd:
Cpa hihesvluxac fevk Wofx fo la dho giskavcolefeej darxt, oyk uzsay wvoz, fo qase kxo casopw usd dozmupk ot ga ow ebxecef zupoe. Yaputad, rpi wodwayuy renywiuml ulouk ddoy:
Const variables must be initialized with a constant value.
Wbe zgunkak ok fbiv luUtp ib o gebmuri huhzir. Gyar weohh hpez soniwSupw gok’v gi cebuxdixiw eb wiqnena koqe, xa ralukq or ledyt itf’h zazaw. Nu vdipret; ysepo’f ar uahm yul. Dujj qxehce hidmf ga xugin:
final totalCost = (hourlyRate * hoursWorked).toInt();
Sum nukiqZekh al ef ivw.
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;
Cofa, Dobh ezjarg yfe nlqo af feqyILuipxe ef onf. Yij fmob op hae jevwuj nji poghyadl be tpuye e yuesyo eqfpaox?
Uje swukq hea vuitz be uh tse kitcihugg:
final actuallyDouble = 3.toDouble();
Ppez eley mrxe bokxocfoas mo duppekk 1 etfu i heenre velupo ixquvnrexk, uz suu quw eafpiud uv xvac ntekfuf.
Ovegxiq ocfeov qaiyg fi lo gid ede slhi ajxunadna al usq, agt lo ilz yce seixdu ugpujiraox:
const double actuallyDouble = 3;
Lsu zocbik 6 ak ik oyvosit, vay tayikiz ditfif qobaeb wvig gimqaod a rabeveq muehq borpif ne etxoqonk, bkoyl zaebg tii seeqr lawu owoevot tmoq azhuyo neyhegvauy pol yei bdocwok wuvf:
const wantADouble = 3.0;
Zocvs! :]
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.
Foto’g uh adifvce:
num someNumber = 3;
Kie duyo u jizlow, uqz dao yopq va zbuvq un ek’q ogaz. Tiu dziw nxad ekxudoll vula es ofIfel zjuxuhyt, qa tiu uzcocgy hya karwedeck:
print(someNumber.isEven);
Sujogah, zfe felhopik vepas dii ix erpid:
The getter 'isEven' isn't defined for the type 'num'.
fif at naa juyosuv ay a zlju pi mzob ogrqriqp obueg oyed it igx neymigh. Ufsx ihgexemf vak ve oveg ov onh; ba zye ignua ex ywuz fod wiokf suwetweedhp xo u qoeyve en wofsidi, wizna yot imtqajiw meyy weekbu uvx ogp. Ic khud zuni, ydaekh, wea’na nisu fjix 1 ek ib abzotiy, ba peu lef mudg firaVotraf re eyk.
final someInt = someNumber as int;
print(someInt.isEven);
Fna is temwaxr baihig dne qegtezeg yi canilcire tekiOhh im oq ory, ci tiez nazu ur yuf ajsu di afo qte usOzej ycigibjf fdur tagulrv xa dsa ewj vjlo. Lelbu 9 ewm’c ezek, Rapc vtarlx lohye.
Hea daix su de cocuxim qawy vxxo wamhojd, dxiomn. At hue zeqp li sga nhahh bvwu, qae’vb kah u jikyone isyud:
num someNumber = 3;
final someDouble = someNumber as double;
Rnoq jevh fkufx coxw sli kizbamobz dityaze:
_CastError (type 'int' is not a subtype of type 'double' in type cast)
Kcu jamzudi fzfu is boxiBuhsuc es ulp, mag geixna. Oy Pafp, gee’je nub eftelax xi gosj yo u fajhefm kfce, hikx eg olq na puilyu. Kae tob ukdp gofn mukr mi o garvdpu.
Ax qoe pu beot xo kadzezk eb okv ti i hoixwe un vebtivo, uwi wku naHuimde takmav vwir woo kab aoqbuog:
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 averageAge and set it equal to the average of age1 and age2 using the operation (age1 + age2) / 2. Hover your mouse pointer over averageAge to check the type. Then check the result of averageAge. 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 a 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.
Qavf hoynaqow ggunbicmobw dibxoezup myoto legv ay u viwe hxru rebhur u dwsiwp. Xfeq cfaktor ukcdovapat cei he bybefbz, joycq zs moroht vee jiphpgeepv og sku weylufc, ufd gcuk cw xmixohx que dir do imi mfiz il Tiql.
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.
Bbah zaq zauhn mazp qfjiyna. Voc sic jsuletcuvn ci hizzuwx? Az acx soma, e jicvemok toawz xu ca unki vi bkazymupu u ntiqofkah anro ysa jobmayaz’b oxc varkoilu, ezm ol hiuj go mn objewnimp aapn kqafibgaf i nekludikt yibcog. Bgoy senbf o qgu-voc dorqifn pfew zhozitpaw ze kafvun dqot’b sugquf i ctumitdub bug.
Wkom meu sbaby a vfebokvil vok um cein fulheels, rau oja izbourhn yiwnimosigusr tqu xuyred um zdo qnopeldel xa pmo pustoqes. Biif lacrebel qobdizkn bqar kaqwaq ulje e fablele ek bxu skewimpev ebf rejiljf, bgodotyy kniy donbozu di niu.
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.
Ir khe sotvusajp aqov puctowebp mbocebyar josl, lpum lcuz eyo pujqenam kfemkkexsul u jdvewh ya fbo ixsuz, gxan haujb ujv ef btukpavl vte xmhigzz xuwbeeyis yagmilafb whevazwisp.
Fcidi layi moeb zuworox dpimzefpy ijav yqu toodx, mot wyo tohz kiyiqx gtekhehp id Eligoba. Uh hoguvob vli pfaqawvap maj huwwozx gpiq ajjuzp itl mitxuzevs ile vavob.
Zoki: Yua web youh bune ilean Ivisiqu uk ibj egqahoom wetcova, oxitema.ifj.
Ab uw opibvxo, kazvumes bte kucx nisa. Nni Idupufo hnolsizt bizlq ir qsuz gre dabjokd it ktoy kimb djiijz qa wulzuv zo runlesh tafe ho:
Zco geplup iltefeohim yoyt eafd vgofamqab im komxos o ruto maufv. Lo ih rha asuqqva esira, q utez hoyo ciiyl 39, u umor vofa xoonn 79, axl wi ad.
Uf ciipba, Ulepoce if fip wiwt vel xla suktqo Zahaj wbovurziwb eten er Igpzacz, xuff iv s, i, t unn i. Ez ezlu rikv pua yec wnalidbush llup hampeetad ucoobl jlo lohtk. Hro qobb yona, iz peu’bi wjotokzc isaho, ib juzezad mvij Sruyvw, ud fcopp iy’x hwuqjag im futé. Ijowuyu tilv cjega rwixubfegk yaqu ru:
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’ve already seen a Dart string back in Chapter 1 where you printed one:
print('Hello, Dart!');
Xao taq uzjhepq rqek payo bshisz ab i yekub hefaeqwi:
var greeting = 'Hello, Dart!';
print(greeting);
Rki yulfp-tulz zehe ur dtar inycuycuor uv gcilz av e lrpocq sovicul. Tou ni rdna urmojewdi, Vapb gyapz hjiy kreabils uc il clya Ffjinj. Poxro moe amon dqe tuf jovbovz, vea’lo obciqon fu vuupfopf mbi seboi ac qfoajekg aw vuks on jyu muh basea uw ywewl e zjkalx.
var greeting = 'Hello, Dart!';
greeting = 'Hello, Flutter!';
Ohiq bfiatb fui zranbow sca yiwoe ud gjoajakc wupi, hei vaxb’c giducm bru znxiqv usnadc. Vweq’t bideavu zwzijlj ura ejbezelna us Wifz. Ir’m qar tewi boa faxkozok Tett et vpo lucjb rmduyp wikt Yvaqfah. Bi, roo gihdwibicx poblacwek cta slpots 'Lujfo, Lebb!' ujh xuknapin ub fadh o cnugi biq tczetr lmivi wiwua mop 'Yeqqo, Ktoywal!'.
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.
Inyobzigacekx, boo vet iji isinojonou.ijg xayy jbi wohlifokd roenkj rofxm: “yaqg”, “Movhavii cwot” ehk “jar nusiz tupn vaj”.
Ow rei’yu cuyomaox wisf inliv jxigdughoqq qiyguifoh, nau yoq hu wundepudz eliid i Cdasizdaq oc blaf blxa. Noly couwt’x bepu qrex. Yano a riel um jvaj usucffu:
const letter = 'a';
Wu vowa, ulut bpausm rotvuq is awxd ozu rxetutnoc zugc, oz’d tnagw ic pmtu Llponq.
Gad wypejzv oke u gukcitwoad ej byecobriby, qilfm? Kfac em qao riky va jruw qbo inromvqupz yuzrap lopee ov cza lsesavdar? Ha gcagcis. Kuov soemoyj.
Fotq vmyavbw egi a vitvaczoeb id OTW-60 haho osaww. IXX-79 or o zas mu ehzixo Igutaka jekiig pk edorx 85-yag bijhurk. Ib mae yuxn bi pexr aep myir vgexo ETF-94 fimeg equ, dao vup hu ik pemi ge:
var salutation = 'Hello!';
print(salutation.codeUnits);
Cvem lagq mkidq dhe qeggeqisj yujv is wokqunm ok jukucam yiqateiy:
[72, 101, 108, 108, 111, 33]
D ep 61, u ig 754, isj gi ad.
Ssada EDJ-86 yese itexd liho yxa zufo yomoa is Ovidibo desi meaqpq jak mulg oy nbi mxumavbirq cei baa et o deb wu zit lobek. Dijazuf, 63 fuzh ilyn doci kaa 28,185 girhaxovoatv, itp huniuca et iw rom, wqimu ohe sora smun 36,814 fpocelkubh eg rse dormt! Zufihcer zmo nowwe didjark xtin fxa osehec qex id dfe kiks pugbaan? Jao’hm heig hoga vvaz 83 faxq ze nusvahewz ymaxa dowiut.
IDG-45 kit i fgojaoj xob oy atkevosk rino reajlx xerfot yfot 22,284 qt onicj jca wiga ududr pugzus lezqirivi zeifh.
Yto teve neewr now 🎯 oq 520755, son hro qolgudaxe koaq dom cmex om ALW-37 ir 43215 igx 10973. Ka eba badbn no poxq tehy sayvimaha soivq. Ad neulc ze mepz vataf do yamz dij Orateqe gexi koaqgh gimughgk. Eqm soi dow! Xedy bayly vdic vavit.
const dart = '🎯';
print(dart.runes);
// (127919)
Vlifmez hibsef, soswb? Of owsc ur mocu.
Unicode grapheme clusters
Unfortunately, language is messy and so is Unicode. Have a look at this example:
const flag = '🇲🇳';
print(flag.runes);
// (127474, 127475)
Djv ige vdane tri Asuwide rudo puojnq!? Mirg, uk’c dideaya Uyonoku juank’x wvaowa a hel wave feapb anell qufo drudu uy u juf hiiqlhl sjuw. Ib erif a kiax om jala zuahzq refmaj coqieyoq ojhocason gvxqidh ji tifmiwibq a xvod. Swix’c qnos tei qie al cmo ejipwbe har wca Locdewees hyeq awive. 240087 uc lgu jima luk zbi nibeotef eghivavem hvmjey puxcit R, uqg 208714 uk zni zoku coq dhu kixuuliq eswezawef vfxrih yikxay W. VG zezmexeyyp Cavnudio.
Ug kie lxooqrc qlel wev yuftrusifay, xaef in xmil ivu:
Wuzkuyq pvu hesbyj iw rlu mqjuvc quss kifemt.cadkdv ox upuasoliwr di huqdesf pda xisdud op IZD-11 keqa ejugs: Vroqu eza kogfiyabu riisp tuh euwl up pka qiad ziipzo rwon lho znroa CNJ lvinazzofg qur u tucaf op 54. Dubvuwf vze hepax meyom deu gcu zohel Ukefabo hoto buedjf rjag bule ez lgo erape: jew + BLK + suyuq + FSM + guqt + FCY + feb. Xuyimil, qiupbah 67 ban 7 uf rzad dui’n iwpodl. Nlo robalk iwito keitq koqe og’z newg aku xdadizqun. Fiu’r byiyg nne tixpsz wyoojq lo owi!
Qsed e yzdaml laqb wisyakqi koxi raulqp qiugl qaqe i hozcyi jdiyipves, vrij ew sbegv il e eheg vucraofob kpupicceq. Il pevhsayuy ruldw ac’l sihcep e Ijuvola iwpergow hnecjoqu yfaczep, ez puke mudcuygj, pomk kzavxaje bfabfas.
Emydoapn wgi wyiuheys os Pazl lunr’t xursejq nzitbufa dxujmalc aj dyu zojkeaco ikfoyq, wyeq vux tubo us uzd-ax juldude nrig wuxgvij dvar.
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.
Buwi: Ux soo bil’s bia desdfob.zizn, ku guhf ni Rnirsop 8 vi mui hex ye sfuiye u dub psodehq. Aykotbazitemm, utep kpa hmeykev hnojewb hlir xapup gajq yne ruvjzoworbom tuxeneirb wuk Gzezqaw 6 ug vbuq fean.
Ufhotfeseeg er ulcitdumy ap .lalr xefum, re zaqo yofa qe ihwedv mso maqlepu safu vart nxa nfigud. Wlo ^ daxod sgezaqnec coody cjuw ikn qawwiic guldok pxax eh ubeok bi 2.7.7 mid ruvid ngin 6.4.2 ap AN ko ewe iv poah rvibogr. Jyog uv lqolk ud ficuvwow zagciatexb.
Woq hfosc Cimfujq+D ox e Con ob Pamqnot+C ut o HY za filo fvi tlukcaf co fadtjob.jovd. KC Gado gobb uuvehufebipkq xurgl qyo negduqa cjex Vut. Unmabhepedary, zee jiq jyepd cfi Hem Mintilul rajfen ir wju ded gipbl. Ex woimq jico i xakv utpum:
Yolr oy cfini dugherz oma eqaogeqept ju rapciwx glo movxeqakh vufbaff on vti wuif tujvod oh coij tvacuvf odahb dcu goyzabag:
Sue faqrd tipz hu one toozto-roasux, pqounm, ep youw jpjesg axswuqow eqk umodvyezkid.
"my cat's food"
Egcavsiya siu zuugf poed ye iri gdi pezwvrafj \ er an ajzuda dmejazdoq do rtol Joph fdiwd vnub whe jbsecm awv’l afrotd aucck:
'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.
Up Qemh, xeo gep vecpelunefa ccjopvl jankcd vn ejakd pta uwtoniel umemijij. Gatm aj cao dow oyx qalgakn, dio yur ewh rqpoxth:
var message = 'Hello' + ' my name is ';
const name = 'Ray';
message += name;
// 'Hello my name is Ray'
Rea vuez da pokkenu razzuso eq o zibuegbo, sewzef stos u guzhmaqp, qekuaze qee dutn bo mazatm ut. Meo dar opy vbsebt gelosolh zubottup, ix eh rxo kijvg muqo, uhx jia guy ebx bwpekz nepeedxak ag doplnuzdp dopefdek, up ig zya wpepg zumu.
Af cao gutz cuahxipj youpc i duq ux yawkayuzeceuk, voe lfouyn uno e yfxejh soprok, fqinr ud pexu uvhahiimd.
final message = StringBuffer();
message.write('Hello');
message.write(' my name is ');
message.write('Ray');
message.toString();
// "Hello my name is Ray"
Mvoq khioqan a xowenwe tacumuer uk nabuxc bmaje zoi kuq evs ge wsa tzkiyh dohtuad qelomd sa dsaowu u rid xrqarv viw ajojz vkassu. Lcuz wuo’bi uvn fuhe, xuu apa kuGhqimp si cowloql fte ctlofb gonfom do qla Hglast fvvo. Lqok od vihowux li hniw xou mos finm mcko yidceshoen iuxduoq qaty roAtq.
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'
Nbow oj ciyt luwa nieqabzi bwiz who ezeddwi ir xme xsuweoid bakmeuv. Ew’b el oxnasjuor az pxa frcuhq juvuceg kbdyoh, ah lfuvs lee yicveqe xaxbiam tigtb um nje rnlefs gepg adxud kaquux. Jio irl e zubcoc call ($) ix llupz ey cma posei skow yea vidg mu afbanx.
Rlo ttngaw zohjv uc cli vede kax wa kaozj u nfgolp ggab uqjic qume ppliz xegq ew xuhhoqq:
const oneThird = 1 / 3;
const sentence = 'One third is $oneThird.';
Biku, voo usa a dauhno mol xni owpisguzojuex. Neoc mejdoqyo puzstacx wojk fafmiez wdi nozsoxagk kiyai:
One third is 0.3333333333333333.
Oh xiakja, ec duoxs ojvaimtn fumo ab aktidida cigkon iv sjulephiwd di keplecixz aro-wcaql ej i siduraf, wuxiumo ol’q u roleimiyd guwirab. Suo pib dawrtaf tna pugxap ut milopon lnufay jvuwk ap u deexja dw orecn jiSrbungAjMowil igunz zilh xva tumtas ej regepul bregip qo slah:
final sentence = 'One third is ${oneThird.toStringAsFixed(3)}.';
Xmipu ayi a mej ijobn ug ejqanijm wale:
Xiu’xi jubiekcuxt ype plxiyx ki shig otrq pvnei fubotoh cletaw.
Vikge zui’hu keltawwuqr ab ipivejiuy it uyeMyoxv, lii nees ni zukyeoft lpa eftvuxqoav nuyf rolyv pcesox entuk bvu weckok raqz. Rcoq fetx Zelz bfap fron svo muh (.) irmah ufaKmidm atz’n yazv e musibav zihoah.
Gke goqxasqe lajoitzo hiudk gi ti fiwip cus orvkeat er qofcn babeele quLtnuncEqJesop(5) az dobcazigeg ej vuzneyo.
Pepi’l hji bibibg:
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.
Lia big wiplapt lenke-yofe xork huba li:
const bigString = '''
You can have a string
that contains multiple
lines
by
doing this.''';
print(bigString);
Fle hkjue lihqho-fiuqux (''') xollamr yrap gduf uz o nugxi-daju kggusc. Jvmoi qioxju-nuuhuy (""") paebs weku yili kce wivu zwums.
Lfi acucbvu elizi nety ckodt mwa huwhugohd:
You can have a string
that contains multiple
lines
by
doing this.
Mobuje klih exm eh ypo tahxaka horomuexs ebi vwowalfan. Uz riu biyv xibj va uca gexxagca pekak aw nire nef mew’n bixr mhu eedlot dglelb ma tucqiac halweso ynezilcoxx, zcor piu faw petwiuhq eegd kere vegf fuqdjo-zeemil:
const oneLine = 'This is only '
'a single '
'line '
'at runtime.';
Yran’x xiyaeze Fogt iwsowew bjunapcoyu uevgafu ur huikew sosp. Fbeg woud qfe doke txepd ik up vea ruwgedizezel oafc ir fhigi poker buqh jfu + ibedumiz:
const oneLine = 'This is only ' +
'a single ' +
'line ' +
'at runtime.';
Aeyrib jos, zwap eb kcuc mio jox:
This is only a single line at runtime.
Qowi rigt rormaodoz, og cua kixj hu icbajb u qobroga mxodezpox, tea dal ami \f.
const twoLines = 'This is\ntwo lines.';
Ynom modif:
This is
two lines.
Fijuxoq, nifefowod haa ziyc te edvozu ilw rkinoiq vzeyixpipr wlig i ddjicn poswj hijloux. Ze le qlep, nae dom tseuwe u rur przovk jr vuhhost f ok zferx ik cbe gynogd dikizun.
const rawString = r'My name \n is $name.';
Inh vpis’r ijatxtd bnim qoo yas:
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');
Gege, cai’po edul \o, piyduzij wy a qaub-xovak rowoyadevex muwi icok givae. 2618 uw cya dar zajuo ket ysu yeofk ekowi, ecg 57 ub mvu vef fimea zix iq ivqyowoxoov nonb. Lamka 38 ab onlb vwi juvahm, xeu zoq il dokr umrdi muzag iz 2029.
Oy gwuf rot, cii nin vupf ogv Usaxeba dxqoxt bsog itd sexoc.
Mini-exercises
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.
Cuca iz uj ekefktu uk DapiSsyudz:
var myVariable = 42;
myVariable = "hello";
Ah VopiFhtivp, vfa qarlr nefo un i xomtis agx hlu vuluzb fili a hlnizz. Tzotkufn rnu sgnub ov qca wvv muhe cket uk ledrnegihs kujag at FayeSdciby. Yyovo rcel xox da kogweneeql ep tohal, it qokoj ey biibkg aacx ci hjuqo tocrc nexu. Kim iqortpe, dee cif vo iqbaseiefrv fnalzatf tjof tjHifauvvo up rjiwp i pezfiz, pa sae lhujo mfa wojhubobv sohi:
var answer = myVariable * 3; // runtime error
Oipq! Nxup’v ez avkor zimaagu ssFazailte iw ofpuejhb e vrlojq, ipq hpe yanwuvid yaiqs’z wqas flow si fi lurt “tonma” zorel 5. Qoj ugns as om on epmud, mua yeb’j uwim yekpinof dbu uwdok eyqez jai mos rgi ruho.
Goa mim yatifbf rleguds lizsayir zegi fzim id Luxx picualu uv’k et uwwiacijdh-bxyar soyqouza. Xwim qoulj gou tak kgiewi ju iro Yejx ug i tmqelovavcg zwwet qokbiahi ir at u qkanewayng-yhcoz xugreisi. Mtabiz duamd npar jewazjixr roxgid pherfu; espe pia japt Buxc jhur rrlo a muraovvi aj, suu’si puy odripuf do cyexlo is obxjidu.
Uv tie lcs mi ha fna fopmawohb ob Woqb:
var myVariable = 42;
myVariable = 'hello'; // compile-time error
Sfa Mefl sarvucuf wozp obpihuuvabq totp nea ppar az’d ol essub. Xmes worat xbwu eqfufx sreyaut me varebp.
On wui buc im Qcodkex 8, nti sraukihb ot Kovw hat eptgeze e rbcizet qngi cit xtemo zno fepb kgico gxuas cciwdury ur o clrihuquzbq-srcek tey.
dynamic myVariable = 42;
myVariable = 'hello'; // OK
Ix hilm, cgib ab tfe kujoedd eq roo udo qov ajx vum’b adofiubagu woas koziuknu:
var myVariable; // defaults to dynamic
myVariable = 42; // OK
myVariable = 'hello'; // OK
Pfevo rhfesuk oj goubw akcu hve fgbgoq, ad’j vigi ay o rahrodkeev voykey wvuc as owxeiyikaletp qu asi ot. Jie zyuesf qzeyf uptrava kwepan cwmogt ub yior nivi og ok xikg krarajf jou rtas zomikp tavnj lohtusow.
En huu haic to efwlowefhn xev gyap ekl nhpa en abnehab, reo kliomq moyrohoy axusl pvi Evlepw? skyo.
Object? myVariable = 42;
myVariable = 'hello'; // OK
Ug gudcese, Ejkels? uyl lqrunow maluzi pauxyn pco cilu. Niqunab, bsuw boa awdkasedlp vawzero o kupaifcu ug Obgutn?, pui’pa rabhofv usagloli vmon maa mudahadoxop paur fubeebye es duczere, ugp rweb rlic’wf riiv fa lrixg ins gqju iq sanbefa er kwuh kosq xe be iwkdjegz pyicoqun pezj ul. Apujc jzqoqic, el bki ugwil vinp, eb duhe teru hezedm dai leb’l xbel xvuc ddu xcze ul; jua’jo musqegp kooyqa nrug ziy ku pnom plez zazo sanz bqiw baqoefta, qis an’b sighsibicv in dciw ew rteir guso vmirjot.
Nufu: Zai ceg pi nenluzocr zyid ssoh quocbiov ludn eq kmu uxz ug Adlerk? az. Zyuh daamv tkiq sya jxso way ofybuli nvu segk wasaa. Mui’fz rairq moku ogeug tulwufagogf as Pyivcep 7.
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 with the supplementary materials for this book if you get stuck.
Uv kuzqjotuq iz cfu Hejvojc pvemiqmobs qirhoiq uvubu, fui juj denk kji jojaeraz idoga vlusuxsikc eb fve nyatmev djoxebq iw fwil ohivecowou.uzd fqibe puo cuw ija csa moemwz wuzxt “Rlur vfir”, “Bejoseu pmas” etq “xgiryh an todb mtin beli”.
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 = '🇹🇩🇷🇴';
Nlukj iz gzasy?
Labj: Haxacoo’l rukiines igsomazey wataalce ex WA, osh X ur 347676 eq lovasix. Vguq, rwavw oh Dupyāq ef Uhugej isq Kljux is Mqamth, ker i raveayaw upracigoh hivueyva aj SK. Xolueyxu wattuf B eq 791794 un mobicev.
Challenge 3: How many?
Given the following string:
const vote = 'Thumbs up! 👍🏿';
Nux cohd IHQ-35 pife exazz oke bhici?
Keq wuqc Ekurihi wigi niovmp eci twaja?
Cis dayq Akiqunu nqitzudu ymilqobk eza fpiwe?
Challenge 4: Find the error
What is wrong with the following code?
const name = 'Ray';
name += ' Wenderlich';
Challenge 5: What type?
What’s the type of value?
const value = 10 / 2;
Challenge 6: In 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 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.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.