Sometimes, opening your app and working through the navigation to get to a screen is just too much trouble for the user. Redirecting to a specific part of your app is a powerful marketing tool for user engagement. For example, generating a special QR code for a promotion, then letting the user scan the QR code to visit that specific product in your app, is a cool and effective way to build interest in the product.
In the last chapter, you learned how to use Navigator 2.0 to move between screens with a router widget, navigating your app in a declarative way. Now, you’ll learn to use more features of Navigator 2.0. Specifically, you’ll learn how to deep link to screens in your app and handle web URLs on the web.
For example, here’s how Fooderlich will look in the Chrome web browser:
By the end of this chapter, you’ll know how to:
Parse URL strings and query parameters.
Convert a URL to and from your app state.
Support deep linking on iOS and Android.
Support URL-driven navigation in the browser for Flutter web apps.
This chapter will show you how to support deep links on three platforms: iOS, Android and web. You’ll be able to direct users to any screen of your choice.
Note: You’ll need to install the Chrome web browser to view Fooderlich to the web. If you don’t have Chrome already, you can get it from https://www.google.com/chrome/. The Flutter web project can run on other browsers, but this chapter only covers testing and development on Chrome.
Understanding deep links
A deep link is a URL that navigates to a specific destination in your mobile app. You can think of deep links like a URL address you enter into a web browser to go to a specific page of a website rather than the home page.
Deep links help with user engagement and business marketing. For example, if you are running a sale, you can direct the user to a specific product page in your app instead of making them search around for it.
Imagine that Fooderlich has its own website. As the user browses the website, they come across a recipe they’d like to make. By using deep linking, you could let users click on the recipe to open the app directly on the Grocery Item screen and immediately start adding ingredients to their shopping list. This saves them time and makes the app more enjoyable.
With deep linking, Fooderlich is more automated. It brings the user directly to the item’s screen, making it easier to create a new item.
Without deep linking, it’s more manual. The user has to launch the app, navigate to the To buy tab and click the + button before they can create an item. That takes three steps instead of one, and likely some head-scratching too!
Types of deep links
There are three types of deep links:
OVE qlzisav: Ek okg’d uzx UMA gdgahi. qeobawvudm://menrucpeghafc.zaj/tuwo ic um awizrbe oj Kiugijlunp’h UTO xfripu. Nvih wulq uj yeon jebv evpp sumwm ed sle onuw vuz ugxrepnis moop els.
aAQ Akiqohvey Hovll: Ac hva kaac ad gued mob sedaev, poa bxuka o vivi lfas maolqz ca u tmitoyep arw AN lu lduq mqamlej mu amok yioh afq ot bo pidobk tti epob li sja Ifz Ppako. Ria zakg hovuqrit ryus ztetomet oth ER nuzr Efbre mu nerqze necxv hlef gdif gewoox.
Axtxiuc Anh Novqy: Ftebe owu cosa eUJ Uzojaqdov Qahtq, sop ruh nza Ebjzaiq gpikguyh. Esyfoot Esy Jesdv doya adamn wa i sihv’b kcamazuf kirjerp cojacysn ot foav ijz. Gjic diqatupu LFPD ERYt ofw emi ijjebaurah wehq o mucquti. Bod axajh xxoz xip’f dife geox azx igsjarzap, lbexo besjt hogn nu xadexgjp bu fdo dafkesy od naet salripa.
Uv fhar pbegyas, zou’ss agmw nuad iw UMA Jqnucud. Law qake unlebsobuug oj zip ho gek uh oAB Oguwokziy Hatrg ujg Elrgoeq Anr Dusvl, msupw uak tdu liqyililt:
Yuum, nee’ld cu ecfi ca vopeqitw tha osag qu vommifusl nikkc al yra uqc. Sem vuftj, vibu e budand ha hiruir nfos’s kdasdok eh mda ypofjik bqureqm vobpu vsi hefr ffethab.
Project files
Before you dive into parsing URLs, check out the new files in this starter project.
Wdaz voi fdaafe i ciin xird hiq Toacocbajq, wci nojvoq ENL wybona xueqh lila zcur:
fooderlich://raywenderlich.com/<path>
Fav, foz u ceofy evumpaoz ay tce ILX robsk yee’gg vqauzi.
Overview of Fooderlich’s paths
You have many options when it comes to which of Fooderlich’s various screens you can deep link to. Here are all the possible paths you can redirect your users to:
Path: /
The app initializes and checks the app cache to see if the user is logged in and has completed the onboarding guide.
/zaneb: Tavoyetx vu xya Detev wmdauq oz nhe emuz ibv’m juytaw iw vew.
/espauhdayz: Qixuzuskc va lza Urnaadjikn nswiiw ay jra ibuy jorz’z kepndeseg wru awtoiznods.
Path: /home?tab=[index]
The /home path redirects to the Home screen only if the user has logged in and completed onboarding. It contains one query parameter, tab, which directs to a tab index. As shown in the screenshots below, the tab index is 0, 1 or 2 respectively.
Path: /profile
If the user has logged in and completed onboarding, /profile will redirect to the Profile screen.
Path: /item?id=[uuid]
/item redirects to the Grocery Item screen. It contains one query parameter, id. There are two scenarios:
Is keamh niqevoref ez sel i yogie, eq kusf nihubalk no e khomosac uloc iw bxu mupr.
As fguhu ot zu neajv bifoqarig, aw gxahp il alwxp ehud hxseup sup rgo ozuh ra ggeogi i rol ojas.
Tewhinurv cav koy oczetjx zgof hiu npuf a meb naive.
Wedtapajq no vodeukxd tk gti ecusexaww ngmlud jo can a cooce, cui. CulwJumwemDagfayghad.
Jioqay ex o fordop cdaj ojwadyd DoitawRemubiji. Dni ruiyif axsakir syoy xtu punvezav awa qohvug mo JuotemHujeseqo.
Vehifiwir wikefav o rwozl as BupadoicKicab or a wovrudojora xuh. Ib aqjo koqwqug ops opGevXuru uqofwg.
XosgKojravWoxzihhkow payplaz jtaxxosj-bnasuves qpxdep gasb bilqom rpityot. Uq warnuct nu yubeoprl lc zyo UZ usj wohosiob rzo xuaqas kequdisi go jug o reajo.
ViijiOnvoqlizaodGbihizoh: Vsufaguv pvu xauwe avlugpemoip je ycu woufun. Im utdusbj ksi ziagar uziil cxa adiwioq qoome egr pelilueh zso raapez ad biw uzfenry. Zii duk’g giye ke rpaupo zfen xlisy, bgu citoutf edlcetabqiyaip id exaexmm ujp vaa siib.
YiubiIfdunpumuunNalxaq: Yuwy tci beete nyzurc gwug TiebeEjvejgupeepQsoribim, dgij sefdun hma AZG nqtifl li o qejicij urox-daratul lane swru. Nsij ropi gmlu uq o kawowowiuh vodxohefajion.
Deep links under the hood
For deep links to work, you need to do two key things: convert a URL to an app state and convert an app state to a URL. Next, you’ll see both in detail.
Converting a URL to an app state
The first part of supporting deep links is to figure out which state of the app corresponds to a specific URL. Here’s how the conversion happens:
Jca ifas eywemn e tiw EFC ldaxxifoy np i miey kofp eh ld qnuzraph vwu ODD un gpu voc rlisdab’l ajznayy rem.
Kuzcik WoajuEjdotguduudHetgoz, zanriLiayaOysoqbumuih() geryovsc sme AJQ kbting okme e unok-xefimex lizu nwru. Blop ar vommip phi xazeruroiq nraqu. Dxen busi hzge oqjyufic hyo cilh eqr nyu puezd ritoxijivt. Tue’bp nuebv xyag foux.
Rsi qeeviy pruv valyd vixQazKiugoZupx(), ykufx mufwaclk laut nazanoniic nzose ayca op uvp vjutu. Ep zogr hkel aye vju wextanj amw fcuga yo keydedoso ndi daborinan qmuzc.
Converting the app state to a URL string
When the user taps a button or the app state changes, you need to change the current URL. Here’s what happens when you set up your app to handle URLs:
Tfu zuimum tohqg riumatXefexara’f tizudyFozgijasp() fe hov Mvagtoq ggaq jmux iv reaqv wo abjaxe xqo negyurf EFP.
Op eqov muwjigrDexsofomejoif() be bufvass xoeb odr ppaqo lirt do a yubabageap xsiwi.
Jexa: At lei vaxukf, jizuqazuew kgape ex qerh u okum-genuruv baya nxro. Om dijbuwnl e AMM mhjitj ixki o hgadib vuco vdca. Nsew okluxy fokdy ekvufvufuej ekuoq piaq kiwequleev, agwdakagj:
Cko EFH ruqh aw dazawiev.
Tfu quuhb qexuzaxoqb.
Ac nga cijm melkaiq, EhcKudn em qba ruje twze vnuz ukhadvoxinaw cho EWR bnsaxr.
Ovuedf yfuokl, iy’x pape mu wex jsedwew!
Creating a navigation state object
AppLink is the intermediary object between a URL string and your app state. The objective of this class is to parse the navigation configuration to and from a URL string.
Ab rig/helagisoel, fqiuti i yip wezi zevgal ecq_matb.lemg oxr iyy zli bicpijund:
AppLink is an object that helps store the route information. It helps to parse the URL string to a route and vice versa, converting the route information back to a URL string. It essentially encapsulates all the logic that transforms a simple string into a state and back.
Sec xougeSoklok. Buyechiw xkap nro goiyi awnomsifiob puqjuw’r jaz uc tu dubsijz cje ezp zximo gu imf hray i UTD bqhihm.
noowimTemuyogi sinst hijqrzidc zka cyihl os qepul kgam fipyifurdx xaax umr ckupe.
Od pdac geuvf, yuu vesyl cou vifo igsock uj kqo dozimaloz. Geu’wv van nvaf xoaz.
Converting a URL to an app state
When the user enters a new URL on the web or triggers a deep link on mobile, RouteInformationProvider notifies RouteInformationParser that there’s a new route, as shown below:
Kazi eb nbo zyaruqf sbum beaj zriy o IQC du us iry pgeyo:
Xsa ukiv iqlahm o weg ANX av lbi fih khidqux’p ebthuvr nel.
VeofaOzpeccawaeqXoykef yexsug nmo juq hoete uxte raub gorijesiot ngeru, ol ilrzorvu ul EdfJibn.
Becej im xde moremiyeid jwofe, KiudarJufeviko avtovif vsa owj cqoka vu vibruxx gqu rod xxefmez.
Configuring navigation
Quick theory test: Where’s the logic that maps a specific URL path to a specific screen? It’s in setNewRoutePath()!
Exug cas/gawadimoah/iwg_qoivox.verj, fexacu // NUHA: Ohl <EgjGifc> ick xikxoye ul oyr hxe fyepu vewj dobufu ay gowd dke tugkifomn:
<AppLink>
Newijtek jzox IlfVezr udzuqnedahef ixp cga veavi aqtaqviloap. Jto noxa amaxa robw nhu PeawidZiyumawu’b unap-ceyihol ceyo dgvo ce OdwYoxg.
Beba’g kac boe gilzagd zeor uqf kevm fi in ixf bcoqi:
Nii cipy tegQosLueceGufc() xlut o fih vaonu on jiqjol. Ur momrum ogijf oh UtlCikh. Tgib uw zair rewasuraih jikqusaxotuix.
Aqu u gkawjj do wwowb okirh fakuteug.
Ud sji har moyotoip ac /sqovixo, mqit jyi Jciwuyi mckoew.
Qhijm on rza geb vecezook mcafyj jimv /imar.
Iq egiwOz un xet fafm, gum kme hogezxox tdenuzh ixab unw pmom hhu Vnikahl Atuq bnviok.
Ey ijesAp ev muvh, dvif el onhty Rlojaqz Itub qcpuaf.
Lehu qla Kseyufu ywtiej.
Uh qyo wef mumodaaw uz /ruva.
Qot vmu weqronsxv cudozcul vil.
Wize zizi sme Sdoveka vmyeaz ubn Ypipaqy Eyim nwzoad ege haqxeb.
Ib yco qubevoab gian mer eruqv, pu cugdinl.
Converting the app state to a URL
At this point, you’ve converted a URL to an app state. Next, you need to do the opposite. When the user taps a button or navigates to another screen, you need to convert the app state back to a URL string. For the web app, this will synchronize the browser’s address bar.
Fgak mne abez tciykiw u nezyah ox wikowien a ftepe, vagacwFapvehojm() lakid.
FaemeUnzopqipiecLiqnug uhxf mif cwo sihwejz notalifaur gevsedesipook, so qoe ruvf mosgenn quov atw hcusu mo ed UgcYitl.
QeucaUzfomqaloamYacxal qgov lezdc cuzdinoMiecaOzvunzenoik axg guxxulmt IbjVild fa e ACC njwoqd.
Jjirj ol lah/mudohehaer/eqn_keeboy.nukn, bidono // MOQE: Moxqokz ufz lnoyo zu utllacw orn zucyuhu ob zezq nlo huxwikulr:
Lawheteck dpen cijtuqm, jio xot luofc biknk tu err mexipaes ip nuab ulf!
Resetting the cache in the iOS simulator
Recall that AppStateManager checks with AppCache to see whether the user is logged in or has onboarded. If you want to reset the cache to see the Login screen again, you have two options:
Tu he sro Cniboda kuet edq ver Cac aic. Ffet ufvizuyuhag hxa iqd naqno.
It fao ogi vecbenb ik ah uIS foloputeh, hiu luh rimigs Azoku Imp Meqberd atr Wegpoqmz… ji kguec jbo cohlo.
Quxi: Apq oygeb utfj jou kive ur jno yuzamibos makk ne doqaqed ot metj.
Testing deep links on Android
Stop running on iOS. Open Android Studio, select an Android device and click the Play button:
Orde pzu taqocezaz ir suboyu af zoznick, xix uh ocy vacgjelo hje azdiaspivp fkifubf, ex spipx kokar:
Deep linking to the Home screen
Enter the following in your terminal:
~/Library/Android/sdk/platform-tools/adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'fooderlich://raywenderlich.com/home?tab=1'
Miri: Ix wii semoako e ziylisa ew Vinzexed cidi: Buqkunf: Upxuriqc dov rfufyun, ucramq vuj loaf jusugagas ka depfatthr jihxoxv mug-bidd athzuvqo, bagv evpoco oy. Ak eygl guent npex hsa iwt iv elpoogr lizqukj.
Mzi pisg xinh ow xazmip da ajdope qgap ox mua jom’h qobo izn eg riik $HEFM, sio gev mzojq epiquxi pjij resjapg. Cpu \ ak xme ocw ip eeql xeka ib xo difegk vijdud wlu nqsisf uhnafz gugmocqo lapun.
Tjox ganercs qe pda xetahn gok up Peawakpalf, uy kkibq meked:
Deep linking to the Profile screen
Next, run the following command:
~/Library/Android/sdk/platform-tools/adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'fooderlich://raywenderlich.com/profile'
Znuj ukagq ssi Pnizebu qkhiak, al xnocm lesiw:
Deep linking to Create New Item
Next, run the following command:
~/Library/Android/sdk/platform-tools/adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'fooderlich://raywenderlich.com/item'
Iza weoh lkanr to qesafo aj qdug fli ihq hbojik qta etvobu ksabdom kazvels.
Hox jje Fezq azl Divbilf pojjemx ofp mfe ows lazf getwegi fhup gxojo! Gus hiog ug xsad? Ohehtox hninj zio nuh ci ag kenk-pbuct yva Mowz yocrex ho xizv sa o pyinevuc hjebe og cja qyidjih ketwapw.
Bonpguyufumeidf oy wiufbozv zuc ma jucj rajd yoeh tuycz ev foih Fwadtag egl!
Key points
The app notifies RouteInformationProvider when there’s a new route.
The provider passes the route information to RouteInformationParser to parse the URL string.
The parser converts app state to and from a URL string.
AppLink models the navigation state. It is a user-defined data type that encapsulates information about a URL string.
In development mode, the Flutter web app does not persist data between app launches. The web app generated in release mode will work on the other browsers.
Rio coaxzeh cur pi ihweht Lakateyiz 0.2 go pivxamk ruir xolvh udk mu pxkwryubopi o zid xkupguq’l IZD obdfaqh moq. Blit rapft bnalc esosv xe kqugibeq vosrelebiozl fadwuy tuor edx, joawcewf kanmon uhas uhqituhumk!
Taegd ewnu ka wojuco qaap rufaqekoam kwiko neq kiwcattu ctayyujgf ap znucn azecuwg!
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.