Tải bản đầy đủ (.pdf) (759 trang)

Peachpit press write web apps with dart develop and design

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (14.36 MB, 759 trang )


WriteWebAppswithDart
DevelopandDesign
JackMurphy
WWW.PEACHPIT.COM


WriteWebAppswithDart:DevelopandDesign
JackMurphy
PeachpitPress
www.peachpit.com
Toreporterrors,pleasesendanoteto
PeachpitPressisadivisionofPearsonEducation
Copyright©2016byJohnMurphy
SeniorEditor:KarynJohnson
DevelopmentEditor:RobynG.Thomas
ProductionEditor:DavidVanNess
CopyeditorandProofreader:ScoutFesta
Compositor:DanielleFoster
Indexer:ValerieHaynesPerry
InteriorDesign:MimiHeft
CoverDesign:ArenStraiger
NoticeofRights
Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformby
anymeans,electronic,mechanical,photocopying,recording,orotherwise,withoutthe
priorwrittenpermissionofthepublisher.Forinformationongettingpermissionfor
reprintsandexcerpts,contact
NoticeofLiability
Theinformationinthisbookisdistributedonan“AsIs”basiswithoutwarranty.While
everyprecautionhasbeentakeninthepreparationofthebook,neithertheauthornor
Peachpitshallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamage


causedorallegedtobecauseddirectlyorindirectlybytheinstructionscontainedinthis
bookorbythecomputersoftwareandhardwareproductsdescribedinit.
Trademarks
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproducts
areclaimedastrademarks.Wherethosedesignationsappearinthisbook,andPeachpit
wasawareofatrademarkclaim,thedesignationsappearasrequestedbytheownerofthe
trademark.Allotherproductnamesandservicesidentifiedthroughoutthisbookareused
ineditorialfashiononlyandforthebenefitofsuchcompanieswithnointentionof
infringementofthetrademark.Nosuchuse,ortheuseofanytradename,isintendedto
conveyendorsementorotheraffiliationwiththisbook.
ISBN-13:978-0-134-21499-3
ISBN-10:0-134-21499-4
987654321
PrintedandboundintheUnitedStatesofAmerica


Tomycharismaticandbeautifulwife,Katelyn


Acknowledgments
Behindeveryauthorisanamazingteamofindividualswhoprovideeverythingfrom
technicalfeedbacktoemotionalencouragement.
Writingaboutayounglanguageandbleeding-edgeframeworksdefinitelydidn’tmake
thisbookeasyforanyone.IwanttotakeamomenttothankallthefolksfromPeachpit
Press:RobynThomasforprovidingtimelyeditsandheralwayskindwords,ScoutFesta
forskillfullyeditingmytext,CliffColbyforputtingthisfantasticteamtogetherinthefirst
place,andKarynJohnsonforseeingtheprojectoverthefinishline.Andaspecialthanks
goesouttoJonathanHartforbeingaconsistentquestioningvoicewhenproviding
technicaleditsandfeedback.
Onthelanguageside,IwanttothankthefolksoveratGooglefordevelopingDartin

thefirstplace.It’ssuchawonderfullanguagetoworkwith,andtheDartcommunityhas
beensuchawelcomingecosystemtopokearoundinandlearnfrom.Ihopethisbook
helpsattractevenmoreDartisanswhocancontributetothevibrantecosystem.
Finally,Iwanttothankmynewwifeforputtingupwithmewritingabookand,atthe
end,fordealingwithmeattemptingtofinishthisbooktheweekofourwedding.


AuthorBio
JackMurphyisaseasonedstart-uptechnologyproduct-andsoftware-engineering
specialistwithafull-stackdevelopmentandUI/UXbackground.Hefocusesonfront-end
clientarchitectureforcomplexinteractiveapplications.Jackhascomprehensiveindustry
experienceasaUI-IXD/productdesigneralongwithadeepfull-stacksoftware
engineeringexpertise.
JackiscurrentlythevicepresidentofengineeringatAugmate,wherehisteamis
attemptingtofacilitatetheadoptionofwearabletechnologyinenterpriseenvironments.
Hisroleallowshimtoworkwithnumeroustypesofemerginghardwaredevices,including
smarteyewear,smartwatches,andbeacontechnologies.
Previously,hisworkfocusedonbrowsergamedevelopment,includingIdleWorship,
DinerDash,andSmartyCard.Hehaspassionfordesignandtechnology,andheusesboth
tocreaterich,engaging,anddynamicuserexperiencesfortechproducts.


Contents
Introduction
WelcometoDart
PartITheDartLanguageandEcosystem
CHAPTER1DARTANDTHEHISTORYOFBROWSERLanguages

TheWebandOpenStandards
JavaScriptDeficits

ModernAlternatives
ECMAScript4
DashMemo
Google’sMarketStrategy
Summary
CHAPTER2UPANDRUNNINGWITHDART

InstallingtheDartSDK
DartEnvironmentalVariables
IntelliJIDEAEditor
OptionalHomebrew
Summary
CHAPTER3INTRODUCTIONTOTHEDARTLANGUAGE

