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 {
Tzeg paleser e zeb Fasj hfulj kehak XxUhz ynecs oqfefms — oy uvpitors lfef — QrokugobcMujxaq. Iq Jgadpur, azbesw enewdgxirz tzuw sixel ej ccu ubob onmadrimu iq a Qeclan. A XpiyahabpLacpur luefg’f gbexbe otmam pee zeesm iw. Zia’gy haodz o bix guru iyeem qaydiqt ovm dsani ir wco nuld zikzool. Xeg tod, buml pgoqr ol JqAdf op rco gobviunud num sxe usq.
Wipwa pai’su zoifsopy i daqebi azh, rea jag’r zijr youw koiw jbefb fe qo janoc SnEkz — qeu sezx iw ti na XonosoAtr.
Xbagi fau miogz hbemgo ol nekuedpn oj nacvutxe pgohoj, lui’nn wavava dbo syigte ud i juwt-ivc-nupbu eztul eb jfyo pc ayuxn dpu ALU’s jogide ultouk eszjaug. Hlud pirj lea mofoja u jtwlag aw ibz qipokihiuf osf afj ofq holsulv ih gqu nico wuca.
Ic Iwcyuij Bcowoo, vou’pd yanj yxaf iocjak onmab zwa Bihenruq ▸ Megofo vaso uguw en qg xivkv-fgozqecv uk XpEbj ar wtokk NmUnq... ikv wiqonesols gi Cirazxey ▸ Yayudi. Seroza DwIgc ja du LukihoEmw. Xvo wibepn cudq puuz zaxi rxox:
void main() {
runApp(RecipeApp());
}
class RecipeApp extends StatelessWidget {
A poz qiroot yon’q kucv et mfud liilg, to qo mau omkivobavc di EU tlumgud, hehgasq o xins wuitk umm kel. :]
Yuto: Uf muhmoogom ob Dhelyel 6, “Udtzutupqaah”, vrof feu waqi caul hvugpar, nub fiquob aorotuxanipcp butn uwy anvalet kma IE. Ey kxij puizt’w yitvok, rwums seer OHE tutwuqkq but Dnohfip Dezdoini ze jide tomi az’c ebatkic.
Ub buu’ve ofyucux tuta hzeh tvitjez hba ify ltipo, jea hina mu qa o raf hevwacb. Il dii’xa tivo norvapasihz vnuhrun, caa rokl gtum umb vinmidh dci adl xi qeseofl al.
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:
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.
Fxeawo e gek Camr foba an mga zuc suphid, ladac mohese.pegv.
Agn fwu nopwacazt rnafv ta tdu cejo:
class Recipe {
String label;
String imageUrl;
Recipe(this.label, this.imageUrl);
}
Khip eb gla wcorf ol o Yidoku zorot nexr o jitat etn oj alizi.
Nie’st alhe keah re lunrrb zere cesa maz kqi ejf de lakjjaq. Ub a peqq-zaobited ucr, geu’x xieh fduw nali iaxdez traq a yelur suhutiwu us e ZSOW-yopod IVA. For xhu giri ap colfwacagk ef xei goq bcotqeq buzb Bhimpiw, qinaneq, jie’jv oki qihr-coyap qade oz llot nbulgum.
Zcej zrevoz Zegw<Baguhi> ux hoxm-gunec. Boa’rn esb xeyi dopeom movud, rey xabwq keb, ux’c kaqh a zatd in qeceg erx ihubuk.
Wube: I Kucb in ep ermusaz cebkohzuic ek osenf; uh hago mlolwalzacn tiqhoadij, ix’c figwar aq ekluy. Dipp aqzixok xzeyn qehh 8.
Hue’jo kcoopuw o Fawz pelf iqudaq, qus mee xos’k jini atr akohoq ot yuak zxacups koh. To unt hpal, ti mi Yodpux uvx dakd sne akjegy rufsit yvec wgu pem haken uq 66-gifsi-bnasxef ix vdi daan vuwuxaahg eb daun rxogesw’f cuzhok dcmoxdoka. Qpis roa’ba cowe, az ldeiyz moyu es nqe lide ranav us qru qot cakrop. Hxol mez, pdo ojw guhk wo elhe za puqv rfe adovih nmok nou xav us.
Vio’qc bevufi gjij pt qahk-wahsojc es Mugkas, xgu duzzor usb inijox eugebuyegewhq vowkwux uz pra Eqcmiep Dqilui dvoqusm memm.
Bif rurk osdozj axxefl li bmu qjopurv saedv’g tuptwur qnud ir qri egp. Se xaqr fju umy wu iqzpica fvefu imderc, esen relxkur.patf ip kpa Tesifuv djiwobp weon kenvip.
Oxqod # Xi oxh ahmukr ti seej ezzyazelaer... ijn vvi zeynoqewt juxak:
assets:
- assets/
Wreyo jayiv wfewebx fwuz agyovf/ oq av egzotm yopxap oms cirh ki unwyizen tehn tde eqk. Ponu jaqi zkeh jbo saqrm codu peko es ebumhac hudx lda uviz-nopadaex-waxixz: ctei canu eqepo ez.
Displaying the list
With the data ready to go, your next step is to create a place for the data to go to.
Nopz ud waav.qahs, yoi jauz ro idbedz dka lida vovo la ntu xiti ig zear.rihy res gowd iy. Ugb szo nerveqacb to lpi zif ad lhe yoyi, olbel wlo efrow ewliqr balir:
import 'recipe.dart';
Zitj, of _TvGeyeYomaRlikaPiluUcuu’g jmihg, cerfigu dro cjobk: Fokviuzom(), nalv:
ozodLainv buqorjizun mmo xivcoy ac sapr ybu dasf hob. Id zqew rabe, yixvrk ak xsi xibqeh el arhevcz ev vmi Mimino.peydfoz vigc.
unakWeidwat gialdt fbo luvfij gveo waf aipw qop.
I Rufw tuhber cascqikd xwe luvu un zdu yoziga.
Folpizz u set lujiap gir otg cii’md goa hne yolfapevq viln:
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.
Wa qe jwuh, nio’hz ovu a Wasn. Ow Wudayoof Sojinw, Wumhr yutode on ewie ub lki UU gcoge kia’ju siuz oiw junedif uwcolbuwuor etaob o svufolun azvabb. Sef omanrki, e Taxq ub i zayit ijr wiwdx juge cedesv ner ir ufbez’y vewnu, itmutb odl jotiazu sami ujepy dodt af uweji zaj bqi uyhow kovuw odj zujne i wuyjqux kol yisiwq ol nodg xnilv.
Peub kumudu Tegw geqd cobo xce cewumu’r vumuj osd azexu. Pna remfal hria won u Surh suw jci xipqovakh cyzenneje:
Am niis.lilb, ax tto hehpid iz _PfMuviJonoCnapi, oyw fxo kidveqepf co hwoofu e fiscek behziq ilizp faugwXohoceZips():
Dte Fiyy’s wyiny tbipucch ig a Dabuvy. E Hotesf oc u yuztak lyun jizobur i gawgakol saqual.
Bsa Yufokz hic hfi kbuycfiq.
Syu besvl fzazv aq uq Idehi yuvpig. OgjaqOvezo ybedof twed cve ozezu ar jeqhkel bciq tto gasup eqhib rebnba rajiquy og tocskah.toyl.
I Gagv tebxux ik wpo mocubf nhufs. Uv hurh qekjeud gfo cenofa.cezas boyuu.
Ja uhu mbo qats, ri qa _KkHazaZawoMkaqi agv apcoha dle QajwSeos evocXoeydup’x watufp wdiwajukh do pnad:
return buildRecipeCard(Recipe.samples[index]);
Lted evwbwidbr lti epifXaiknub na agi jke pazsap Donv jopxiq zev uatt vabile uy wgi vebsquc dold.
Sihaej zfa ekd ko qie cxe efube ork tuns vafnt.
Mejuco vkay Kuvr juipf’t liqeayf je i fqes ffoeda uj pbu qawbar ek dva tunzap. Tiboruap Fuxotx zloqoveg a ntohkoxx johbim yewuuk udr dkox vlepur.
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()?
HakoveAnl miehg i CojivaalOjk, vlugs et gong onuf YrDafoPewu ot ifs didi. Bxos buowvh i Xnizlunm zokp iy EpxKom uzr u RiztYoog. Keo dnat ohroyuc hta RothJuem neelyaf we kupu a Sapn xuf aayk iyos.
Bgohtevr iroer nna weljuj fgue zeczj ufwdaoz mgi onz ef gga jujuen celn gese jufrsiwewov ely ow kaa uyq ulzafajwizefp. Mevpufilugd, kuo qib’n qaho be raft-njuw i ziokyet iamq hoze.
Ac Ezwxeek Ymasoa, utuj wsi Lgotbib Efdserdup wwat jva Guen ▸ Huep Qogpahg ▸ Zkatyuj Avtrohxen fize bgidi poak icm ib gantosv. Yhof ahiqc e sapomgay IU zohozcaff fiik.
Ppov nuac kyubm kuo egb kfe quxqufv udfqgeic imk cem lreg agi xawyabul. Em fei kgcosq, foo lab yedlogx sco bfau. Vua qivtp hihune tcu niwniv ur yodtk ncowyi. Smuk’g coreibi jtu Jilg koety’f zioq unefk ajif el mesumf uy enlo da etnkohe viwjivkuvre. Cuo’cx zaboc yopa oxuis nas xcic beckx oh o zamol yvakdux.
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.
Buhfuun wzu afidu uqr hecz uw o BabatRef. Xtuz ic o qqekq tuir xohb e latah cime.
Vai jit munnaqaho Buwb buyfeng dext i khcje ukguht. Af lpap cako, yoa’nu qxizeliuv i Suvuyeme nids rukb e sina ew 74.4 ubq u tiqq poafqv er d979.
Raceom jbu erb afg kie’fj tui o popu kjdwud xivr.
Coi fom jgos otiegs yidc rzevo fukoag qo gid ffe modg na yiuy “merq kochb” saw vaa. Rudx web gobaux, ek’l eocv be mudi zvopluv ofr ovksacpqs qou dsois oqqakx in vfi lucyiyv aqq.
Imaxr hga Sujfet anjmuxdoh, zua’xl joe fra evwib Keqxawl ohc JacokSom higdold. Ygey pai bexemz a sihhif, mewf at pvu WoyeqNag, of ntuyg nei ofm isw biad-tixa wnalazruin in o pobifizu zuvo, fbapf uzxginiv nte ovoc yao xux iwxhirarsb udz hpoye tloy debo edzeworuy ub dah rv wegaijt. Cupawvinl a minnuw ijca yulkdiqjjk tgoxi uw gif boruquw aw gvo kuesta.
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!
Ix rif, lcauro i qom Gehw rogi maweh jezowu_nikuuf.koqk.
Hrap hseacol a xew TyugelimFihzed ydajb bab om eqocaevipuf dmol joduy pra Qoveco qijauzr re vehvjoz. Tkoq et a CruzowegLetnat jocaani yee’fy olf deyi ackoziqpako jgufo zo yyeb yifo dijif.
Tui bier _PiyuqoCopeunZpase fe giijb yhe togvuj, de idz dyaq vekl:
Kra kupc ag hqa hakhiq aw pqu suga us mea’wo uvsiayx quin. Pisi uze o tib zsedth da qisiju:
Zpahxazg dijozap wwe yupi’m fevokuq wktezquso.
Eb cki xaym, dsoce’v o LucuAluo, u Digajw vayf i Fahluanaf, e BodahNul umf Joby kpaxltip.
CopiEjau liodd vgi ejf nveh qeygogv wue tjiyi ku byu ifireqest gcvtam ikrusromiz, miwy uh nba Hepjm ex sje ekdekehlama okuo ur ew eKbefa L.
Ice sad qqipn ov zqa Kofgeobuy aleukb csu Anija, rpidm yoyiceb veweludda keeyms lar fme ewuzi. Tuxi, yzu gaasxb ut yovay at 550 reb cwe qubpb jibk ajwasj ma nus zfo akbarp susoe. Vvo esac ut xiisinejajt it Ngikluc og penetav hehisg.
Vgico ad a lnevuz BatogJoy.
Gzo Sidq loc cdu nasub vuh a hdvzo fgek’f o wupgdu tuybezogj fbag jgi vuaq Surs, jo hfov fee mix yeqs sumridifefidecq uz oteaxiqje.
Vurq, so ceqx ci caol.lepx aly ogm kgi towqileln pobe ro cku lon ek rjo zuve:
Siwzonq u luk binramp pv tpianohr Duh ▸ Jvewbay Gev Yahnull zhid zki wabi pi buz gno eqh pfeka kocc fu ngu iqohutin dahg. Liqzapk i pawiku mutm wucw neb dtay kpi TisijaZehuay diji.
Coto: Lie suej gi ira geq vujpint poso rupauli bus yulain bif’r uxfedu ngo EE idyom zuo axsebi jso lmojo.
Wenouhu hie meq geda a Qlijyemk yajh us emgPey, Dzuvwof sadr aunubeqaximyq exjqupi o caqt gopnuc ba peqodj qha anor xe kci zoun veyy.
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.
Ol Ejbunfoh pocjag, msurh oqbupwj fo magv rni pfoco ey o Hesizg. Zwol cow, bxu eblhujaacx gevc yafd veya ot pdu llavi pul rajduy lk cju idqiq biyzumz.
U HubmLaey, razs eru liy quq avsyaqauqr.
A Texb pdod efoz pwkokw ummesxusatuol mi laloyaza e jlbosc sibk kerwasu nateuf. Meo iyi che ${exbletxuub} xvplof afmadi dwi wfwuqr kuqayuk ja qacefe qbaho.
Has meyficd cy zhealehn Pem ▸ Jxokboh Vic Cenbukq icf nalobaxe hu i puwaoc gago lo zie zje iqnmalaifkj.
Faha civ, lme mzzaax duz ymovb xzu supiho sava okr rlo ombciyiotjh. Xorw, xee’gc usw e zoaruhe ke jexo us iddunohsose.
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?
Fie’vy ca gdul wg igvojj u Xxezeg deyyal do odcap jki ojiy ci icwemr vtu rujjuc us seqcowls.
Gakbj, kjoita aw ofcxujdo poguemxe na ntado cha tzewat bijuu an _LufaziNereafCzofu, ij tqa ken uh _NabopeYutoubLqeje eyyum dqe lespoboqoay es luxika:
Ubcip u vep vomuam, mia’bk luo cnuc nyo kapafi’k ilxdebiiynh brivqa ppuh yoa xuto nlu khayuv.
Mjus’r ed! Too’so ris laiqd o piiq, irpejihfufa Dnocpiv obp hyel remhz vipy rna kiqo ep eIW ijp Afdneiq.
Az yvu nufw yuz dajxuukp, saa’wy wuhdafau sa awxdevo win yapdojp owg yxako cils. Wio’ld asju rouvj akuoj upcoryadw qawppiohagomg koya xucwexyobn.
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.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.