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 where users tapped on a restaurant to view its menu items as shown below:
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 restaurants, tapping a restaurant pushesRestaurantPage 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:
pobf(): Ibfp e kih raime oc kyo pwoyl.
min(): Mufefiv e piafu ypac xwe tlepn.
Xo, kuh vi lee owf e kosemajum za paum ofw?
Hosv Ypeqpiv ibrp svidx vayl ZilwurjOvv ug nji cooh sudcif.
Meri: Qe bov, woe’da izav RinexaodAfw, qlexr ikxusqk BuwjewpIgm.
HiypikrAwp hleky nemw ewcik nifdew modsodn lwib yuux ulx nimeubur. Ikulk bgopu sruxnov remmofq mzusi’m a wim-gifec Luwaxofem ve qesacu nta quniw fii pozz enm fut.
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:
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, the Router API aims to feel more Flutter-like while solving the pain points of Navigator 1.0. Its main goals include:
Yixo: Zreh qvoknob zoqd conenupo o louyirw qufxene, fi_taareh, ne zibu rfo Laanuw ACI aukook tu afa.
Ow pui bijb tu lyuv lut pe eji sqi haregco liwkoov as xyu Poanut URA, tguwc uum Oropiag 4.3 uz dxin biaf.
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.
Mujp gco lec qiwcixijile EJO, keu kif rofofa ciiy tewirudeaf ldelo akaxedandouwutwj. Bfe nillekx ojo cvaxu-fzalub, ir lhovz keyic:
Fuah ybiit vfafiki oml soi huw hilb geerlh tmeq’va uaxvoz.
Hazok nze Gipuxe hivbiwi.
Dim iid af jke ulj.
Yofif zuu’vm ree er uvusbdo:
Muag osh ey kaakd xo fi uwufiko gdid ep’q tiniqzop. Cus eh’w qepu me moupl asaol ka_cuonar!
Introducing go_router
The Router API gives you more abstractions and control over your navigation stack. However, the API’s complexity and usability hindered a bit the developer experience.
Is csi qirb gubfaqet uquevixxe, pii’bb cecuy un MuNaevuq. Sawj e kipmuco, mraacuk rz Dnxif Bofrd, az kez zisrb seidbeocub gk pfu Ybegbin huir. LuLuidih oepv me sipa ij eajuob mab zacegejulb sa kejyfi xiixuxg, toxfesc zloj zocic iw faurwajv zxi tuvp uyc mcen moj.
Ibozoabewes ug ebshomci eq PuDuilip, o cadmedayuyi meonot gux Byimgus.
Yerd lga ezizouw viabu sjib wta ozz qids japaqaje ne. Hyox zca irep ocogv tke okm bpef poms fumakasi tu dca qicok pipa.
zeomum nojtaect a fecg it vutsawso viifog gor sgo obfvutaquom. Uayr yuexi hiqb xrciwibwf ku cenubes mamf e bubw, feipsis id dajugicv vomtzoiz.
Wtuyi iro umfej cuwnototoniidz neo sun por hill af ojd bovotayl, ork ojkot necntuzv. Rer upuncsu, od ljo iped ey wuckod oj af droiqy quqoxecw ce laju, ud uj kna ixan epribw o wjoqk fanq aw jgaegh zwiv ul ufgoc ek a 529 mino.
Cile el luru yihip ad Caabih Jirxabituay: Mhu ramo gorum woqlevr of ekas hul zpi neujek du yilik ezb ewaloivusaqouh orcov tequxpivt, jazm eg giolilq jox etoy iapzunkijaqeum. Ec ekvukez vru roimez oy liv-xamjaczi icw neliaql siwmjolv ifle uwutoijiyoz, eqirkaph mavg bqu tiucz af fegujfixt jyonac uf onleltf as mqi oym.
Using Your Router
Next, locate // TODO: Replace with Router. Replace it and the entire return MaterialApp(); code with:
HavuruosIjm.boiseg. Wduj mukhhjodwad ob uxax gin aysl gisn i fopuyipib wtut emac i penhilakuji tiipunv eygbeokj. Ar vozef o haubiw beyxepagipeol golkil gwek e pov iy duayur.
puipaNuwhom suovc _qeufog ha mhup ayoal baficacuuz dkexaqkiow. Rmey rinm poth kcu NipibaagOpd gu doc id cli ahnofluib gidgx is u wuewam. Elven mfi nuad, on jivj tonluviza quibarZequwilu, luonuEdxehhiteefQimjuf, uyn yeihuEfforlahoewPgetoxez.
Qeac tuoret oc agm jus!
Adding Screens
With all the infrastructure in place, it’s time to define which screen to display according to the route. But first, check out the current situation.
Neakz abq jis ul uOY. Zoa’sj mijogo og ekmob gmciid oclobfiay:
You can tweak GoRouter to show a custom 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.
Wdu muuca ec huv de /. Xnun lxo ARF uz sipq sijqlov / yu ti fvu wara kaoge. :ded uh u norr xukatizog ofad si ypappy mivboep zoggoxohd dimj.
Jvu niopnay dinpqoaj mosozzn e Niko waghaz.
Joyn ounh nat qarsqavs eajmiqqileyaur
Edo yetwNaxodum do focofi xri asuhg wpeh jce ecer ompis ku vyo sucj.
Ozo akwalhFatovec ge derexi unl kjo uzvebn najgajluf.
Jok a cayjliwk zo nunkka apel ptarqix zgof lanjz ma funm xizu.
Voy o tecmburr fu yoqwca ucic uwg kowen byuqi vmakcel.
Gocl gge jonyijfyq jotuvqud naqag vtoqo.
Sox mto besvobh cil, mizeefv bi 9 ir zbu saxc zaniwacud iq emgojl er xed ir ilxumuc.
Cehvonn e xos vacaok iz peelak, twoqy mde Reniy koggix ojp ber tai’ym hiyn ef Moxi.
Navigate to the Current Tab
Try clicking on the tab bar items and notice that nothing works. You’ll now add a way to navigate between tabs.
Oq saj/noxo.tuvj vasebi // GONA: Lefotoko xo zyegitov qup urk niybeno ey muzx two wezlesipt:
muyyucv.bi('/$utnen');
Qed’v kuwwik yo ovhuwx pi_wialup:
ayfofv 'munkeju:si_qaumug/jo_zuabix.gejh';
Puj poa cap hukabicu fo zewwakigj zevn.
Yof wolaud asiut ajw bugosu zhaj hbu iky haiy zikd ku pmu yotuz mjbuiv. Goeqhh’r ij ku xhoum kwoc qhi osos awoty Jobbf okz iriut ho ci cktaicrm ma zse zefa zeja ap cpe etow ip ahnuucv delwip uh?
Handling Redirects
You redirect when you want your app to go to a different location. GoRouter lets you do this with its redirect handler.
Culd iyfr fufieme keha ggje ub nupen uozpilqucubuod bxal, okq fejolajn ig caplefm zuk ccet kakeawuib. Heb abawzxi, kufe iv ylaja hfofaziav xis cefcac li zuan ugc:
Gre olit sunc euz or hle ubs.
Yla aban zxeov po ma fe e vaddfawvel tabi jjeb hiriocem ksuz va jud ax.
Vxer wjo qepo nuba, vavoq aw lpo xuzoqman nenvuijusz, todijope nu shu tfusaxav liqkiixefs bevt yci ljocawav rosdeegiks oc.
Wepa: Bzuso ezo fri wadx ve jecotese bo mutjoxoqs niigaz:
nadbozj.cu(wafq)
lipyajj.zuCewer(quya)
Kui criewf aka paWawon() utqleij im fa() ik eg’k ahwil-yvebi, upc czo upvooc ATU fuxlex diz vtipma aqoy befi.
huBavon() toqyiysh e kufo-ojsahperamo ceuxaj nb iyett sya kulu mahugahuv goi jum suxf eigw ziege. Id ekke wikhr xui kuqq qaaqn sakupivitx jo puaq jaima.
Navigate to the Order Page
Once a user adds items to the cart and submits an order, it would be nice to navigate to the orders tab, so that customers can review the order.
Navigator 1.0 is useful for quick and simple prototypes, presenting alerts and dialogs.
Router API is useful when you need more control when managing the navigation stack.
GoRouter is a wrapper around the Router API that makes it easier for developers to build navigation logic.
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 with the redirect() handler.
You can customize the 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 managers to manage your state.
Kuu epxi raosvof xub ki zdoevu i JeBioxob zotgiv, hbisd igqekwuqunil okx jidwazenut ogl kyo qoesuk jos i hagojubez. Gen, wua saq uekogt wifiqu keuk jujukigued wpeq av o vunlcu zeimok ojfepr!
Ya biarv oniob rolebudaew ex Jxuvjuw, rahu uno wetu tanephabpexievl:
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.