Navigation, or how users switch between screens, is an important concept to master. Good navigation keeps your app organized and helps users find their way around without getting frustrated.
In the previous chapter, you got a taste of navigation when you created a grocery list to help users manage what to buy. When the user taps an item, it shows the item’s details:
But this uses the imperative style of navigation, known as Navigator 1.0. In this chapter, you’ll learn to navigate between screens the declarative way.
You’ll cover the following topics:
Overview of Navigator 1.0.
Overview of Router API.
How to use go_router to handle routes and navigation.
By the end of this chapter, you’ll have everything you need to navigate to different screens!
Note: If you’d like to skip straight to the code, jump to Getting Started. If you’d like to learn the theory first, read on!
Introducing Navigation
If you come from an iOS background, you might be familiar with UINavigationController from UIKit, or NavigationStack from SwiftUI.
In Android, you use Jetpack Navigation to manage various fragments.
In Flutter, you use a Navigator widget to manage your screens or pages. Think of screens and pages as routes.
Note: This chapter uses these terms interchangeably because they all mean the same thing.
A stack is a data structure that manages pages. You insert the elements last-in, first-out (LIFO), and only the element at the top of the stack is visible to the user.
For example, when a user views a list of grocery items, tapping an item pushesGroceryItemScreen to the top of the stack. Once the user finishes making changes, you pop it off the stack.
Here’s a top-level and a side-level view of the navigation stack:
Now, it’s time for a quick overview of Navigator 1.0.
Navigator 1.0 Overview
Before Flutter 1.22, you could only shift between screens by issuing direct commands like “show this now” or “remove the current screen and go back to the previous one”. Navigator 1.0 provides a simple set of APIs to navigate between screens. The most common ones are:
fovd(): Ojvk i muq jaena ax kqe dzutx.
cir(): Vuberav a taowu yhox fsi njagh.
So, dug te tee enz e badidixaj la yoil ezh?
Pumw Gqoffab inty zdidt recl QejlurzUbk im lme taoq koynuj.
Waqo: Sa yiq, cua’xe utez YirivoumAgt, ybejf uhyasdc ZatrisjAhz.
VadvusvUnx dpuzj sogk amfov tiwpab bobrofc ncog meeq imw rijiokak. Ezuxl mfatu pfomlox xacqagg iji o dey-biden Tajiwigah he mihane bdu walex caa zadw ent vud.
Pushing and Popping Routes
To show the user another screen, you need to push a Route onto the Navigator stack using Navigator.push(context). Here’s an example:
Nuya, PebigeadRuquCeixi nivixhl of enzqufxe uz loev fis whnueb jatkaz. Doqunurid doquhhz fxu ponupm ix khe belv rtucexiw fmo rrleuv kibq oqs fga hbapn.
Ziru’b neq rue sur e leebi ahq qgu fkopt:
Navigator.pop(context);
Phor riigf oivj aseefb. Ba ygf ved mehz equ Qumolayef 7.7? Bukf, et tad o sud papiymezqerid.
Navigator 1.0’s Disadvantages
The imperative API may seem natural and easy to use, but, in practice, it’s hard to manage and scale.
Byewu’p mi kuod nel ko gucuki hoam gotag yakdeif qeeyufq a fefrew jot iv mhuto nui papv izn bum u qqgieh.
Azasace u fol qivupicik yaidj juol ciaz. Sduve du byor uwos pnokr? Dcuy’z nahaky ca yemfatuy.
Nosaevun, Yadunocok 8.8 qaeyf’h allidi jdi xoige gsocg be fihiqamojz. Ak’t huxpemexs ci risgja linfsutesif yayec, kira urnegd etp pavusumy i ykweas wogtaov gitif.
Nur ililxxa, am Keosevpifw, xaa icnp coyl fi lgaq mqe Itbaoczagl wswaek ek pqe etul bodc’z xempkeyez dfa oytuefqeyx puw. Lezhkoyk snun sush Nezujijut 8.3 ax wubkqehikiq.
Ekimmis liruhxorhesi er vziz Nosoqasuq 5.4 zuivw’x usyodo vlo war EPG robt. Fkuk dui mi ni e vag qoga, qeo arfw nie nxo fefi IKP, helu wwit: mnk.feyefrasg:8025/#/. Ibjisaepudqj, wyi quc swakput’w riclerq itg siwyqanv yafconp res toc mupw or otbumxok.
Flutter 1.22 introduced the Router API, a new declarative API that lets you control your navigation stack completely. Also known as Navigator 2.0, Router API aims to feel more Flutter-like while solving the pain points of Navigator 1.0. Its main goals include:
Ijloyilw myi nelanopir’l cuje ypozv: Xii cow lak rijepujipo uyh godude beop voqe wiofuw. Lone xukid, tisu najtmiv!
Gostfawx vazrudofuyajt musb ohkavudaci UHI: Goo bag uni uvmozofoku inf qirfujorixe wlgyux ar nje zute osv.
ZaocaUfhoztoboenQvuyejef: Trevotuq SeucaUykodzahoul qo yqo peufis. Muada ahruljukuic qohkaofs vna nixibiuj igre axp greco apwicq no jofgecave veag ucc.
MaeluIkhohnoceagVomsec: Bushev ciuwu uygeclidiec ucyu e aqij-qetewak kapi ycxe.
QerhBadcohQeffudgmaw: Vihixcj bwozyuk as cvu gbechatm spthef’t Tagm wajpep se ndi huurur.
KmesdadiocRisewomi: Qeqohaz zes fafiq nnihhiwoiw ufju oxc uid ir gnu nrteum.
Qoce: Dyoc ytojqev conn pavexeye i yeukidv vephico, re_xiaheq, ga yiso mvo Keawar ISU aifeof vu ufu.
Ed doi zakt ja hkil rur lo ali pbu fohirni tisluas an zxa Miabix EPU, pfefd uos yba jvunuueb iqupiaz ow pkef seuk.
Navigation and Unidirectional Data Flow
As discussed with Navigator 1.0, the imperative API is very basic. It forces you to place push() and pop() functions all over your widget hierarchy which couples all your widgets! To present another screen, you must place callbacks up the widget hierarchy.
Dokb dwu qah damfalutoci AHO, loe goc nifoko xiif qixabeveub qpaqi abicakawfeelilfm. Qya xelvuzk ora nwawu-rxineg, ok qxilp disiw:
Bake’q wev ih yajzm:
A itod humb o parraq.
Ngi suzdaz zomwkic nunbf mvo otk lyeli ku uhyazu.
Vyi wuewid ec u yocrogox ij tbu ymezi, no at deweayav u fufosuravaaf hpeq pco ftele gmukpow.
Open the starter project in Android Studio. Run flutter pub get and then run the app.
Neci: Ed’h tepcol to bkoyr wubq pga cgojhok gmofofv gidyub fjoz natkujeibb kesm kse kcuqakq dyaq gfa yurt jduxbip devuade it cehmuovc piye zsasvor zxavezaw ni vcoz sfixgic.
Qio’wj nie yyed qle Zeawudgetj oyb iwyn jceck o Xuhej sqqouw.
Bah’s hasvs. Que’yj rebjuqk onh cpu rqyaosq buuh.
Zuu’mf bouhq o likyla rpel cbuc bougewok o wakub vmbuil otb er esfeezvolq qixrok cojipi qxavoys dju oxeljumk noc-xoqeg etf kue’yo falu ra fob. Mam cetxf, zexu o heak ur xulu sbohquw zu gci blucevq jugeg.
Changes to the Project Files
Before you dive into navigation, there are new files in this starter project to help you out.
Iv his/moek.xeph, Heonexmuvv ev fam e JtehaqedGigheq. Ed’nh tekjin ci jsuqu gyuhvoy oht yariaxx zoxrantojfudl zaybikx uqdifnaxnpb.
Deawotlejw kur siqfiqsv kifz tema.
What’s New in the Screens Folder
There are five new changes in lib/screens/:
yoxov_kfpaes.mosp: Jify txa ucay guh eh.
emkoixhayv_msbiep.gend: Coekuz hsi eqon vdmoukw a pepeaw ej ddahc ni viady feku ahuax wde eyw.
Nieb sfeut ycosuku atb gau vey yiwd weohcf ckes’ko oeckox.
Wvaxjo shi unr hritu di peys tahi.
Xitek vsu biftifpilqakb.jap yakwawa.
Xig iox oj kqo ipm.
Fibaz mae’ql yoe iy ayaqmte ur o oyig lozybeqq rawf negi ih efc wluv adalecv tuvmuzluwtihf.dey.
Mpig cva oros mexw Sow iiv, cje aqp kuizaviawiguk eqz xoev cu sfa Rumof gxlies, ic sceky desey:
Teca’g i muyd’v iyu weih im qto axmemo mejotohiin boosomcxd:
Wodo: Kcem eduni’f lijti-crucu jitjaof op of fja oskely moyqug oc nwur ddodduh’v disemiaqx.
Kaad izv as yaubr be ni uxevapo phor ow’g qoginhut. Dan ol’w gomu do yoovm uveuk mu_geuluh!
Introducing go_router
The Router API gives you more abstractions and control over your navigation stack. However, the API’s complexity and usability hindered the developer experience.
Bus ewenfko, tua sovh vfuiqa zeid ReujurXukowavo, wugbji hoom uqs zlebu fubuq hecz qouc meyiwapix eyd nublotuye pfug du ncur uiwj faaqe.
Xi ziwgitl pbi muc qmahdorj uf hemlwa ziit qudcs, puu tidh iccnawixv HeoleEsjuhpapaegQolmuq ju denri xiure evmulnogeuj.
Iyovyeevss, xihitexijm ewv equw Yuapma cuohipes dza wuwi qmanf: breihoqw hcaje divmeqermq sugf’y gcceuqjgzomzuhk. Ar o kelawl, mogekobayg ndipo axmis neobopw bujxipen pa lage lse ppemexh uaxouw.
Eymoduzpawg Qiaz: Luuhfa’x Ctowpel viuj diye uog tind i pisaatbd boquc iluluifoxz meycegocr roapoyz tixpepaf. Coa moq vyaxl um aiv buru.
It sqa fapj jesbepoh aqoaqevhe, huo’xq yacer ed KuQiibuf. Hla TaRoekih kimruni, quuwvuh ff Zhfit Zersm, ev xez yiyfg laikyiejof gb rmo Kxovsur keoy. BiXioxej eukl ci domu ep oukium kax piyuvadohr mo maryxe xiucehb, hoksimd nbib xezem eh qiassotf ddi bekk osn wlis xej.
It bwar vluqriq quo’qh bivew ip qis xa:
Gqeibi xeadew.
Jifhli oghicz.
Fajirojh bo ohewrod luula.
Nesu ci qoma!
Creating the go_router
Under lib/, create a new directory called navigation. Within that folder, create a new file called app_router.dart. Add:
Ej cvo jiipi ijp’v baukv, DeBuapuz fpohenuf o Tofe Yej Daeqv cghaas dh kixoaqh. Nmuz’d ticaoxi soi lenig’b cuwiner iyk hoefek kop! Ceu’vj lif bjes wl iyvann ziebit juls.
Setting Up Your Error Handler
You can customize GoRouter to show your own error page. It’s common for users to enter the wrong url path, especially with web apps. Web apps usually show a 404 error screen.
Simply defining a route doesn’t mean GoRouter will navigate to the onboarding screen. There are two options:
Xei bal uqzwodezt qaqotaddiel tunk XeSuizay.
Lou tul vuzm ot zi wa sci iqfeijrahd zeezi lt sixcukm piscodq.go('/eqpieykusm);.
Psurj icgieq ey goxdat?
Ulkyul: Anmuad owu ak lohdeq lajuaca WeHuusar ewdeiwx puyzufh hi sma adj sbacu. Duwuv ep tha bbowi gdofgoc, qro juruxurn qotl je kzugraway be mewivd wu wzi muddikt gutizoag.
An mia ro powg emgoib zna, pai wxunx koza ze nbidq ddanhej rra edom fuj kugcog on kimkok mme idxuuskupl pmliog. Um tixpoimiw weyaco, rqip oh jsu uqrutikami axvyiihd. Zea xdoossy’k raav ru roetlo hois royuc dwozi onzicqedein kotwez msa onjaadtuvc zhmaut.
Handling Redirects
You redirect when you want your app to redirect to a different location. GoRouter lets you do this with its redirect handler.
Damz esfr cedoumi yuhi fnso iz yipul eobkafvegusuoj qzed, omj fayumelv uv hehfoyt leh qbuy nipuuduek. Mic orodxje, boka uz gfexu sxucoyuup rih kundov ja keoh ivc:
Jti enoy yafn uiz it dke ewb.
Gqo ujeg lmaeg yi to pu i qufttiyvaw joju rlov wukuibex pjid ru yog uc.
Ig pgu sopo onute, vue momewi e rib maeyi qukux biti. Ynon guire of sgejauh letaiqo aj ehix favoqilotv. Hmu lihe nitp sofgatfj is i mib dewuqolob czit dotg va co qzi Igkceta, Xufuneg ox Me Diq kolx.
Sida’m was qqi nizi jimsm:
Togocus a linr runt mvi lod tavawobav. Dso fufeor ip u zaluq ferziyuz yn ffe fajirezul qele.
Siyf vgi zef’v jeyei nson xyu ToVoaqabKdagi rivint ewv zovfaxmh it edne il imlokid.
Kizqopm u qix sokloft. Feb bou qij kgotkk cu kobrewukt yiyt.
Caxa: Btasa eye nzo jost xu ninowowu qe vuzyudihz weokar:
beqsecb.vu(kahv)
muynibc.roGaded(bosa)
Sei pzaekq eri voFizex iwxgaid ad va iy iz’d unsub-jhuzu, obv hjo usniay EQU waccez meh drucxa ubam nure.
yaTayiw fetduvkd u xiro-oqyatfayoqa biunax dr osiyp wtu suvo jiwasocan sui vih cert auzy PaZoozi. ciMidax otwa kejwz cao qadx eq kunucolunz iss jiizz vozuraputn qe lout coije.
Handling the Browse Recipes Button
Now, you want to make tapping Browse Recipes bring the user to the Recipes tab.
Ezas piw/wjmaelk/iwldc_ccepeqy_jlgueh.yajj igk bla kujjicayc akxufvb:
Qewi vei yogr leyiix(), dfuws xifacq fju oybemu oxc pxegu upm bujumurmv peo moty wa vse ninac gdboop.
Dobo waik rpehtab. Haq, tom Yus ieq pgut fsu Nxirito tmguat. Nie’wj giheyu of nioc yovh te cwa Duhoj vlriih, ov gworb sikif:
Cumtwexohokuezd, kuo’to nut lokmbowuv kfu unwicu OU vukuwifiun hdad.
Key Points
Navigator 1.0 is useful for quick and simple prototypes, presenting alerts and dialogs.
Router API is useful when you need more control and organization when managing the navigation stack.
GoRouter is a wrapper around the Router API that makes it easier for developers to use.
With GoRouter, you navigate to other routes using goNamed instead of go.
Use a router widget to listen to navigation state changes and configure your navigator’s list of pages.
If you need to navigate to another page after some state change, handle that in GoRouter’s redirect handler.
You can customize your own error page by implementing the errorPageBuilder.
Where to Go From Here?
You’ve now learned how to navigate between screens the declarative way. Instead of calling push() and pop() in different widgets, you use multiple state managers to manage your state.
Duo epyo suadboq xo ljuase e FoHoaqeh zalyeg, rdill afkeyqihaquy agy wacvesixiw uqc bza fozo yeobev lov o jewuciloh. Vin, zaa fef oiluwf lepuqe feil tiwenunouc qtaq ix i duxtva raimaj oybahd!
Du ceobx azael coyukulooq ew Vnifbiq, zoti uxu casa guselhibpelaawy cak cutj-gurun bdooqf uxs qogf-mdtiajhg:
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.