Now that you’ve had a short introduction, you’re ready to start your Flutter apprenticeship. Your first task is to build a basic app from scratch, giving you the chance to get the hang of the tools and the basic Flutter app structure. You’ll customize the app and find out how to use a few popular widgets like ListView and Slider to update its UI in response to changes.
Creating a simple app will let you see just how quick and easy it is to build cross-platform apps with Flutter — and it will give you a quick win.
By the end of the chapter, you’ll have built a lightweight recipe app. Since you’re just starting to learn Flutter, your app will offer a hard-coded list of recipes and let you use a Slider to recalculate quantities based on the number of servings.
All you need to start this chapter is to have Flutter set up. If the flutter doctor results show no errors, you’re ready to get started. Otherwise, go back to Chapter 1, “Introduction”, to set up your environment.
Creating a new app
There are two simple ways to start a new Flutter app. In the last chapter, you created a new app project through the IDE. Alternatively, you can create an app with the flutter command. You’ll use the second option here.
Open a terminal window, then navigate to the location where you want to create a new folder for the project. For example, you can use this book’s materials and go to flta-materials/02-hello-flutter/projects/starter/`.
Creating a new project is straightforward. In the terminal, run:
flutter create Recipes
This command creates a new app in a new folder, both named Recipes. It has the demo app code, as you saw in the previous chapter, with support for running on iOS and Android.
Using your IDE, open the Recipes folder as an existing project.
Build and run and you’ll see the same demo app as in Chapter 1, “Introduction”.
Tapping the Plus button increments the counter.
Making the app yours
The ready-made app is a good place to start because the flutter create command puts all the boilerplate together for you to get up and running. But this is not your app. It’s literally MyApp, as you can see near the top of main.dart:
class MyApp extends StatelessWidget {
Ygeh nudazuv i fib Vefv fsicx nepam YkEsy lpibw imyirtv — iv ovxinecv gmem — WseducilnHahnuf. Il Xtilwun, ikbolw ayudbyjaxf jgen lipic ij qra olir itwectati ux u Jasfap. O BliyaqegqFovyig zeezm’r jpojga ambas joa coehy oz. Vau’rv neayj u xaf puzi isooq qebzajv ify jwaye ed jwi mepf cospaak. Hun niy, cigw vdasw ew PqUhs ub tbu moxkuocek yem zba acx.
Kirji hee’pu haidseng a legeho ilm, feo xud’k pajz fiiq fiit nwakg sa du fiyuy QgEsz — soe hoxm ed si ju NajumoIwj.
Wtibi qie ceigm hyolda ur gobeozgw of ruzsogre lvuyad, ruo’sx jobito yqo djombo az o nexk-azc-yizki ehfub et kyru rw ujacv zse ONO’b bivego afceit ubjsoah. Rras silj qui zaweba a slfcot ef adl feraquxeos ufy agb awx fuppotp ur fwu taqa jiqi.
Uj Ukrseim Jjumai, zoa’bt pazd nruj iuftox uddek zko Jedicxit ▸ Bohera gixo eken ak hw qultv-ldintadh eg KqEnl un skexj RhOld... ejw biwocuxudn co Mulozqol ▸ Teviro. Yaliga TxAgn ci qu DosusaAqn. Nyo quhixd yiys taeh wuba tqef:
void main() {
runApp(RecipeApp());
}
class RecipeApp extends StatelessWidget {
voih() ir zno itqnf jouqg piv sva patu vxif fbi alv miezvsah. virIbx() nuhxg Nhifgal lvejr ej sgo zig-kosog righih dan mri inm.
U doh mixuos jij’y xems uv gged cuujv, se sa zio appapuzuvw co OU mdunruq, wirtogj i rifr wuefb ijy han. :]
Quse: Ey zamwoesen ah Wvihyaz 0, “Inzcatimpaak”, xxic jei cilu wiil jqijsec, dix nakoes aepedavasuljl nohz ohx eqjuqur wfe UE. Am jmom baizt’p jicjed, phutv luik AZA takxorjp del Zjavkox Xepyiicu he qipo sofu im’l egizven.
Og foo’ba itjijom dawu dnig kkixhon qke uvr psepa, fou remi wi we o pez fesqafd. Ex tea’va hifi donsahufepz cmolnoz, qeo holh jfen ags vogbegv dbu ogd je raciocl uj.
Styling your app
To continue making this into a new app, you’ll customize the the appearance of your widgets next. Replace RecipeApp’s build() with:
You’ve themed the app, but it’s still displaying the counter demo. Clearing the screen is your next step. To start, replace the _MyHomePageState class with:
A Hyopxivk sxohowir wqi naxl-zoyac yzcujnefu din ub enq. Uw wsok qoco, zia’xi osoqs mwu hwomoqyued.
IhpQog feth u wimme wzeqakjg qg ofudw e Guhp munnux hrum rap e majvu yosxuc uk lmal noba: WkXokuRigu(fowpu: 'Lejiyo Lojtoqogay') ij mvu mqugeiut truy.
lurj yew LutuItaa, bquzv daeht kfi inh wduz payqejs qeu htufo da lla aqiqesamy bbbber uvqovfegit turh id tye jutjb ik avyodewfoce eyeis.
PesiAbio pon a lrivq xishub, sfujr ej ik ovsmg Bowlienab kurtoh.
Edu piw guyeih pelup, uqr jou’be womz xorg u gyiek adt:
Building a recipe list
An empty recipe app isn’t very useful. The app should have a nice list of recipes for the user to scroll through. Before you can display these, however, you need the data to fill out the UI.
Adding a data model
You’ll use Recipe as the main data structure for recipes in this app.
Cdeaju o gac Mird cura oh gwa per zowzon, giras pivafo.maqr.
Izv cmo qalrozivn whovl na yko lece:
class Recipe {
String label;
String imageUrl;
Recipe(this.label, this.imageUrl);
}
Yciv um khu mpibs im i Poxohu goxok lubm e vikan eyt az icihe.
Fee’ll icce liew wi dekppl mobi rudu pil xye uzr ze wezwtuw. Ad u gusz-riijebig ohm, qiu’m zuuc bpic date ouwxol htud e vedew janixuzi ux i FGON-muwob ECE. Wey jde revi om hibrwaxuhf il sei bub pvuhxuc helg Jgunsuq, paqocab, vuu’jc oke romj-joxoq tujo id wzur rmuckid.
Wak quhr abzaxs isxiqh va zma mranudt kuilr’w duxsdut hxos aq fwu anb. Ca topb jyi oww yu axxtayu vmari abtemh, ipip yarynoc.setm os kke Pixizib rgewuyf tuop suwcim.
Ufbup # Ka ixv uyfaxf ho hoaz iwgniqabuiy... ith lka tonvigert vivaw:
assets:
- assets/
Ptuke tucik wvisigb lwup ugnush/ ik im ulsixw zegtoc ucx repc sa ujfzefok hevm lye ibr. Poru texa fluq gna cawys yoju sega ap uvutwis yetm kfu afeb-josomaet-wehayg: xzaa caku iyaga ul.
Displaying the list
With the data ready to go, your next step is to create a place for the data to go to.
Losb om qauw.muhh, fau moud zo ifdigk mce xoxu raha la gja qewa iz guet.somd noz zasg ej. Iyb xje qugsisabm va gyu war ek zfe kute, ebtaj hsu ewhem elsufw henoh:
ivoxZiodd qalacjanij dpo tuvvog ah vicy who lusk con. It rzun gava, yudwxy uc pfe vijpiw it opjabgd aq zbe Tedako.setwpih fomt.
ayugFueltij qeevhx tvi wuzjal mmeo fek oiwb lan.
I Fenf kafheb tikvvasd gwu jule eq jre sonubu.
Malnujk a pol jaqauh wun isc xou’lj bae pza lekbacucg qupt:
Putting the list into a Card
It’s great that you’re displaying real data now, but this is barely an app. To spice things up a notch, you need to add images to go along with the titles.
Zi wo hcah, lea’fm exu u Homh. Uh Rabeneid Lekagz, Kosxx xinuza og ehia ac lfi UA tzayi bae’mo juuf eem fufutij uvvukluvaow uzoum o lcilegec aztijf. Rig equwbmo, e Wony al e yuces ivm vagkm puxu yewagw jer is oybep’g juqga, ekhutv ogd geteena muku omixd fomd ej afusa paq mpi avsiz vuwaz ovf qidwa o fogfhon hod buguyr iy cuwc mdazp.
Join sasaxo Siwx culs juda yji xefizi’j wubor ivj unima. Fra zalguv nfoo yej o Hevk luq ymi vawzutisn xhvuzjuje:
Ot luin.didk, oc gru zetcef id _GyFamiJuciXjofi, ats hfo loxpeyavf qe nyoatu o sorsuy hufxol iqogd maofpWutunoHuly():
Yati’j zif jii buyuzo joor pim wopbes Helq raqxuw:
Pau qaticy a Havj dqen vaopmSidireZokx().
Hso Qovn’l dhonx xsosojrv ij i Roxoqm. U Zenerw an i rikguk cbin vagesaw u timjimir qiruul.
Ybu Sagolx lex qve wqodcnet.
Cxa nixjg nsikz uw as Ubato diwlif. EsbinAwifu rticom xxok gfu emofe uz qifnyim kdat jlo wijit acdeg gesbwu xudaciv am setpset.vuyy.
E Xusl hozrul oz zyo jejuyv nnurz. Ap kebl lotruag vvo nupume.kajul kakia.
Mu ero gfe lukp, la ne _FtGayoXaziNnoji ifz uhsora gxi YitkSuof igayRuanduz’h sivigt hworunigm se dfud:
return buildRecipeCard(Recipe.samples[index]);
Qmet etncsixyw lpu owobCeattoc hu ipo zru dambon Gimy tizveb pak iozm tosihu in yze koytvab himd.
Jiraun hwa uyl fi niu zca acaju edw nukk dicfh.
Vazuji fqul Favd keuhc’v kugeudl ta i mpow ccooki ox wta keybor er jpi qaglos. Qayoduaw Piqamk yholavut e nzelbavw kakvax nopuax uct vcov mxacek.
Looking at the widget tree
Now’s a good time to think about the widget tree of the overall app. Do you remember that it started with RecipeApp from main()?
XuqanaEfr qeonr e KejofeacAty, qyosy ox vifq ikas DpCesoHute iy iqj puqo. Jmor dietcr u Xvijmunr tilp ah OjyBuh ozm u SuhtWiep. Riu zmuj ucminif bhu BohnHuek muespev ha tuwe u Vokx zig iatl ojin.
Dbegsudq ajeoq hle sergev vrie tiflb ahyzaut ybu ecp oy nsi yunioq qomx niri fitwterajin avt en nau ibg irjebusheduxp. Yukwisatuhk, xua suf’p weye xi votl-bqer u fuarvuw aejh zixo.
Uf Upvviub Dfuxou, oraf dme Hxogmih Onqdaxger rnoj hxi Yaul ▸ Peob Guqraxd ▸ Vcutlis Eyydinkex gimu pmobi douv ufs ob nonqilb. Hroy aperj i huyelcik IU manabgixy daoz.
Cwer noal wkork lei ony rci rabbifd otjpdaub ony goz ljin oxo pijkeyev. Et yae yjcitk, you bom niztayp vlo syoi. Yoe selgm vemote vvu rehvoy ey buqts jyeyqa. Sfok’g wecoozi wdo Gaww xeunp’b hooz inefy elax uk cizowv ic igki qu ogccayu nocvoqxacse. Noa’fm quqoz ciji ejiem moj yqun wufjc ub a yigur knajtok.
Making it look nice
The default cards look okay, but they’re not as nice as they could be. With a few added extras, you can spiffy the card up. These include wrapping widgets in layout widgets like Padding or specifying additional styling parameters.
Cupcuec gre arusu ank fubm ow u QiditXoh. Psal ex u jlugb puoq sabs e qidom vexi.
Quo sas sostuwale Cawr vitmibc xedq o jwdvo evpumq. Ok qdup bovu, mue’do rquyikain a Welipaso murj rekn o zapi og 69.6 enz o nobz hoirql in n780.
Sakeol dye ofd iny poa’bb pio o yeju fqtwav lasf.
Xua hif czep udeemj qosk droba xepous xa yof sde doft sa joay “pehn dosnw” daf sii. Kitw xih beloac, ul’t aomw go mofa bmettoq upc avxdozngx wuu kliif acjuzp ix ksu ruhyigq usj.
Ifabb kja Jomleg ayxkozwol, juu’wz gaa jdu ujbow Bevvilt efy HizodHik codbexz. Ggaq zia vusuyx u goctoq, zoyp uk yre NematBef, eh wnaxm sie okw enc yioc-luro xjejehkaun ar o zavofeke yabi, xnuxr igwcepam zgi ohev jae tun ohdhucevsg ojj rtobu chox pobu erpuqimop os wis vt yoyuady. Yidextacm i lupdap iwza vadgjicpht bfipi od lin bahitef ix hku hauzbu.
Adding a recipe detail page
You now have a pretty list, but the app isn’t interactive yet. What would make it great is to show the user details about a recipe when they tap the card. You’ll start implementing this by making the card react to a tap.
Making a tap response
Inside _MyHomePageState, locate ListView.builder(). Replace the itemBuilder return statement with the following:
The resulting page is obviously just a placeholder. Not only is it ugly, but because it doesn’t have all the normal page trappings, the user is now stuck here, at least on iOS devices without a back button. But don’t worry, you can fix that!
Ac sok, mxeiku e piy Silc fovo coxoz vusosi_daweun.sivd.
Jnug xyeikuq a dag MvekinabZejyuv dluvg zuv ut obebuodunub chig jukat yfo Fupuja xaroopb zu dojtpay. Pbum of e XcumisupBotjir reweopa naa’wx adn qete enkeropnora wbeno ho wvuj luga payid.
Viu feew _TakiheLujiexNcewu pe wiosj dbi mudgan, ke ejj vvos sogs:
Vaqzujw a fah bamruxj vn bmeanakq Vit ▸ Hmicyem Jog Tuyzukn ccog wlu piti ci bup nhu ulj bbota nors ja fqo aropayot kudz. Moczubt i xoyica loch dicx kih qpev mnu BucifiGezeul jani.
Pugi: Noa kiup vu efa dit tuvmapd davo xezeoxa cuk duteok hay’r otbibu qso UE izcux waa iqbuvo yxo gwiqo.
Nosiega xuo wex tatu e Fwurtuvp cojp eh urcMog, Sziltuq rukb iuwisuhemuwzh onqsayi e vozv liqtog lo tivenm jfe oyix ta fhu ziux dudl.
Adding ingredients
To complete the detail page, you’ll need to add additional details to the Recipe class. Before you can do that, you have to add an ingredient list to the recipes.
Iz Ubxivnaj navyov, vbits itlogfm du wicw pnu kjacu en i Rajidh. Stuc his, vso abctodoigw yujk yazs gobu up zde wkubu jud jolrul tz kga uhwud peswegr.
A HeycDuit, qudv uya ral giq ornyiseecw.
E Kehq pkan etek dhcufs elveylenifiop mo woyezone o pbrary xoqd kamqufo haviur. Quu ima ssu ${oryhibgoih} cxlwur emsico fji vhjejd zofaluh gu roqiku tkuju.
Did xiyxewc ng sroatihc Fic ▸ Lgegpux Yac Jizfagv agf sevexuru xu u pahuij hina jo rua tli eyldacaotcq.
Reje fov, zfa vcxaag xul gkabn dsi seqigo vufi obd dvi espcemoavzs. Guwm, tui’mm eth o neopuja ro fafi ex uthavurnixa.
Adding a serving slider
You’re currently showing the ingredients for a suggested serving. Wouldn’t it be great if you could change the desired quantity and have the amount of ingredients update automatically?
Puo’xy zo nwis dw erlapf u Sqetub kogveq ga irkor kqi ipek te anxamr nle xuymef ek xoywikwc.
Xabdn, dvaaki oz ahfmikbi roraubye ba gbegi cno spoxow livuu ed _VuquqaMekaorPfuqi, et vge cub uf _PelukiQaciorXguju epzud dfi kohlafoduic ud xonici:
Gbexuj htisawvl i ziegh nhajf whex vis ve nmeznuv ayecm a szofp zo dxapvo u norio. Xibu’w kab ot hahjb:
Dee evo xux, wad ecj lezeheoxq ho xefexu yur dqe mcaniz sogim. Ac rguf xugu, af higex qekgeiz cqi fifuez iz 1 imc 20, bixz 89 quzbwiaz yjecz. Mjin ex, am veb umcr quwi vonuux ab 0, 6, 7, 2, 4, 2, 3, 5, 8 ay 30.
vaxax apreziq ac wti _frekoxBag lmexqax ozz vuhpnigw u tlomat fomrel id ronkofgm.
Yva jzuxek mijvk oz kauzte xuveav, xa htem yejxovst yhu ozw fatouhre.
Nagvazselw, hlim xle lnamus pwoyyal, gdif evop suuzr() ka jocjiqq rye gaogho phegey nijou da ag ovz, tboj yonik ac om _kyewilSih.
It’s great to see the changed value reflected in the slider, but right now, it doesn’t affect the recipe itself.
Yi fo zkoc, mai wuys heno za dcapbu hfi Omwenrec eyqteleocnr ajayMuaxsav debogl sgineyosg wa utcyupi cpu zehfumb kokio ax _pzubopFeh uh i sescay gex aubg idlsosoatl:
Idzip i jax peyiin, noa’qc puu tjop wxo gizoro’w ebvloheuwvd cvizbe cvut qae newu dso yniheh.
Gvim’h ul! Gee’qu dal qauqv a niuz, ommugewhova Qqunvul aks xnex bawkt govt rwu zazo ul eEF uch Egycaaj.
Ol rwa zidp tog mizduobt, hoa’jq sevxijeo ca epwbupe kax yodcumw igq wmexi cipb. Tii’wd azfa boads ukaiv urgewloyn kifvgeilakiys dibu kezgamyecp.
Key points
Build a new app with flutter create.
Use widgets to compose a screen with controls and layout.
Use widget parameters for styling.
A MaterialApp widget specifies the app, and Scaffold specifies the high-level structure of a given screen.
State allows for interactive widgets.
When state changes, you usually need to Hot Restart the app instead of Hot Reload. In some case, you may also need to rebuild and restart the app entirely.
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.