CreatingYourFirstDartProject
UsingFunctionsinDart
DartObjectsandMaps
StatementsandControlStructures
Errorsonassert()
CollectionsandIterators
Numbers
Summary
CHAPTER4OBJECTSTRUCTURESINDART

Variables
LexicalScope
Classes
ClassConstructors



Constants
ClassInheritance
Polymorphism
AbstractMethods
SuperConstructors
Interfaces
Mixins
Summary
CHAPTER5PACKAGESANDLIBRARIES

YourFirstLibrary
VisibilityandPrivacy
partandpartof
Packagesandpubspec.yaml
NamedPackageImports
Summary
CHAPTER6EVENTLOOPSANDASYNCHRONOUSPROGRAMMING

ConcurrentComputingParadigm
Futures,Completers,andStreams
Streams
EventLoop
Async
Summary
PartIIFull-StackAppDevelopmentwithDart
CHAPTER7PLANNINGTHEAPPLICATION

FictitiousCompanyBackground
FeatureRequests
DataEntities

ArchitectureChoices
Summary
CHAPTER8INTRODUCTIONTOMONGODB

Relationalvs.NoSQLDatabases
WhyNotDatabaseX?
WhatIsMongoDB?


InstallingMongoDB
TheMongoClient
Summary
CHAPTER9MONGODART

SettingUpYourProject
DownloadingandInstallingMongoDartPackages
ExposingDatabaseCredentials
SeedingDatainDart
ReadingaFilefromtheFileSystem
ConvertingtoJSON
ConnectingtoMongofromDart
VerifyingtheData
Summary
CHAPTER10DATAMODELINGUSINGDARTSON

WhyDartson
MongoPooling
DartsonSerialization
CreatingaMongoModelwithCRUD
Summary

CHAPTER11WEBSERVERANDMIDDLEWARE

Shelf
SettingUpaShelfExample
AddingMiddleware
AddingRouting
ServingStaticAssets
UsingMultipleHandlers
Summary
CHAPTER12APIROUTING,REQUESTS,ANDRESPONSES

ModelingYourTicketingDomain
ImplementingControllers
HandlingRoutes
Summary
CHAPTER13UNITTESTINGYOURCODE


WhatIsUnitTesting?
JasmineviaGuinness
SettingUpGuinness
CompositionofaGuinnessTest
TestingMongo
Summary
CHAPTER14AWEBPROJECTWITHDART

PlanningforFront-EndDevelopment
InteractingwithHTMLandtheDOM
QueryingtheDOM
BuildingtheLandingPage

Summary
CHAPTER15INTRODUCTIONTOANGULAR2DART

TheHistoryofAngularJSandAngularDart
TypeScript
DeveloperPreviewWarning
Angular2Overview
Summary
Congratulations!
Index
ONLINECHAPTERS
CHAPTER16ANGULARCOMPONENTIMPLEMENTATIONANDBUSINESSLOGIC(AVAILABLE
ONLINE)
CHAPTER17DEPLOYINGTOPRODUCTIONSERVERS(AVAILABLEONLINE)

SeepagexiiiintheIntroductionforhowtoaccesstheonlinechapters.


Introduction
WelcometoBuildingWebAppswithDart.Inthefollowingchapters,youwilllearnall
abouttheDartlanguageanditsextremelypowerfulecosystemofcommunitypackages.
Thegoalforthisbookistopresentaseriesofsolutionsthatamodernfull-stack
developerwillrequiretobecomeproficientin,andlaunchaproductionapplicationwith,
Dart.Wherepossible,thisbookwillusecodefromtheGoogle-backedDartpackagesto
helpensurethebookremainsrelevant.
Forback-enddevelopment,Iwillmirrorsomeoftheexpectedfunctionalityfoundin
manyserver-sideMVCframeworks.Forthefrontend,Iwillgoastepfurtherandnotonly
introduceDart’sbuilt-infront-endtoolsbutalsointroduceyoutoAngular2Dartforthickclientexperiences.

WhoIsThisBookFor?

Thisbookassumesyouhaveanovice-levelunderstandingofprogrammingandweb
applicationarchitecture.
Youdefinitelydon’tneedacomputersciencedegree,butI’massumingthatthisisn’t
yourfirstwebproject.Ifyourexperienceisstrictlyfromaback-endornon-browsercentricplatform,Iwillintroducemanyoftheprimaryconceptsneededto
programmaticallyinteractwiththebrowser.
Inaddition,thisbookwillintroduceyoutomanyofthelanguagefeatures,buildtools,
andbestpracticesthatadeveloperneedstobuildamodernwebapplication.
OneofthebeautifulthingsaboutDartisitssimilaritytomanyotherC-stylelanguages.
IfyouhavespentanytimeinoneofthenumerousotherC-stylelanguages(Java,
JavaScript,Python,andsoon),theconceptsIdiscussshouldbeveryfamiliar.Regardless,
Iexplainthesyntaxandrulesindepth.
Thisbookisnotareplacementforthelow-levelDartAPIdocumentation.

