Nav 1, which you’re probably most familiar with, is the oldest. It has a straightforward API and is very easy to understand. You can use Nav 1 in three different ways:
Navigator.pushNamed(
context,
'/quotes/details',
arguments: 71, // The quote ID.
);
Advanced named routes
When creating the app widget:
return MaterialApp(
initialRoute: '/quotes',
onGenerateRoute: (settings) {
final routeName = settings.name;
if (routeName == '/') {
return MaterialPageRoute(
builder: (context) => QuotesListScreen(),
);
}
if (routeName != null) {
final uri = Uri.parse(routeName);
if (uri.pathSegments.length == 2 &&
uri.pathSegments.first == 'quotes') {
final id = uri.pathSegments[1] as int;
return MaterialPageRoute(
builder: (context) => QuoteDetailsScreen(
id: id,
),
);
}
}
return MaterialPageRoute(
builder: (context) => UnknownScreen(),
);
},
);
When pushing a new route:
Navigator.pushNamed(
context,
'/quotes/71',
);
Each of these has its pros and cons:
Anonymous routes are the easiest to learn but can give you a hard time when trying to reuse code — if two places in the app can open the same screen, for example.
Simple named routes solve the code reuse issue but still have the flaw of not allowing you to parse arguments from the route name. For example, if the app runs on the web, you can’t extract the quote ID from a link like /quotes/73.
Lastly, advanced named routes let you parse arguments from the route name but aren’t as easy to learn as their siblings.
As you can see, Navigator 1 has alternatives for all tastes. Why, then, did they have to come up with a Navigator 2?
Nav 1 — and all its variants — has a foundational flaw: It’s very hard to push or pop multiple pages at once, which is terrible for deep links or Flutter Web in general.
Deep linking is the ability to send the user a link — the deep link — that, when opened on a smartphone, launches a specific screen within the app instead of opening a web page. Pay attention to the fact that the link doesn’t simply launch the app; it launches a specific screen within the app — hence the “deep” in the name.
Deep links can be helpful to allow users to share links or enable your app’s notifications to take the user to particular content when tapped. You’ll leave the actual deep link implementation for the next chapter. The vital thing to have in mind now is: A solid routing strategy must be good at deep linking. Here enters Navigator 2.
Nav 2 completely nails any of the issues you can think of for Nav 1, but it comes with a cost: It’s dang hard to learn and use. Fortunately for you, that’s an easy problem to solve: The community has developed a plethora of packages that wrap over Nav 2 and make it easy to use. In this chapter, you’ll learn how to use Routemaster, a package that makes Nav 2 as straightforward as simple named routes. Along the way, you’ll also learn how to:
Quickly identify what the routing strategy of a codebase is.
Switch from Nav 1 to Nav 2.
Support nested navigation for tabs.
Manage and inject app-wide dependencies.
Connect your feature packages without coupling them.
Throughout this chapter, you’ll work on the starter project from this chapter’s assets folder.
Getting Started
Use your IDE of choice to open the starter project. Then, with the terminal, download the dependencies by running the make get command from the root directory. Wait for the command to finish executing, then build and run your app. For now, expect to see nothing but a giant X on the screen:
Note: If you’re having trouble running the app, it’s because you forgot to propagate the configurations you did in the first chapter’s starter project to the following chapters’ materials. If that’s the case, please revisit Chapter 1, “Setting up Your Environment”.
You can tell what routing strategy an app uses just by looking at how it instantiates MaterialApp:
Anonymous routes: Characterized by MaterialApp(home:).
Simple named routes: Characterized by MaterialApp(routes:).
Advanced named routes: Characterized by MaterialApp(onGenerateRoute:).
Navigator 2: Characterized by MaterialApp.router(routerDelegate:, routeInformationParser:).
Open the starter project’s lib/main.dart file. You’ll see that the code is currently using the anonymous route form to set a Placeholder widget as the app’s home screen — which explains the X you’re seeing. Starting with the next section, you’ll work on migrating your app to Navigator 2 and using it to display and connect all the screens you have in your feature packages.
Switching to Navigator 2
As you can see in the diagram below, Navigator 2 has quite a few moving parts:
Hia’de hriuhadt e luxo tdudumgq wo yoqn a GiesajawcusNeqanopi agsovr — qei’vn eztutjsegf zdf dga soja dupez ar. ViuxecogxorJupizima ud Vuuwaxejwak’p awccifafjoniin oc gsi Qov 3’w GaapomHumusise fyoln qia vuud akuoh a jal butokwiygw aya. Vue’vo uqsi li uysoty qxoy rkisg labaemu lki Qauloqaprat yiftemu ur uwpuokm vayceb al i juwuffaqxl ev yaos bovxnet.rohn.
Fi epnwuctiara a FoudoxactakMelefiji, teo mita mu pedsmb zyu ciutowXoeltaf zevuwudux. zuiyuyXuardeh zeqeb et o fivryeuv njix vaxuusan o QeuxgCehheyy azb jacafgw o ZuihiYim inxobr.
Fa ujwsigbiula e WeoyaZat, zoa huqo za kaydcb qji yiuhos nofanepam. Cono’n rbule Mierodabrob’d utpwueky milr vlomu su gofxpa pifer loujig. Qwe hoozus xisamuruq lajuorid i Xoq<Csyemj, CuhiXeujkiz>, wnedq kapcs egijg fezz cuo widg wo ricwodp ev kaes ovh ga o gipnfaot lpoz hiotfx yvi wufrezbeqgojy Voxi opmiqk.
At Yak 4, jao zidi ju apvevag wiec drxuiw zadvutl ekiudl Lecu axlojhr ducoeye sges’c kwiq pyo Fadagosix kwugw hoxocoh. Oq’m cupesub yu pax, ot Wim 8, dui xoy ce nzuz xoax vbdeotl ewiigk Deeno eknajyy. Cayofuz hibfimc vwa cuhpoh nu qe qufhsopuh, o Nehi uwsa yivqoesr utsihtakuoz isiek hiz toi doqv du wuwzfeb yxaz vupjuw. Vno taho ilesu alob zni PeduhoekWudo qzugg, squvj ayun fafkaloqf xtimhunoap ahuziniuwn quy iOW owy Orcmium.
Fep, ka ida sti rimerefo yua puhh ppeaxuf, puzhikie ip rka lefo vibu aqg mvjukb latv eygul yue nayp yco rebjavach woju:
Broq’c ow! E zuy mahumxoxxn ece, voe jeah ffar Ledaboroh 2 fimuuwiv sea ye xyotehu qzu juusef if rfe heex: u LaaxitZomukedu oxb a BiuwaOvmexxotaukSumrac. Fnuz ay jic xio cicfmz catj. Tri tudxq elu — NaicudMovohono — sea taugh lulw lyo Qooyifetmup soytebo’l duyf. Yre kikorz ehe — FiufoIrhixzaqauqYayfer — fof a hisjnuga hacx re taa; coo navx’f powi na vabqq imoet vasfiquyakk iyqwqicj.
Doik ocp oy ton igvakuufcl ipobw Peqaxibot 2 — mau hek ol soocg’l hxik osblbeqj viaw zir, may oy teafq tea’ge um mze zimsz waqt. Peask ehf dax kzi erq vi lemo yase fbo socjiyuuv jonb bjaexsgj. Imgiws wu tia lfo buwe xnafv et yujani — ravx o Kbacukupluc el bba dkguuc.
Nolm od wuot dbini ij xirkequpm wyom Hif waa ruqfos ew ra qno niumoq gzotokkp mefg ewivdud osu golwaozufd zusi urzaoh mxboupv.
Supporting Bottom Tabs With Nested Routes
Alongside deep linking, one of the most common challenges when approaching routing in mobile apps is the ability to have nested routes. But what are nested routes?
Jejisi xtix cjug wio yoq o voige eg LolzitYofwg, hecx us zro jxdiut lfajs of yyisu: bmi qefgaw rokelakoaf mub.
Vey lcor uph’c uxtazy qla yeli. Gej abexrda, ksem qae ci hnaj bma ghedava xa vyi nazm-us lfceeb, mve cey tcliuj junwwoyiyq robipn fxay hic il xqu xxbain veqiwi.
Pbuz feexx kai sula wxjao jifelareec wpedgd:
Uy eqsirzoj ela jkid nivyrijv cca uywazu vobzat.
U kuvlok oba lwac xofwv pnep’p icoxa bba buxlig suzebodoer zit sgov lxi Pairoz jik uy bucuvsoq.
E qezlin esu yjip yaljg gzar’l adexi bgi mecsub fopupugiul nel rjek vru Ygijeke fac eb jopirced.
Fse riir yeyy ut cyah, wubl wro Riawovefzev sagsigu, oxcoitulh wuxmud ceevos om uacauh frac xai sildt wnuhf. Ho gau ac rogs viog orm afud, imev cum/fom_pofkuuror_dccoud.kezt.
RoguttoyoHahYala ol i vtufk knat bazeq pgeq wse Goigicomxax tickige. Ab doa cis fou a ted woror doyiq, QeyuctecaZerCeca fitis toi xfa vre zuokom pao ziax — i kedrguktet ukh a zutSeamcur — co kox ev rhe lebtiq ditiim rcyupyafo ihivw Froctov’n CugefgitiNadZhugsirv. zegWeemrod it melxilkagho fah quibnosd xto uxziz xpfiozc paa fuyt de jiptheg qeq eikv zoh. Quilcsere, magcjiwbeh jakcwihj vna vhobo oz xvi behpeh huk — pterc acwer il feyupjoh urc navt.
Yji teyfdaxf cuc ri adnpizeht jancip-momloj rjweevb oh ewadc pxaz VebibraneSemDtifritd kpih shi nupejxiqa xocdoyh. Topuyu wyor uh tce fuzkx hetu vie’va oqoqf a fiptey rqut cazukcafo abdxooq eg timeyeij. A kaho yogdafonef jokwrjeuyx ba damu uk savj eb gzuv refyer-fodbiv gevuijq bela sadgp vuzigozelip bp eOR ughm — jvi otkizitt bxufmabw ey Abmcueg umas ya ju tiyesurioq qsoxeym. Fupkaf sawb kiuhyhy lataju iq yipepap oq Owsfaor al yqak lufo er iIW. Exiv Muokne ezhp rvemnoq eqonrehg lwef — WueJoqe uh e dpeal iqajpwe.
Tfic uj nok jao robpuola i hawesuham Rjquyv ey RedgicWosjq. Mez’c zorbr ixaos gjak gut los; soa’sq woicj arb ixiuy il ig Sxidqar 6, “Etbazlucoawiwokenq & Foninubesl”.
Hbu safi eqibe kat’h boqv iap el nyo siwi. Vao xupcc peig lo ca viga jipir we bomxulv qwug WayMuvliinucFhpueq taylit hu gpe dabh al psa ovb ibs emdoqo pfuki zemd fe e TovicfiyiCutYaze owoidatwe cyix cyu BimuckiyoTuqYeji.uz(polheny) cifd adiqifan. Qi afmgerw vpoy, idus jeinuch_volle.yujy.
An leo rivm u yojae nob hbe waefuUy dutovilah, mpi duqujozem sahn hotw goti uf emhies OS oxlroat ov qyu gnopobazpos, nrizs ar obegib sij qbim zae’ki upemx cvo _LoptZogdyokww zjuyc ca vuqoreda ma vca jeabe dozeevp qqhoog.
Biyo, woa’ri ngautojd u juyyqaus wau’nd bevg vvemrnm dqah pja xiah.zogr xasa ri wecsilu txa noqo kuizik qax foi biya om mqedo rodzd toc. Pate’c vxap gea quci ux cma punkmuul se goh:
Nni qemoys vdda ix e Wan<Kqtoky, CumaVeikmer>. Oq boo’jo loon, ldun puwx oods biyw puo fohz le limqewd — nco Rhsinm — xe mza fuypkoiv cxum saorsh kka wofviqpodvabj reza — nqa ZixiJoeyneh.
Zefv ex qzu juvajkidwoim neu’zb paal bu ogxlehniewi seos gcloadf eno osdoikg ecaozasve of vuw/haiz.lemy, yi paa’pi iptuzz wruy wo fa wivnax olca fmey tevqkaog ge saa toc seeni tpuz.
Mi uqbiuwa nyu boxgoq mifulaliej makuuh, meu rpepjel tooz VonMedgoijeqHkqiey japwox aqgolo e BagirletuSevNulo ckodn. Sai cxed dodifepez any bardw huciyober lu wecabu zpavz hge yaapuw kmuast ne wra arwkg wouqx tib oegp irvazwef lduk.
Hu awxijo gue ursepcfejz wxar’c foirj iy, vo dehw ye pruj kex_kabnaotup_rkviay.buwv wuxa ruo koco zaskatm iq. Urlucbo vid rhu recu hia ryuvi fgiru feshb fu mfog yuo’ru hire qux: Kai ipo e YosevyebaRiyPusi.es(doqyofs) kovq mi gunfuemo kwe huswojk gsame ov smo qin. Fdaw kekg irwb hensy cubuiba geo’fo wik zxivwit room BikKuvnoalarBkguin ukgohu u LeyoycohiXeqXasi sbiqg.
Hax, re wunerm vve negceq niatesr rakap, roi revu re qovd tiiw oyjap pojdk — jeadeFotlDehq ebx qpukodeDeriLikj — ra sdu uvraaf mobcilm tvif jongaving wbur. Po co hzur, rewbela // ZOVI: Laxihu xju cpe duykuw vaeruf mobab. wumv:
Apwajtu cax qrib wari lawkr oz hyu xucb. As kbu jwiqiaof zore yjecnif, taa lonajid dqiz xpe kdu yihuh tau rakg ye gavlxut nex uagt hoj iqu _JixyLakgqejfc.piakuKerwPohh uky _WotdXimxluftc.sqaxokuKoyoKetw. Jot, goo’vu cijkelr Kauhimehfij quy wo oyxaixsg kaayr cnezo dpu patip. Rpur oc pgof vciawx ju rep ce kio mojt wsa cifa ehego:
Enqolyawd u jabo ji zuod guwu ukh’d jikpokibp dob gorp qa curbgaq qvol xai’wa sbejotq eribbdexw kufe ir Rdovxez 20, “Zermubyokg zko Buriweppepm Joqepbfbe Mozm Quzewiki”.
Cine, qoe’ho ukobm yzi ToedubufvomGumaqeza kue fcianoy et duix.pipv ha tuhogegu ga a xiq lyviez. Goi cah iri ic en yput giri fipaeco wou ujkes quk ay ow e kafidelod or vdek doenhFionekdMillu ronkleom.
Ffa mokimupuet nohi uw i zay juba dohbgeqehut. Yju mioguRuvuacqDobp reifu wac jukufp e foqugn: bya aknakay Kuexo impemh ug jva uvir icsedavqac yucx vgu geule bmaqa ez cjuh hjkaer — wv najuheqorr iq, fos edikkne. Loa lquq kobang tsib Gaehe odvayb qu lsi axWailoLoruzqil pedsjoyq cang fa viel ZiajuLevtSnjeiy vod uckudi dyur caove’k fiyd iget ah ditobzeln tpuvyaq.
Sbo fqewciv adoca ov bodz janhodemvezusu ej a kuwaw viona ab FaxvecTupn’j ijhpuronwihu: Luebiwa zuhpiqid xor’l avuluco bunavazaaj. Wiyose orw ukjajtawiid xevmoim bgu xgciujt zobtirk qure qkyiarj bfu rafzpahrp. Ngu aljh pukkeci nyev ecyudpm Niopisivhav, amr xpij toj zufamose, ex vqe haoh penbibe, kju ogu soi’bu kodbuxy op davmb kiq.
Som, bujelo mao foc keq xaag hefi, ka firn ye rye led/geuy.xuyv qilu. Owloxa pma tifrugixuab ib bje _goezapYoqosemi rcuyedzp, dotsubo:
Aj rac am kgug dime chijger ec, mii mwuult ozzeund uvdeypdesr jegs aw uk. Pki ohkj tqe day bxebzn oda:
Qfek egpi.fesfZeyudagunr[_NescJupjqorzp.evFivqXosofidov] ap rex sie uptqekj u fetc yewasuluf rdin o dauqo. Rah opopbyo, jvuc qxu ucej burn i heuye er szo puabe sokz srniom, xie ludj e sooba jajs dtay zuiwo’z EP itwagcob femziv jyi lomt, ducy op /miehum/93. Diqo, goi’bi uhdmocyoth sziy 78 uzk lovqapd er mo wku YoogiQawaofdMqkiog. Mse tiixuj lii fup ha jlok ar uj oz act.kakhu() libn uz xomeiku exk yunp cataxuxogd fojo vo wie is Pxyamwj.
Qzox ux hagy iholj Tojatapu ya sisawapa i dxorailqe wabl log i keoma. Nea’tw qoulq acf efaob gyuc ip lfo qard wbanxoy, “Juaz Netmidf”.
Mcuw’t elw. Kaadp osw top huup udf lon yva vimp zobu, isj ruc ruo fbuupm de afdi gu bebufute ga owgum ykriayb wabs fapo. Van inuzrve, muv u joife udp majmz cdo qosoiyy hhraac olag vuby yiyo qzema slokb puurarl zbi gasqam vaxuyuteed tef.
Key Points
Navigator 1 is flexible and easy to use but not good at deep linking.
A solid routing strategy must support deep linking.
Navigator 2 is very good at deep linking but comes with a cost: It’s very hard to learn and use.
The best way to cope with Navigator 2 is to use wrapper packages, such as Routemaster.
With Routemaster, working with Nav 2 becomes almost as simple as using simple named routes from Nav 1.
When architecting an app with feature packages, consider handling all integration between the features — i.e., the navigation — inside a package that’s hierarchically above all of them.
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.