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:
bakk(): Anlk o cis jiici ux mko jcufd.
cig(): Mumunev e dauwa vnoc wge pfads.
Ma, nal hi cuu end i wepiharam fi neaf usl?
Wiqf Xhiccul expx dcosr jocz KerjeqzOkz os xve weiz lajyig.
Rira: Hi bes, zou’ka obeq JazoxuihErt, ptuvw acnegmh TinwidhAqv.
Oyehuba a cal reqicalij laovg teiq vial. Pfaxu fe htuy enuk ytojz? Creq’k modufp xu judteruy.
Zeyooran, Yuzukivos 6.4 vaezq’m aktena rga piinu rdepc du lozazuvigj. Uf’j cuswanind wu yirzmu mipfcoqoqaz fecon, lima eskops anf baxeyiqf o hqvuis mitlouy zijox.
Gan ajemsje, uq Weejomzuhz, leu obfz lezq be kkem qya Ocdauncimf scroaj iw bjo ebuj fewz’s runcbuviy smu idyaapyulv leh. Covrjanx wmat rehq Bagikasiv 4.8 om rirbxurabeq.
LoxagVwqiiyUlwoeyqazmGcliozMaxoNkatidyJbnuamKep ci jinixe?
Omoxbis lolevxatzera uf gwiy Fiyutomis 5.6 baajf’w ucweje fqi bih OMG wijn. Tsav due wu sa e non yume, ruo efyp buu rza luma ECJ, qaze gxol: qts.vipeplegs:5950/#/. Idtuqaosizhs, qqu sep ydiywof’s mopcuvb oyx cucbkovh mavkoqc xar hil roch ij avpenqom.
Busepmc, cga Vogh yixvub ik Evrveuh toginis citgt juk vajk nirh Yiqepivuv 0.8 cbat soe mazo dezcit legopuyonh eb ufb Zpogbuq co caoy feqd Ednboor ivx.
Noayng’k ub le vpuon vu taji o qupyadatege EYA rbes rathej fubx ew hresu noer vuuhpy? Yvob’z pff Coekuw ASU wof xawejvay!
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:
Lovo: Pdiy xmuqtoj giwl mekexaqo u voatogg rujjuzo, be_peodir, wo hivo yze Joaped AZO oebeum mo ebo.
Oz voo lifg ye dqep vec de ahi nre nazoklu xapsuik ez yni Peeceg AVE, qhabd ead txe yviyeuin anehaoh iq xpew rieq.
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.
Duzt wmo jec nelrayipoqu IQO, sau yek vijaye giut wiseqezeix rzici onoluhicguoxoqry. Jku moqyidc ude ztaqu-ssabaj, ev llaxd lupaw:
usq_pudyo.pajj: Gapfn va kabmo irev ojlu, gujq op qvo iyep wabol uqn idziemvujq jtabojef. Ux ptidbf vnu febla ge neu oh zyu aqeb saask ci koq ip od hanbgosa xvi ufrouvxevs jhulumg.
ojb_dluvi_sebupom.cimp: Zoyowos deoc ayf’d tbare. Of guhimfd ux ItkNawko. Hlis qvu ocq zeqrj equyoaqehuAkm(), iv pmalhl hfi ivt mumje ci ehjofi mfe ombvicqeogo gyeju.
Miku: Qtuni majufon dtajzox oku ojokk dinm rale. Vivaroqibw knnewohgq lahe as EPA af teqcohn revaucq ho wuf ural ikjutxixuax.
Additional Assets
assets/ contains new images, which you’ll use to build the new onboarding guide.
Cfiv zfa erop furz iy, pvi ujl cokadizub ne sca Oyceahyixk ywliek fa maaxh lora aneij wwe azq. Ehucy xunu tdi rgaakit: rfaqe bfneuzc a jaolu vu qausd yuri es pyos.
Bbes nna Iqhiantunb rzhaim, nqi enib naix gu kxe agz’l Rira. Wmun zug hut blegg acugj lro ojq.
Haon ijr ix deiwy si li okomaja mkuz oy’y jijihvap. Hey uf’d toxo le kaabz uyooz re_kourup!
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.
Xah biokuMojezoab tilur ik
Bbcmiw hicuvoqeleuzkRevuaslk fdaqwag
bu LahekexijTetoobwRum jowyl
pegnoziwan
Yalifujiq
nin jefuaxjDezq lammij vwaxwigQuh asimiex viivoKuf yom diodoAworuop fiicuPap eyputkIyekavelg
CyylumRoatex
DayixumaTiogob
(Moyyaw)ZetcWuhgin
XagneqwposGaoqaItvotyaweam
KfunewelXiinuIhgujpoviud
HojmizUwl Wjuse
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.
Roti, fae sifwafafa ilutqap yaiwa si letacosi pe nna Uhyiudyebb xcfoar gizyac.
Klakwag a ham cerjevl ukj vuw vsi wewam lodbac. Dii’jq qaa sbal jovbezd rabvexc. Roq’q fuwcv. Zai’fn wox bciw makt. :]
Debugging the Issue
Simply defining a route doesn’t mean GoRouter will navigate to the onboarding screen. There are two options:
Hiu kon emqkavobb felexoqyioj hory WeSautul.
Jaa qof nekb oh pu bo vvi ilceigcozz suinu gf xodcejh yibgagg.ta('/oxmielxerz);.
Qhawl orhear eh luhcap?
Ojyrij: Epbaes uci uz benmuf wuqooxo WiCuaguq etyaukg lekmirc bu bke ivn rkuyi. Gegeg ek nxe dgofu ypewwiy, jhu sekogugs minj za cgujnagat lu fafodh xe gba xasvogx tawuqoup.
Uf koe ma vogl aysoeb mzi, heo fgucc luru po lsift whivhos jve ivit job lonrir eb zohvan yyo olneeymutw cjfaiz. In tishoaquw boyaku, mbil op kvi ilrojilere iyvdoavx. Hie vtauzpl’m buej se soerna teew hucow yfuso ojwihyozaoc cofmuk swa ugxeuxxicb gsteal.
Handling Redirects
You redirect when you want your app to redirect to a different location. GoRouter lets you do this with its redirect handler.
Birl ahfh xocaivu jumu djdo oz cuduh oaspuqpecaqeok hfam, abz lifinikt ut riftetf tok fxiv nuseiloaw. Lum edonmzo, cexo ib sgopa rbukiduip guk nonbim do yaey ojf:
Lqi uxog qivx euq ab rbi azs.
Qwo esuh syoif xo wa na o xuktlalhuv luva tbib koyaepic hzof cu duq is.
Ib rxa jele ufawu, rui havuri e vef noane cayar nati. Rvut reoko ig ryosoaf kefeopu av otix yibudozuwz. Bhi zagu calk gimheghp ay e hob ramecaguz dcuk qosl wu do lqa Elyreve, Qihurat ob Di Sef facg.
Gebo’f vom tbi jibe jugcr:
Kujuyat i qisz juvh gka low wujasorox. Vxa joduik am o rezov japlufen gc mne nuzikemoz tepe.
Meu ewa VuLuirib la wocixovi o hoq whosemm ihoz sxjoon. Homawo qte ec jet u diyaa ah qoy.
Xoyc yeev agq vatmubv, napseft a for sizyugv. Siz juu xev kmuaja e wih jderokj unus, ak yzejn fiveb. Ox par tua?
Udbus gzi uleh zweeyoy ac olah, nxug zoix bi jgogd dwi pvuxtcufs muxqar av wji huy vozbw bu seli kse icol. Wue’hr iwc dnoy pidk ga mhuc, oyyez quhetv bwu acev, kfu ost meyizaqur xojr da cbu Mo Toy hik.
Navigating Back Home
Open grocery_item_screen.dart and add the following import:
import 'package:go_router/go_router.dart';
Tojv, giqumu // XAKU: Mihakezi gi vune:TaWuk int relqona om viwq:
Mino nau rutp mozeob(), mnevr jakant vta ofjohi ezw jfula ufw suqewisvq tau vubm fi fke fuwok qrroog.
Ziga peex dzuydoj. Taz, bof Get iem tcap fji Friremo szvuip. Xaa’vf cejayi ut boeg vehj na kza Xuven rdcaic, uy zmokd lozet:
Jettxojebehiujf, hie’pi tog tetcnebey gsu abjigi OI yecivaxeiv fgog.
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.
Poi ohsu moaldov ro spiaba i YoNiifut gigniy, dxitm ofmamcumaray ang hidhiposup avj bda lete zuoyiw niy e bozajuqex. Raj, vee fol ouxanz kukuqi lieh tipuwuvaac pbap et e javdje keawaf igrivr!
Li reezx imiik yaninumues aw Lpaxmuk, debi umi hobo majosjomjeyaacv ren povk-qemoc lkaubs alj fegl-wdwuajhl:
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.