HowtoUseThisBook
Eachsectionwilloutlineitsspecificintentsandprovidestep-by-stepguidestoexecutethe
associatedexamplecode.Theexamplecodeisdesignedtoeitherillustrateaconceptor
pushforwardtheexampleproject.
Thecoreofthisbookisbrokenintotwoparts:
PartI,“TheDartLanguageandEcosystem,”isalanguageoverviewandexplains
thehistoryofDart,thecoreconceptsoftheDartlanguage,howtouseDartinside
theIntelliJCommunityEditionIDE,andthefunctionalityofDart’staskrunner,Pub.
Alongtheway,you’lllearnabouttheserver-sideDartVM,theDart2JStranspiler,
object-orientedprogramminginDart,anduniquelanguagefeaturestohelpfacilitate
asynchronousprogrammingwithDart.
PartII,“Full-StackAppDevelopmentwithDart,”takesyouthroughahands-on


approachtobuildingafull-stackapplicationusingDartforbothclient-andserversideprocessing.Iwillcoverapplicationplanning,thestateofdatabasesupport,
MongoDart,unittesting,front-enddevelopmentusingonlyDart,andfinallyfrontenddevelopingusingAngularDart2.0.
Formatting

Youwillseemultiplefonttreatmentsusedtodisambiguatedifferenttypesofcontent.Ata
highlevel,textthatisprintedinamonospacedfontreferstocode.Thefollowingisa
high-levelbreakdownofitsuses:
Generalcode
Blocksofexamplecodeappearasfollows:
functionstart(){
print(“Hello”);
}

Highlightedcode
Thefollowingstyleofcodeisusedtodrawattentiontoaconceptortohighlightwhere
codehaschanged:
functionstart(){
print(“HelloWorld”);
}

Codecomments
Graycodeisusedtoidentifycodecomments:
Clickheretoviewcodeimage
functionstart(){
print(“HelloWorld”);//Thisisanon-executablecomment
}

Codeoutput
IfablockofcodehasoutputintheTerminalwindow,itwillsometimesbeshownascode
comments.Thiswillallowyoutocopyablockofcodeandensurethattheoutputmatches
what’swritten:
functionstart(){
print(“OutputItemA”);
print(“ItemB”);

print(“ItemC”);
}
//OutputItemA
//ItemB
//ItemC

Commandline
CommandsthatyoushouldrunfromtheTerminalareprefixedwithadollarsign:
$command-to-run

Mongocommandline


CommandsthatyoushouldrunfromtheMongoclientareprecededbyananglebracket:
>mongp-command-to-run

Output
Outputfromanycommand,eithercommandlineorMongoclient,arehighlightedasgray,
asinthefollowingexample:
Clickheretoviewcodeimage
>mongp-command-to-run
Thisisoutputfromthemongodatabase
Itisamonospacefontandgray
$terminal-command-to-run
Thisisoutputfromtheterminal
Itisamonospacefontandgray

Wrappedlinesofcode
Linesofcodethatarelongerthantheprintedwidthofthepageallowswillwraptothe
nextline.Thewrappedlinewillbeprecededbyanarrowtoindicatethecontinuedcode:

Clickheretoviewcodeimage
main(){
print(‘WelcomeToTheCityAirport’);
gotoField();//Functionmemberoflibraryfield–exposedonimport
field.dart
//ClassHangarismemberoflibraryfield
HangaraHangar=newHangar();
//ClassToolboxismemberoflibraryfield
Toolboxportbox=newToolbox();
}

OnlineContent
Oneofthechallengesofwritingaboutemergingtechnologyisitspropensitytochange
quickly.InAprilof2015,theDartteamannouncedthatthenewofficialfront-end
frameworkforDartisAngular2.0.AlthoughthisisgreatnewsfortheDartecosystem,at
thetimeofthiswritingtheAngular2frameworkisstillinitsalphaphaseofdevelopment.
Withthatnews,ratherthanpublishingabookcoveringstaletechnology,thedecision
wasmadetoprovideagreatopportunityforyoutodiveheadfirstintothenewframework
toensurethatyouarelearningthematerialthatwillserveyoulongtermasanactive
Dartisan.
SothefinaltwochapterswillbeprovidedasdownloadablePDFs.Thismeansthat
everyreaderofthisbookcanlogontopeachpit.comandacquireanupdatedversionofthe
finaltwochapters,coveringAngular2.0.Theupdatestothechapterswillbeavailableat
thefollowingintervals:
Whenthebookisfirstpublished,coveringthealpha-levelrelease
Whenthebeta-levelreleaseoccurs


Whenthefinal,v2.0.0releaseoccurs
Therestoftheapplicationstackhasalreadybeenreleasedandisinamatureenough

