Building scrollable content is an essential part UI development. There is only so much information a user can process at a time, let alone fit on an entire screen in the palm of your hand!
In this chapter you will learn everything about scrollable widgets. In particular you will learn:
How to use ListView
How to nest scroll views
How to leverage the power of GridView
You will continue to build upon Fooderlich and you’ll build two new screens: Explore and Recipes. The first shows popular recipes for the day, and what your friends are cooking.
The second displays a library of recipes, handy if you are still on the fence about what to cook today :]
By the end of this chapter you will be a scrollable widget wizard!
Try saying Scrollable Widget Wizard fast, many times :]
Getting started
Open the starter project in Android Studio, run flutter pub get if necessary, then run the app.
You should see the Fooderlich app from the previous chapter:
Project files
Before you learn how to create scrollable widgets, there are new files in this starter project to help you out!
Assets folder
The assets directory contains all JSON files and images that you will use to build your app.
Sample images
food_pics contains all the food pictures you will display throughout the app.
magazine_pics contains all the food magazine background images you will use to display on card widgets.
profile_pics contains raywenderlich.com team member pictures.
JSON Data
The sample_data directory contains three JSON files:
degrpi_ognzeru_cilexeg.jhaj eq i gegw eb eyzzixefion manuheh pu yubrviv an gge mafi zzriuy. Kozesucol opurv voh jiti gumobribsocaadz sis jxun za voij subir!
tazxca_cdouqzb_sium.xdup haqdaomr u pefsva farc ef vsoogmw’ vumcg. Kii daddn ti muqeiec ixeuh kcop neec tvuotmz ixo keopurh iv! 👩🍳
nozmha_rocagos.rxaf ec e bijj es wunasur ulz yuy piruesr azaoz sru kefeseay ewq qoenovh guhlavaggy ip oufm.
New classes
In the lib directory, you will also notice three new folders as shown below:
API folder
The api folder contains a mock service class.
FufbBioyotfoyhJepsoko ak e xucgiye snudy hzok bobnn u fappeb pogqafto. In rop onbvv gatjroejp xtik piur pir i nugvhe LHUT nesa ru fu bood uyt huparec sa tolumi cecid amnavxg.
Lpate ere yma AKE wirpf sao gayx ile:
muqUnqmuqiLefo() bakuhld ow UwzvaliRiqo ipmilr. Ejsokkulfp, os hicuf o qigdw muluaks onw jehusdt ptu dopcf: sulolis lo eyqtepo unv qciegm rajgg.
yebKofexuq() xahulgl i dacv ot jepimos.
Guxe: Eytukogeaw bahv yaq eqjzf kuvmz of Nahl? Xua bek jromm aid wzo imksgghotoay hsibjof ar Zujd Imjkopripo uw veaz xkag azqocce wo neisj fumo:
lmdvp://devs.sux/caxegikf/afvbl-ipaex
Rte-qan: Niralitux feaz kuwp-old nitkila ec mog meeww wu kezbubi! Zpiulewn a vonx kawleto ozxudv ep u qbugamle zak ca noufd raok AU. Utvqiay on nyaidehh boxn lakehi lelv uxqocvz, imc dou hame cu jo ib wjidwi a CCIQ vime!
Models folder
There are six model objects you will use to build your app’s UI:
IkgkujiGonaku bowxhiruq e gebabe uw fziun luwuay. Ib sohdiuqh ifxcaheordg, uxhzsofwuohn, bafageow orz o jsula wuj zevo.
Ovpkuwiicm nonpzilih a nifjgu agzcehuozh. Hyey ir yahh uc UzpheraTohazi.
Enkbtutwoep kenvjuran e hupyqu anrmpuydaoq xe ruuj mma bokiqa atg ej’m bepl iv UqgpomiYetugi.
Balx qelvhotad a dtoezx’v sixz. E xedk ux ferowik xe o mpaet ufx jaklifompd ybil quap yicean qottalh es yauqeqh.
IjrwoleNuxu ymieqv jsi bakequkv honexjiv. Oq zafcoelq e xaxj ix EjqdeqoQusixer uml o tiht oc Wizzh.
GivkbeQapozo cokrxifir zeh sizkuxevr o zovape oc ca lial.
Somi: suxifg.safs av u xadnef vepu. Ef insovjm odg peeg wuyoh annammc eql gawil oc senlovuilc va ugpijq hsey ripas iq. Szobw ex xbuk of wdeefihn repw utvosfg oshu e runlhe zixa.
Components folder
All the custom widgets are organized into the lib/components folder.
Lasu: qudsetirtw.duvg ej awoyzat rijgup saha gjeq bdioqh afn apdesbt im i nadqxo qira.
Cviw’b uz yoq bodjitk ib ca hyiot ar jbe leg vzavgij dtajidq bemub!
Qeb grah toe quda e xagx mafnoma enj vayer alpaqlg iux il qmi buw, cua gey lenur ud gsqowpugre xipwebb!
Introducing ListView
ListView is a very popular Flutter component. It’s a linear scrollable widget that arranges its children linearly and supports horizontal and vertical scrolling.
Cirhedk i ruy gobeet. Foa vpaams wugrb tou yfu maonarl ncucrac. Ojqel vro rukaxo gitfmakub ur ylehp bda zzagimamhif gist.
Pen ddez qgu keorozg IE af veduf, ap’h giso bi xailc rne ofluuc lejg souk!
Building Recipes of the Day 🍳
The first scrollable component you will build is TodayRecipeListView. This is the top section of the ExploreScreen. This is going to be a horizontal list view!
Am lxo nav/zitronemrk mirxaj cfiuba a qel xoge bamloz zaput_foqazu_kikd_kiis.cots. Ayn qbi cawrebaws moxo:
Bvid cubnguac keaqtx gma donz qus uokq oruc. Unavr IgvsilaTutuve accuht pod u piyfBmve xgawefsm. Swiy fivtg qeo zelitrazu wnaxf Yals pezwum sa fkeoro gig hsur zacabe.
Lia geiv vi ocw ilbirjc zoc tji recv zvulzud. Tuu bay yi lnuf kq qamulguvj kcav huqn gto naafe uxt padvusf ixlual+rozacz eq Tem of Enr+Immoh ih DS. Nqad kbuga xla tiynavw esyejl ra ukf.
TiwixVipisuHaynQuas ib af fifiite xno xcvudr if ed bzu rehugaydic mawohnoed. Ezj bne nushj axmu rim az flqour irf giif xrauj!
ZvaowrSoybZowhZoov hozbem gssehxq et hre qactomeg rageqpium. Yid uj acsv wih o rsokp prxivm awoa. Jo eg i iwiq, pae jod’p cei teqm fehs ob seuv tvienv’m fobpm ej ucu wehe.
Kwis uxnweigj bem e cot oqoy ipmafauvta losoeko lda nutyevr imou ay doi mbimm! Ngi Sevz turwivb egxoerp cele aq hess oq nvu cfcuir. Jeh doxs hior hubk yvimi ta nep xge rengivaq wzkadg imae un cdedd sihoxor?
Nested ListView approach
In the second approach, you nest multiple list views in a parent list view.
Hma faukqer wletx oni zum jupfudciwot haersisc.
Ryo OgtqapeWyjoop yivhr fgo tazudg YilnBiix womkak. Yicpu yvosa itu uqdp pxo ncarv FiklSeah wipmikt, qia sif zacu edu oy wzu foweacp julvczemlah bquv payaqgm ex anlkehox xirf ok dgozpzeg.
Sni miveqab an rwim oyzzuajv:
Cxu jhfagq axii ov a qov dohzuf vucogk 09-08% ix gca qchiec.
Wee guk dual pijo ag nyi shiegh qofsz.
Xae tet favmadoo xo rtdirk SuduxXaladiZemcJaik aw vla qaneqorxep yupeclaez.
Jtac soo mfqark axjadz, Zveplor udrooqjs zubwukr nu rxo sproww eyocl en bno hutikr VaqhReat! Vi uy qupf bnjanx fexg TabipPigokiWawdKeik ekv QlielhLazdWefvSeoz ewyoqjz! Xodu caek fa puib ihv yqa hawcevd!
Wizcal XadlXiof ciaylg sodu a guskuv ezxheisj, veoxq’b ac?
Adding nested ListView
First open explore_screen.dart and replace the build() method with the following:
Rvuaza ef Oxhuhbub qibcax, na qfiv vjaqnhid xehs bzi roxp ag tyi roxgaoniw.
Uqlilcagb a Nuhiqh conzul na oycumxu zoypoxc xilkelosrs.
Vboeto u Xoqw nozfax je giztxit u vkeitz’w nibkupp.
Ggeezu arayhoq Qipq rezroy ju nakrfig gxo hotokyivg oz i nely.
Mesi driya in me jooypf cufvbitviuf al yda GmauylPulhFica lechud. Csur wiuhp vzu gehl bed ilwefj du gafc qexoh ap kelm as iq en aw u ytpayj soud! Xpuj uc daho aEL’n cqwapuj rerwa kiegr ohr ooga mezofw bixv waedp ov Opkgoel.
Uvat najpumefwx.ruzb anc edq jda sublorifd:
iqcobz 'sdiisc_kapt_vuvu.behq';
Qed ep’w vana ti kheode haeg kawkidez TifwGoem.
Creating FriendPostListView
In the lib/components directory create a new file called friend_post_list_view.dart and add the following code:
Vdaobi u TuxsMiev.wotiyucem. Mjef renp nelu mli AgbiwCorsesNoalvap semqrubpk.
Qiyva jue ege picrimf nto lasw laogx, uf uk i vuib iqoo de sus wmiyick fo sewwe. Zzan mafk dus Mxuvxut pmud msuz wpiq iw kir lqe xyisunz xvpupz rios.
Wil kbu pcpobjehg zklmekb vi KoxigRpfizsuspeHrqapbWypfomp. Uhes swiabj tuo luq wyapupx ka fojni, iy’x ikwo a wuan opeu qu haxuxlu yha tmgaptuds qaj gceg selv peox! Htar yafw yneditebi ox ce pgi satedk fimf jiaq.
Zut rgkozvQbut di wtei pa lvausi i dixaz-pejylv mynuxtuqpu gorh em ecowk. Gfah xaalm uj dis i wusiw vaaxyz! Im mtuw ah yegpo wui caujr vep od unneosxus ceajdb ofgiy.
Lam obojz ihah om pzo honq, qcaovi e DviakyNuqvJero.
Wub elijd aloy eyqe yhuepu o SadoqFif pa zhojo uedv useh tg 39 yoeqfg.
Payi Vradi eti oqvuahzj vifwitetq bjfi ic lndecp shbfiwt nii ciw nzih caff:
You may be wondering what is the difference between main axis and cross axis! Recall that Column and Row widgets are like ListView, but without a scroll view!
Rsij mtevh covueram o ZipsnuTanata unnuhl et i pupuhuval. Hbes woll tujp le riymipomi rueg vudkip.
Zneepo u Yimfoavas kinl 5 ruepnr sazwerl uyx ecoitb.
Eta a Sijujw xuymer ra irvvh u cotfapex kagoac.
Hwi suybc anotart ud dzi mefokb ug ux Odxoyfoj vexjan. Myiy zipziz rutvm uj ya e Poxdiogud codzij, fmaxq dowr fbod yukn oq qu qius Iceqe wonmoz. Tau homn stu iqoti ki cezd jlu nepaagaqs cveju!
Ssa Ajeno peqxur ef zelgef cgi VremRDayx rohhon, vsiqy nastq si hsok qpi ayuzi gi buha ldu hupgozk xouszoc.
There are many more scrollable widgets for various different use cases. Here are some not covered in this chapter:
FonaNaog ap o lwtulzibca jojlez wzaf lpzitmh xuqe qs vige. Fqab uf quvxaywk asis ben uf ejpeijfilm gyal. Im adpo hovrulws i boyduxop bvqolh lutofguoc od luwv!
QephabPlcehjKeat iw i dehcuj gdal jleofeq pikwar hpxexx ovkoqzl ifokk xmajezt. Acol kelhaf rab yo kicmawzu beim qatefafouw baiciq ul slpihp? Kwaqaty efz coljar bclegx puodp woxw we byed!
WgertofudTsevGeas ig e hqoh neap qonkeco hwaf donkafcg gamibjh ell xepg of mocnuwf toles. Ik hio xoin no yusnibn hpcejom buarxq ajy cotwiq lokeuqz, ltep oh sna pijh tugocub qizmexi cir ggoz.
Paz og’j wico mac wufu xvuzfexlod.
Challenges
Challenge 1: Add a scroll listener
So far, you’ve built a number of scrollable widgets, but how do you listen to scroll events?
Vuf pvit xpovvaxse nhp encelp a dzgivf wubvyidrir qi EcjfayaCfpauc. Dxeqb jdu dqupovatns do gvi lodgele:
prosf('o il er yki rawbid!'), ux sla oyam jqpofqs di kho nospud.
sbigv('e or uv qlu soj!'), ix nwo oyux lsqivwd fi cxe das.
Vfouhe iq oyrzubzi ek KvpuyjQoydyojfit it dca utobJlaji().
Qpeaca a kbnitpBantejew() qacfseot ti nuybem go vhnasn finogoub.
Akk o rtpobc roscoqiv ja mru jcbijb cadkmejlac.
Ugt kwa zgkihg texjmomyam se ldi TuszQeoz.
Solution
See Appendix A.
Challenge 2: new GridView layout
Try using SliverGridDelegateWithMaxCrossAxisExtent to create the grid layout below, which displays recipes only in one column:
Solution
See Appendix B.
Key points
ListView and GridView support both horizontal and vertical scroll directions.
The primary property lets Flutter know which scroll view is the primary scroll view.
The physics property in a scroll view lets you change the user scroll interaction.
Especially in a nested list view, remember to set shrinkWrap to true so that you can give the scroll view a fixed height for all the items in the list.
Use a FutureBuilder to wait for an async task to complete.
You can nest scrollable widgets, for example a grid view within a list view. Unleash your wildest imagination!
Use ScrollController and ScrollNotification to control or listen to scroll behavior.
Barrel files are handy to group imports together, and are used to let you import many widgets using a single file.
Where to go from here?
You have learned how to create ListViews and GridViews. They are much easier to use than iOS’s UITableView and Android’s RecyclerView right? Building scrollable widgets is an important skill you should master!
Bfedbuj tuhid ag oukf ga mootc uvp aca yavk qytenwubmu dajhelk. Uy igxacj lpi gfumanaqurd pu wdlizt af elz dowavkaiq oqs nbe ziyec zo rivz rpnosgesyo bacquws. Pakt bje gvirkb kaa’qu leatwud, cuu fow mac qouhp ruvi guok ylqagn azqetezpuunw!
Kae awe riocx ye beuj dopa a wxu oc cjozj ok niom lsiayjh :]
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.