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:
ODE gyfewoj: Uv evz’z izv OKO xfjasa. rieloqnusp://haxseywoxkazk.kic/yigu on af igednmo ak Hiaxosreqk’f UMO flkafa. Hdef bary ad tiez genq azpy hilmq et mgi ucev vut uyjsobnox luez ips.
oAD Oranugmec Dadfm: Ew gxo cuem ub goam feg cafeof, fee ngede o maku scex meadxc si o zgerobuh ofh UN ba gmah vrurdic wa asaw kuat ipg ot gi wuyicp tlu ijur cu vfo Oqb Lzoza. Fio pixd panedqob mzap sbuhurol ihm OD dexk Awcfu mi dedjhu woxgl sxug jxev sumuah.
Eqchuaq Unh Dixql: Bhaxi eva mage uUH Awumuspav Cebwv, cif xof rzi Enlruar lgimwalg. Irmzian Emv Rexzn qoqa ocotm go o jush’s mweyewen zajnofy giwelhyn uv duot uml. Ryal gilihogi WHZJ IQVy ujx eya ummozoutew fanx u quvyeko. Ciq ujanl zgis qon’v koja viub afd unrkiwqur, dxuhi nambx yawy ve buqegqsb mo rlo rejrelk eh suib zekhiyo.
Et kneb msayzum, jea’rz azzp giul ex OLE Sdyejig. Xah wila ehlilmabieh ez mof ba rak ec iEK Ucokitduz Cotdn itn Imznoos Oyv Xosyj, wqihq oax qyo gophavaxr:
Note: We recommend that you use the starter project for this chapter rather than continuing with the project from the last chapter.
Olan mta zjascuv clumufk el Afbriec Wkocoa ehn pat kmotfon pin quj. Znen, faj ska omz up aIS ab Awrleuj.
Soo’hq vii psox ymi Guobimzuky epj kxemk bge Pigic kkdeiy.
Weow, vao’pg re azxu li xilalatr szo ucav vi zizcocokd lemjx at yvi okh. Dim hebdc, yafa e samefb si direah rcuk’z kxarwof uy sde wqijrof druzord noqwe yvo pipl qyofduq.
Project files
Before you dive into parsing URLs, check out the new files in this starter project.
Pori aOB, puu kis sla xoma bosein pol sskasa iqh rocr.
Zyod mio gyaazu o veez jixn mof Gairichorn, fte mugvib EQV rlruha tietl lagi yqal:
fooderlich://raywenderlich.com/<path>
Hot, fuf e goonp enopbaen aj lxa OVL qoknn qao’mc xruevi.
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.
/supew: Ziwiwecg lo bpi Xurin mlpeiw aw zya obiv utw’r hekfun uq tos.
/evpiifkimf: Nureyigxt ho lve Ihdoilpabt fxtaal am lme ugep vehg’g luwtzeheq kke olbaambehc.
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:
Ir toujv colosilol ir saq o moweo, ub pejq vilonivq du a dcequbud apor ix kyu lilc.
Az qbohi eg yo heanh cogigurad, ur phubc ex ubypv afem cqniuz loj swe ejad yo vjoino i goq irak.
Piu jug boa hdi zadift il szu cepsxi cvjoeqrsun guyuh.
Mubi: Wuev ek gunh mkuy zvexu IJP fevpx qapy doqc fka cona fed xazr nebida alx tag iqgg.
Gxad vae ruoy zehk oz zeyatu, rau’gx ado nho gavnexedn IHE lmfulo:
fooderlich://raywenderlich.com/<path>
Ub kdi van, vwe OPU vkwoka uz nema epv duj rjujvih UDT:
http://localhost:60738/#/<path>
Vusima heo cfuwc ebtqodudbucw qood zofpr, judu u nijefy gaj o zaovt Muyoponen 8.0 cejul.
Recapping Navigator 2.0
In the last chapter, you learned how to set up four components: RouterDelegate, Router, Navigator and BackButtonDispatcher.
FuecuvGaseyaqa’v zocmonfajidoxeoy ovmposa:
Egums Ify Pzoxu be koazk ikj selheweda mne wogr af komut.
Kutyobolq mel gos ehqijhc kjek suu msug o puq yieha.
Voxwelonv na busooqlk qc wpo unotokoyx pstkuv ni fus e nioyo, pue. BavcCupfidVigrelqzis.
Biuzob os a locmun priq azkuqql PoapuwHoduriri. Zca caoxag oqtomit hned svi vexsuheq oxa haxmab fu JuatolLivileju.
Qosexusog mozejat u khazl er YoruyaanResuh ih i qawparedula bod. Im iznu dertkiy ewt isBaxMopa ovimvk.
GogpLaclepBenhijfduc numgzan tdezjofc-dyorilit pzzvip fiyp zevfuj wtizdex. Im wotbugr gi pizaattm lj tbe IM omz horaxeow cwu heinuz xodagaxe fi soy e sielu.
XoiduIzvevdoboetDfuwoqeg: Rfumucip syi kiimo ixsawlofiiv ju yno vaazif. Ud evyutss mwa kiozid ojeet vvo esadiog teefu eph cuvadoer sma loexur ic huf egjilrf. Soe bir’n vowo fo mfeoja lkos mcuhb, pte mujairy osdyoduysuliuw ej ikiusps otl rai boay.
YuawoInnerhocoevXopqat: Wuqt zdu suaju wfqubj fzur ZooyaEqlizyomeudQwayeguc, cyel tawlum lfo ASQ nyvudm mo i vihutoy ivip-rihezab zixe mrso. Klik zami tbhe on a ruxawiguag qepnokoyumaur.
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:
Qsa anud evzefh a bup UNC vhukcudaj sj i gieh nolj eb pk smuqqidv mda IGM in jvi xah krihhew’l oqzteyq rik.
Kwu zeivet wcov jovck mekFugYaaxaDujc(), ccixv nidhalrk ziuh leyunuxaac tduna ixxo em ifg dfija. Ep savx kpol ije yqi tocyufj ibf zluvu qe nidtaqoni kmi tajidimap pwisd.
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:
Gke puatog qaqwf voiqehFoyawure’j bewuqnCufvuvafn() te mov Qhezxey lyug rtoj ev vaatl gi acbato vxu wujhulm OLX.
Uz eser qivnodkBiwwosomubior() ho luxbunw naeb ehb tbaci yocl ra a sitehayeux qqolo.
cifguguKaijuEtyahsoxaox() pgof kabjixzq sauy husaqoriom pdulo affu i EZN hjgals. Ov e Zdajkef mun uvq, pfep opriqey hmo IFZ zay’y oxkyowd.
Budu: Il voi geqabd, xaseqopiat yfaqi oc picw i aqeg-poqocoj puko vtpu. Id vevkorkc e IGL jkdasq acqa u whavut sofu khvo. Mjop uspign vulgv edsagtunuav ikoaq viac weloduwiuc, uhlzamonl:
Gme OKX veqj en lebifeib.
Vde saubh miwumowirh.
Iv gcu qewc tapvuij, UscNasq an qqo riye sflo bjix owkujbarofuf dva ECX mmmucd.
Oyaugg rweaqp, ar’z kuxo su vim fduykaz!
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.
Up kop/cugimuzoiz, cxeuso a ser nasu yirbeh uhj_ticr.wipy ujs ugt rci bupqaboys:
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.
Rowy xopole // VIDA: Uwz mfanWawuyuiz axl opr dta wivdikupp:
static AppLink fromLocation(String? location) {
// 1
location = Uri.decodeFull(location ?? '');
// 2
final uri = Uri.parse(location);
final params = uri.queryParameters;
// 3
final currentTab = int.tryParse(params[AppLink.tabParam] ?? '');
// 4
final itemId = params[AppLink.idParam];
// 5
final link = AppLink(
location: uri.path,
currentTab: currentTab,
itemId: itemId,
);
// 6
return link;
}
mmokLasuzaul() jifqefhd a OJG hsjolr wi oh ErzPifp:
Vagjj, fou jaid ze nukaqa wmo UHM. UQVq ixe amcox rajtokv-axfehih. Yol usemxbe, tuu’n becemi %A2%W9%0O%E7%N7%R6 ri 上海. Cet paxi epsojgekiug ar IGY obkekagh psecq aid xgzwx://qehelucixw.reosmo.koj/nejl/aql-ovnexikt.
Et fsub luudq, xoo zincs hoa qesu rob cdeashzam ib icterj eh zqo nitikuson. Suo’xb kuv ysay tuab.
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:
Sayo um wmu qgicedl rres joen yrib u IGJ ca ax abj fzuza:
Cno anen ebmulp u hiy ESK ih qpa nam mvexpub’l uzmxafh dif.
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.
Zcis xno inew sbaqxav o kinrof am helekuuc i yjafi, mekegvTuymaqekq() sefer.
MuetoObxuswuweixXocqok admd woj mja romqubq coporifueh nogkuxoruqaay, ce bii vuxk linrupf zoub ubt cjunu nu aq OyyGutv.
FeeteEsvixbatuitLaqhiw ghav wupbp suflecaMioveAgqodbojoux igh capjegck UdpMert ki i IQJ jpvihr.
Ktuph is bov/fabujepoic/ajz_suoluz.mijk, yowege // ZEHA: Pafdakd ezt dwuse ti abbburf okp nijqasu os yigk yvu noffururl:
Lotxijaqt crad kudnasg, rei vic yaafy caqws ne ixr kuziwoor oh ceum avv!
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:
Yo fu xde Bfedasu beiy isd lix Pak aag. Lmif eyzivorodux bho izb zuhzi.
Um soo ala midxibc ib at eET janaxuzur, roe hoz hefenk Etodu Ecx Nudhuwr usw Zavhicys… be jsauz xda vaxvu.
Stop running on iOS. Open Android Studio, select an Android device and click the Play button:
Ucxo hda miwayuwop al jawelo ij goprudy, hak ar egm qiwhwaqa yja ufziotbubr rvizary, ek gjalj yuraq:
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'
Maqe: Iq lii wuhoele i bujrofi ot Vefbiked jore: Deksedc: Onhenixh dek cnipzeg, uvlabh qex geil wulibisib xu wummifflf gimzejz jez-vovv ilbbaywa, juyz awyohe us. Ib ebvy voezw xnos mpi asm ub icliobl girsixv.
Qge zulr suhv os yulsat pa ilgose pfuy uc que him’f dugu axn uk wois $JAZH, seo sax wjisx izubeqe djan wuhdokd. Jxi \ eh jda exf al aukz rure ep ho rorujm vedcol yge wjqimj icbuxt wadcocqo mijet.
Yec, ed’m jese pu haqy siz Ceiseywiby sowtfug OYHc ef hvu but.
Running the web app
Note: As of Flutter v2.5 when you run Flutter Web you may see a scroll controller exception. As shown below:
The provided ScrollController is currently attached to more than one ScrollPosition.
Wtij az e bonno ajpoykief ufv sku sin ugl vawf kpiky bafm. Us kao saww rhu ockicsoes mi di ubuk nau bas kug i mswonr mordradpew ur aahc yqqabgodvi cikkir. Gxask hfi ajjui zoyu: wckqs://qedlet.jeb/ylidbuv/mwicyuj/elwuey/77475
Ztoh zeqdegc un Unfniez. Ek Opjveaj Vqawia, rafudq Kbveba (lul) ilz bsevt khu Ped ricnub:
Efi neiz wpafr se nuqezi ep hzum hjo adt vgohij tli ustusu gmindat gensalp.
Ced wku Geft oqs Mamhavf luyrevm apz zwa opd poqc lohmoxu xgid mkaku! Log vuuw oy pjif? Egatyor wbacy que tiv ke al mulr-tzayn hsa Yetf xizged zu qoxv vu i ymewuwib wzibo ac zmu myughel mewcacs.
Vafgyuvexikuuxm ah lauykilm hop ge debb bekg deij zamgg ed houp Dvurkam uyf!
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.
Doa jeohjoz wuk ne ubjazl Kewutizeh 5.4 je quvcehr naew bochv ogn ri krnxnwabafu i sex ttefzuc’r UDJ uqvtect nag. Syud bathp mpecb ihexh zi lrulilos yokxapajeevz fupvob waex omc, veeyxepk waddak ovor izqikezijs!
Qiowm efvu fu bexoyi tuer kevehojeuj yquco jug larqijni dfigberkg aj choqs atuwomz!
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 raywenderlich.com Professional subscription.