statetoputtoprint.I’veusedDart’sPubversioningsystemtoensurethatwehavelongtermsupportfortherestofthecodeinthebook.
Thefollowingchaptersareavailablefrompeachpit.com:
Chapter16,“AngularComponentImplementationandBusinessLogic”
Chapter17,“DeployingtoProductionServers”
ToaccesstheWriteWebAppswithDartonlinechapters,downloadthefilestoyour
computerfollowingthesesteps:
1.Registeryourbookatwww.peachpit.com/register.Ifyoudon’talreadyhavea
Peachpitaccount,youwillbepromptedtocreateone.Onceyouhaveanaccount,
youwillbepromptedtoregisterusingthebook’sISBNnumber.
2.OnceyouareregisteredatthePeachpitwebsite,clicktheAccountlink,selectthe
RegisteredProductstab,andclickthe“AccessBonusContent”link.
3.Anewpageopenswiththedownloadfileslisted.Copythefilestoanylocationyou
preferonyoursystem.

CodeExamples
Asyouworkthroughtheexercisesinthisbook,you’llencounterallthecodethatyou
needtocorrectlyruntheexamplesandcompiletheprojects.However,sometimeit’s
helpfultoseethecompletedoutput.I’veuploadedallthecodeexamplestoanactive
GitHubrepository.Youcanfindthecodeat />

WelcometoDart
WelcometoDart!Dartisapowerful,open-source,expressivelanguageforbuilding
modernfull-stackapplications.Afterreadingthroughthisbook,youwillbeableto
architectfull-stackapplicationsforbothfront-endandback-enddevelopmentusingDart.
You’lllearnhowtomanageyourprojectusingtheopen-sourceIntelliJCommunity
EditionIDE,andyou’llmanageyourapplicationpackagesandserversusingthebuilt-in
Pubtaskrunner.Finally,youwillspendthelastpartofthebookbuildingademoAngular
2Dartapplicationandhostingitinthecloud.

TheTechnologies

ThefollowingtechnologiesareallpartofyourjourneyintotheDartlanguage.

Dart
DartisapowerfulnewlanguageoutofGooglethatenablesyoutouseasinglelanguage
totargetthemanyfacetsofamodernwebapplicationarchitecture.Dartshipswitha
comprehensiveSDKthat,whenpairedwiththePubtaskrunnerandPubpackage
manager,willempoweryouandyourteamtoquicklydevelopenterprise-level
applicationsforboththewebandmobiledevices.

IDEA
JetBrainsIDEACommunityEditionisanopen-sourceIDE.IthasapowerfulDartplugin
thatprovideseverythingfromsyntaxhighlightingandtestrunnerstodebuggersandcode
analysis.

Angular
Angularisadevelopmentframeworkforbuildingmobileanddesktopapplications.This
bookfocusesonAngularDart2.0.Thissuper-heroicwebframeworkwillgiveyouasolid
foundationforfront-enddevelopmentusingDart.


Pub
PubisversatiletaskrunnerthatshipswiththeDartSDK.Puboffersdevelopersastandard
waytoexecuteawiderangeofcommontasks,rangingfromstartinglocalwebserversand
acquiringthird-partypackagestomanagingversionhistoryandrunningaplethoraof
custompreprocessorsandtransformers.

MongoDB
TheDartcommunityhasaccesstoafantasticprojectnamedmongo_dart,whichenables
theDartruntimetocommunicatedirectlywithMongoDB.MongoDBisadocument-store
styleofaNoSQLdatabasethatsupportsaDart-centricapproachtostructuringproject

data.


PartI:TheDartLanguageandEcosystem


Chapter1.DartandtheHistoryofBrowserLanguages
Sincetheinceptionofthewebbrowser,browsermanufacturershavebeenstrugglingto
enablealltypesofauthors—fromthemostbrilliantcomputersciencemindsintheworld
tothemosttimidoftechnophobes—topublishcontentontheweb.Thisbalancingact
resultedinthemostdiverse,vibrantcommunicationandcommerceplatforminhuman
history.
In1995,NetscapeCommunicationCorporationreleasedversion2.0ofitsfirstweb
browser,knownasNetscapeNavigator.Withthisrelease,itintroducedJavaScripttothe
world.
JavaScriptwasNetscape’sattempttoofferaninterpretedprogramminglanguagewith
anextremelylowbarriertoentry.Inparallel,NetscapeNavigatoralsoshippedwiththe
capabilitytoexecuteJavaapplets,enablingauthorswithastrongertechnicalbackground
todeploymoresophisticatedapplicationsdirectlyinthebrowser.
ThisbalancingactbetweenpowerandaccessibilitycontinuedastheInternetmatured
intotheglobalmarketplacethatweknowtoday.Theseearlychoiceswouldhavelonglastingeffectsonhowsoftwarewasdevelopedfortheweb.

TheWebandOpenStandards
OverthetwodecadesafterthereleaseofNetscape,oneofthemostpowerfuldriversof
technologicalchangetothewebwastherelentlesscommitmenttoopenstandards.In
1997,NetscapesubmittedtoECMAInternationalaversionofJavaScriptthatbecame
ECMA-262specificationv1.Thepoliticalramificationsofadheringtoopenstandards
enabledcompetingbrowservendorstodeveloptheirowncompatiblevirtualmachines
(VMs).
TheECMA-262standardbecamethelanguageofchoicefortheweb.Theupsideto

havingasinglelanguagewasthatwebauthorshadaconsistentplatformonwhichto
developtheirapplications,andbrowservendorshadasinglestandardonwhichto
optimizetheireffortsfrombothsoftwareengineeringandbusinessstrategyperspectives.
Thedownsidetothisunifiedapproachhasbeenone-dimensionalpoliticalbehavior
amongmajorbrowservendors,andithasresultedinanever-shrinkingnumberof
languagechoicesinbrowsers.Atthesametime,thenumberofvirtualmachinesthat
adheredtotheECMA-262standardskyrocketed,andcompetingtechnologies,suchas
Java,Flash,andActiveX,despitesometimeshavingsignificantperformanceupsides,were
deemedincompatibleorinsecureorbrandedasobsolete.Thedeprecationofthese
alternativeswasoftenbasednotsolelyontechnicalmeritbutonbattlesovermarket
position.


JavaScriptDeficits
Thedichotomybetweentheneedforpowerandtheneedforaccessibilityinaweb
programminglanguageisnuanced,andtheimportanceofeitherisoftencalculatedbased
ontheneedsandexperienceoftheauthor.Withtheincreaseddemandsplacedonmodern
webapplicationsandtheremovalofcompetinglanguageoptions,manyaretakinga
criticaleyetotheinherentflawsinJavaScript.
EventhemostardentJavaScriptenthusiastadvocatesunderstandingitsmostcommon
pitfalls.Atahighlevel,someofthesecritiquesincludeweaktyping,notruehashmap,
limitednumericaltypes,prototypicalinheritance,falsyvalues,unexpectedthis
behavior,oddequalityoperators,andmisleadingapplicationsofnewfactorymethods.
Problemsthatareoftenmanageableinsmallamountshaveacompoundingeffectat
scale;JavaScriptisnotimmunetothis.Thingsthatmightbetrivialtosolveonasmall
webprojectcangrindanenterprisedevelopmentprocesstoacrawl.

ModernAlternatives
Withonlyonelanguagetouseonthewebplatform,thedevelopmentcommunityhas
createdaplethoraofJavaScripttranspilersthataimtoaddressmanyoftheshortcomings

ofJavaScript.Eachoftheseprojectsoftenstartswiththegoalofaddressingwhatthe
authorseesasthemostegregiousoffensesintheJavaScriptlanguage:
CoffeeScripttakesaimatJavaScript’sC-stylesyntax.
TypeScriptisMicrosoft’sattempttoaddoptionalstatictyping.
EmscriptenallowsdeveloperstoportcodefromC,C++,oranyprojectwithLLVM
bytecodeontotheweb.
asm.jsisasubsetoftheJavaScriptlanguagethatishighlyoptimizableandgeared
forperformance.
ThemostnotabletranspileratthetimeofthiswritingisMicrosoft’sTypeScript.
TypeScriptisastrictsupersetofJavaScript,withitsbiggestemphasisbeingoptionalstatic
typing.Alltheselibrarieshaveachievedmoderatesuccessbecause,whileofferingvery
differenthigh-levellanguageoptions,thefinaloutputiscapableofrunningacrossall
majorbrowserswhentranspiledtoJavaScript.

ECMAScript4
OneofthemoresuccessfulcompetitorstoJavaScripthasalwaysbeentheFlashVMand
itsActionScriptlanguage.TheplatformwasapopulartargetforrichInternetapplication
developersbecauseofthefeature-richlanguage,excellentassetpipelinetooling,and
consistentinterfacetounderlyingvideoandaudiohardwarelayers.
ActionScript3wasAdobe’sattempttotoolitsfamilyofwebproductswithanextgenerationlanguagethataddressedmanyoftheissuesoftheECMA-262standard.Adobe
usedActionScript3asthefoundationforitsdraftproposaloftheECMA-262v4standard,
alongwithitsopensourceTamarinvirtualmachine.Ineffect,theECMA-262v4draftwas
anefforttocorrectthemanydeficienciesJavaScripthadsufferedfromandanopportunity


fortheentireindustrytoputanimprovedtechnologyintothehandsofthepublic.
AtthetimeoftheECMATC39committeemeetinginOsloin2008,Microsoft’s
InternetExplorerstillmaintainedroughly80percentmarketshareamongwebbrowsers.
TheECMATC39groupwascomposedofmembersrepresentingGoogle,Mozilla,
Microsoft,Adobe,andothervendors.Microsoftaggressivelyarguedagainstv4ofthe

standard,andinsteadadvocatedfortheECMA-262v3.1standard,whichwasan
incrementalenhancementandmoreinlinewiththeircurrentproductofferings.Afteryears
ofthegroupbeingsplit,andaprocess“miredinamorassofbickering,infighting,and
sometimes,outandoutnamecalling”(thegroup
agreedtomoveforwardwiththemoreconservativev3.1.
ThisessentiallyleftAdobe,andthesoftwareindustryatlarge,holdingatechnologythat
waspoliticallydeadinthewaterdespitehavingsoundtechnologicalupsides.ECMAScript
v4advocateshadnowaytotargetbrowsersthattheydidnothavedirectcontrolover,and
werefacedwithapoliticalandmarketenvironmentthatwasnotgoingtobacktheir
efforts.Thiswasanimportantlessonforbrowservendorslookingtointroducemeaningful
changeintothebrowserlandscapeinthefuture.

DashMemo
In2010,roughlytwoyearsafterthedefeatofECMAScript4,aninternalGooglememo,
commonlyreferredtoasthe“Dashmemo,”wasleakedtotheweb.Inthismemo,Google
outlineda“2pronged”(approachtolanguagetoolingin
thebrowser.
ThefirstapproachGoogleoutlinedwasconsidereda“lowrisk/lowreward”
(approachthatinvolvedcontinuedsupportforthe
evolvingECMAScriptv6standard.Thedownsideofthisapproachwasthecontinued
sluggishpaceofuptakebytheremainderoftheindustry.Inaddition,evenwiththe
eventualadoptionofnewerlanguagefeatures,thisapproachwouldcontinuetoinheritthe
corelanguageissuesthatareattheheartofECMAScript.
ThesecondapproachGoogleoutlinedwasreferredtoasa“highrisk/highreward”
(strategy.Thiswasaradicaldeparturefromthe
ECMAScriptstandardandarethinkingofhowaweblanguageshouldbedesigned.Itwas
tobeanewalanguagethatmaintainedthelowbarriertoentrythatJavaScriptenjoyed,
withthepower,maintainability,andtoolingofamodernhigh-levelprogramming
language.ThislanguagewouldgoontobecomeDart.


Google’sMarketStrategy
GooglelearnedalotfromwatchingthedefeatofECMAScriptv4.Googleexecuteda
technologystrategythatensureditdidn’tneedconsensusfromthebrowservendorsprior
togettingitslanguagetomarket.Todothis,Google’snewDartlanguagerunsonall
majorbrowsersrightoutofthegate.Itaccomplishesthisbyintroducingthreenewpieces
oftechnologyalongsidetheDartlanguage:theDart2JStranspiler,theDartDevCompiler,
andtheopensourceDartvirtualmachine(VM).


Dart2JS
Dart2JSisatranspilerthattakesDartcodeandoutputsbackward-compatibleoptimized
JavaScript.Thisworksonmostmodernbrowsers,includingChrome,Firefox,Safari,and
InternetExplorer9+.
Thetranspilerrunsasapre-processorthatoutputsminifiedJavaScriptthatcanbe
executedinsidemostJavaScriptvirtualmachines.Thecompilationstepnotonlytranslates
Dartcodeintocompact,highlyperformantJavaScript,butalsotakesitthroughaprocess
calledtreeshaking.Treeshakinganalyzesyoursourcecodeandremovesanyunused
portions.Thisattemptstoensurethatalltheshippedcodeisactuallybeingused.Dart2JS
hasbeendevelopedalongsidetheDartVMandhasbeenconsideredproductionready
sinceversion1.

DartDevCompiler
InadditiontoDart2JS,theDartteamisworkingonanewpieceoftechnologynamedthe
DartDevCompiler(DDC).TheDDCaimstoaddresssomeofthecomplexitythathas
resultedfromhavinghighlyoptimizedJavaScriptcodeastheoutputfromDart2JS;
namely,readabilityofthecode.
TheDDCaimstooutputhuman-readableJavaScript.Thiswillenabledeveloperstouse
Dartanditspowerfulecosystemofdevelopmenttoolstowrite,test,andmaintainpublic
nativeJavaScriptlibraries.TheDDCisalsoanintermediarydebuggingtoolthatwill
allowdeveloperstorunDartcodeasreadablenativeJavaScriptinallmajorbrowsers.

ThiswillemulatetheexperienceofhowtheappwillfunctionafterDart2JStranspilesthe
languagewhilemaintainingreadabilityfordebugging.TheDDCisslatedtobereleased
alongsideDartSDK2.0inearly2016;however,theprojectiscurrentlyhostedpublicly
andavailableforpreviewat />
DartVirtualMachine
TheDartVMiscoretoGoogle’sDartinitiativeandexiststopowerserver-side
developmentneeds.Itincorporatesmanylanguagefeaturesfoundinotherserver-side
languagesandpairsthemwiththeabilitytosharelibrariesbetweenyourback-endand
front-endapplications.
GoogleassignedthedevelopmentofthisVMtoanengineerwithalonghistoryof
buildinghighlyperformantVMs:LarsBak.Bakwasthecorearchitecturalcontributorto
manynotablehighperformanceVMs,includingtheJavaVMandGoogle’sownV8
JavaScriptVM.
TheDartVMisspecificallyoptimizedfortheDartlanguage.Googleoptimized
performanceforasinglelanguageinsteadofmakingamoregenericbytecodecompilation
target.HavingalanguageVMallowsfordirectinterpretationandexecutionofDartsource
codebytheVMwithouttheneedforacompilationstep.Compilationintomachinecode
isachievedusingaJITcompilerthatinterpretsthecodeatruntime.
TheDartVMrunsonaneventloopwithtwoqueues:aneventqueueandamicrotask
queue.ThisenablestheDartVMtoimplementnon-blockingasynchronousoperations.


TheDartVMissinglethreaded,whichoffersastraightforwarddeveloperdebugging
environment.However,totakeadvantageofmulti-corearchitectures,Dartalsosupports
isolates,or“isolatedmemoryheaps.”Eachisolatehasitsowneventloop.TheDartVM
anditscorrespondingisolateterminatewhenbothqueuesareempty.
TheDartVMsupportstwodifferentrun-timemodes.Thefirstrun-timemodeis
referredtoascheckedmode.Checkedmodereliesonthelanguage’ssupportforoptional
typing.Thisallowsdeveloperstotesttheircodeandtohavethelanguagefailfastandloud
whenthewrongobjecttypeisencountered.

ThesecondofDart’srun-timemodesiscalledproductionmode.Thismodeis
optimizedforperformanceandnotfordeveloperfeedback.Surprisingly,whilein
productionmode,theDartVMinitiallyignoresalltheauthor-assignedobjecttypes.
Instead,theDartVMheavilyusespolymorphicinlinecachingtoimproveVM
performance.DartseesmuchofitsperformancegainsoverECMAScriptVMsbyadding
supportforadditionalprimitives,whichyieldsmoreaccurateheuristicswhenexecutingits
inlinecachefunctionality.TheVMalsoleveragesrigidobjectstructuresthatareexposed
byhavingnativeclasssupportinthelanguage.Google’sdocumentationshowssignificant
speedgainsbytheDartVMwhencomparedtoGoogle’sownV8JavaScriptVM.

DartVirtualMachineStrategy
Formanyyears,GoogleadvocatedforDartVMtositalongsideJavaScriptinsideChrome
andotherbrowsers.Googletriedtoworkwithothermanufacturerstosolicitinterestinthe
technology.Theteamevenhadlong-runningexperimentalsupportfortheVMinDartium,
abranchofitsChromiumbrowser.
However,afteryearsofactivedevelopment,Googledecidednottopursuean
alternativeVMinthebrowser.Instead,Googledecidedtofollowtheincreasingtrendof
usingJavaScriptasacompilationtargetwhileinthebrowser.
AstheECMAScriptstandardhasimproved,thecapacitytouseJavaScriptasan
assembly-likelanguageforthewebhasbecomemoreandmoreviable.Thismeans
developerscangetallthegreatlanguagetoolingfromDartandmaintainthecross-browser
compatibilitythatECMAScriptenjoystoday.
TheDartVM,whilenotbeingdeployedinthebrowser,isstillunderheavy
developmentbyGoogleformobileandserver-sideapplications.Developerscanwriteand
deployhighlyperformantproductionapplicationsbyusingtheDartVManditsassociated
server-sidelibraries.
Note
Ifyou’reinterestedinseeingDartbenchmarkswhencomparedtoplatforms
likeNodejsorRails,takealookattheEC2hardwaretestsat
www.techempower.com/benchmarks/#section=data-r10&hw=ec2&test=json.



HowIstheDartLanguageDifferent?
TheDartlanguageisGoogle’sattempttodeliverabetterexperiencethanECMAScript.
Sowhatdoesitlooklike?ThenextfewchapterswilldivedeepintoDart’smanylanguage
features,buthereareafewofthehigh-levelfeatures:
Syntax:Dartsupportsafamiliarsyntaxthat’ssimilartoJava,C,C#,orJavaScript,
withadditionalsemanticsinspiredbySmalltalktoenableterse,concisecode.
Sanescopeandcontexts:Dartfollowstraditionallexicalscopingruleswith
hierarchicalscope.Childreninherittheirparent’sscope,butparentscannotaccess
theirchild’sscope.Classmethodshaveaconsistentreferencetotheinstanceusing
thethiskeyword.
Singleconsistententrypoint:AllDartapplicationsstartwithanamedfunction,
main(),thatestablishestherun-timecontextfromtherestoftheapplication.
Accessmodifiers:Dartsupportspublicandprivatemembers,allowingauthorsto
properlyencapsulateobjectaccessastheyseefit.
Optionalstatictypes:Atitscore,Dartisadynamiclanguage.However,theDart
VMandtheIDEprovideoptionalstatictyping.Typedobjectsproducemore
readablecodeandprovidetypecheckingduringexecution.
Classicalinheritanceandmore:Dartsupportsclassicalsingleinheritance.InDart,
aclasscanbeusedasaclass,aninterface,oramixin.
Dartalsosupportsabstractmethods,abstractclasses,andinterfaces.Youcanuse
thesestructuralelementstodefinesharedinterfacesinwhichindividualclassescan
thenimplementtheirownsolutions.Thesearelanguagefeaturesthatareoftenused
whencreatingcontemporaryobject-oriented(OO)relationships.
Mixins:Mixinsallowyoutoappendpreviouslyimplementedmethodstoclasses
withoutusinginheritance.
Multiplenumerictypes:Darthasbuilt-insupportfortwotypesofnumerical
objectswithamoregenericparentclass.
int:Asignedintegerwithamaxrangeof53bits.

double:AdatatyperepresentinganIEEE-754double-precisionfloating-point
number.
num:Agenericsuperclassforclassdoubleandclassint.Anumcanbeeither.
Built-inlibrarysupport:Importingalibraryisawaytobringacohesivecollection
ofclassesandmethodsintothecurrentscope.Bydefault,thedart:corelibraryis
automaticallyimportedintoeveryDartprogram.dart:coreprovidesmanyofthe
buildingblocksneededtoimplementthemostcommonprogrammingtasks.Youcan
alsodefineyourownlibrariesandsharethemwithyourteamorpublicly.
Built-inpackagesupport:Apackageisacollectionoflibraries,classes,and
methodsthatworkinunison.Yourmainapplicationisapackage,butitcanconsist
ofmanyotherpackages.PackagescanbeeasilyacquiredorsharedusingthePub


repository.
Pub:Whilenotpartofthelanguagespecification,Pubisatoolthatiscentraltothe
propagationofDartcode.Pubisparttaskrunner,partpackagemanager.Pubcan
downloadpackages,manageserverstate,executecompilationtasks,andmuch
more.

ANewECMAStandard
Fromtheoutset,GooglehaspositionedDarttobeopen.TheDartVMisopensource.The
corepackagesareopensource.AndwhiletheengineeringteamoveratGooglewasbusy
workingontheDartVM,theECMATC52committee,withrepresentativesfromGoogle,
wasbusydefininganewstandard.InJulyof2014,ECMAInternationalannouncedthat
ECMA-408hadofficiallybeenapprovedfortheDartProgrammingLanguage
Specification.ThespecificationwasbasedontheDartVM1.3instructionset.The
standardisnowopentoanyonewhowantstotargetit.

Summary
WithDart,younowhavealanguagethatworksonbothclientandserver.Itisbackward

compatiblewithmostmajorbrowsers.Itdoesn’tbreakanyexistingstandards.Itadheres
toanewopenstandard.Ithasanopen-sourcedVM.
IfirmlybelievethatDarthashugepotentialtochangehowthesoftwareindustry
handleslarge-scaleapplicationsdevelopmentfortheweb,andIthinkyou’regoingto
reallyenjoyworkingwithit.

YoushouldKnow
WhereJavaScriptcamefrom
WhyDartwasinvented
Whydesigningaone-size-fits-allweblanguageischallenging
Whatatranspileris
Whatavirtualmachineis
WhereandhowDartcanberun
WhatDart’slanguagefeaturesetincludes


Chapter2.UpandRunningwithDart
BeforeyoudiveintotheDartlanguage,youneedtogettheDartrun-timeenvironments
setuponyourcomputer.ThischaptercovershowtoexecuteDartcodebothonthe
commandlineandin-browser.
You’llbeworkingwiththeDartSDKandJetBrains’IntelliJIDEACommunityEdition.
Aswithmostlanguages,therearemultiplewaystogetDartupandrunningonyour
workstation.TheseapproachesvarybasedonwhetheryouarerunningWindows,Linux,
orMacOSX.Thegoodnewsisthatthetoolingsupportforeachoperatingsystemis
excellent.
IntelliJIDEACommunityEditionistheopen-sourcevariantofJetBrains’powerful
collectionoffull-featuredIDEs.TheDartteamhasselectedthesoftwarecompany
JetBrainstoprovidetheeditorofchoicefortheDartcommunity.Previously,thefolks
overatGoogleprovidedtheirowneditor,namedDartEditor.DartEditorwasdeprecated
inthesummerof2015.

DartEditorwasbuiltusingtheEclipsesoftwaredevelopmentkit(SDK),which
providedmanyoftheworkspace,plugin,anddebuggingcapabilitiesfoundinother
enterprise-levelsoftwaredevelopmenttools.Inordertoensurethewidestrangeofchoice
fordevelopers,Googledecidedtofocusitsenergyonmakingavailableallthepluginsthat
wereusedinDartEditorasstandalonepluginsthatcouldbeleveragedbyanyIDE.This
approachnowenablesDartsupportonawiderangeofIDEs,suchasSublime,Eclipse,
eMac,vim,IntelliJ,andmanymore.
Theremainderofthisbookusestheopen-sourceIntelliJIDEACommunityEdition
editor.

InstallingtheDartSDK
Let’swalkthroughhowtoacquiretheDartSDKforyourspecificoperatingsystem.
Here’showtograbthefilesforyourmachine.
Note
ThestepsinthissectionincludeaUSER_HOMEplaceholderinitalic.You
shouldreplaceUSER_HOMEwiththeproperpathofyouroperatingsystem’s
designateduserfolder.Forexample,mysystemusernameisjmurphy.OnOS
X,thestepsshow/Users/USER_HOME/projects,butI’llenterthepath
as/Users/jackmurphy/projects/.
1.Gotowww.dartlang.org/downloads/archive.
2.UndertheStableChannelheading,ensurethatthelatestversionisselectedinthe
drop-downmenu.Youwillneedtouseversion1.12orgreater.


×