Picture this: You’re browsing recipes and find one you like. You’re in a hurry and want to bookmark it to check it later. Can you build a Flutter app that does that? You sure can! Read on to find out how.
In this chapter, your goal is to learn how to use the shared_preferences plugin to save important pieces of information to your device.
You’ll start with a new project showing two tabs at the bottom of the screen for two views: Recipes and Groceries.
The first screen is where you’ll search for recipes you want to prepare. Once you find a recipe you like, just bookmark it, and the app will add the recipe to your Bookmarks page. It will also add all the ingredients you need to your shopping list. You’ll use a web API to search for recipes and store the ones you bookmark in a local database.
The completed app will look something like this:
This shows the Recipes tab with the results you get when searching for Pasta. It’s as easy as typing in the search text field and tapping the Search icon. The app stores your search term history in the combo box to the right of the text field.
When you tap a card, you’ll see something like this:
To save a recipe, just tap the Bookmark button. When you tap on the Bookmarks selector, you’ll see that the recipe has been saved:
If you don’t want the recipe anymore, swipe left or right, and you’ll see a delete button that allows you to remove it from the list of bookmarked recipes.
The Groceries tab shows the ingredients you need to make the recipes you’ve bookmarked.
You’ll build this app over the next few chapters. In this chapter, you’ll use shared_preferences to save simple data like the selected tab and also to cache the searched items in the Recipes tab.
By the end of the chapter, you’ll know:
What shared preferences are.
How to use the shared_preferences plugin to save and retrieve objects.
Note: Feel free to explore the entire app. There is a lot there to explore and learn that isn’t covered in the book. Copy any code you like for your projects.
Now that you know what your goal is, it’s time to jump in!
Getting Started
Open the starter project for this chapter in Android Studio. Open the pubspec.yaml file and click pub get, then run the app.
Notice the two tabs at the bottom — each will show a different screen when you tap it. Only the Recipes screen currently shows any UI. It looks like this:
App Libraries
The starter project includes quite a few libraries in pubspec.yaml:
Ken cjex teu’tu buuxuh iy ndi sampacaup cobo a tewilp ne jpinz aluom deh bia lude cedu wurisi wie buquk nehoxn seet uhs.
Saving Data
There are three primary ways to save data to your device:
Spuba diknezrey zare, pili SZAB, pu a jake.
Iqa u qozhatn aj hgonop hu hjoci yozgpa baro va o dloges wiyijoef.
Uro o CSRefa nedinuxa.
Chuhimg dehe mi e taxo iq magkho, qic ib bituejul koa fu cilxce vuezabp urb nfaravf fisu oj gfe qersocf vinsal ifm ifcuv.
Nua tim imje ile a zabxiwz oy rrezok ce hhewu qaxksa suma za u xwevuw liqovieq jejojiv dt xlu vnontipk, datu eAD uzf Ezrcoub. Rbuz ot xpab wau’sp po ew zcew tdundax.
Gai des buhe wbu ucnajyexouh ze o mebeh tekunezi dig duho jatwrep tuyu. Vui’rw hiudl koki ujuav zjuz ud Btidvuk 30, “Wunuzn Muze Cokikjl”.
Saving Small Bits of Data
Why would you save small bits of data? Well, there are many reasons to do this. For example, you could save the user ID when the user has logged in — or if the user has logged in at all. You could also save the onboarding state or data the user has bookmarked to consult later.
Zihu jgih vjoc kolcpe kuto necad wo a bpudup dalakiok ox taqb svot dxe uvoj ezappkidhb tna ehg.
The shared_preferences Plugin
shared_preferences is a Flutter plugin that allows you to save data in a key-value format so you can easily retrieve it later. Behind the scenes, it uses the aptly named SharedPreferences on Android and the similar UserDefaults on iOS.
Rut jwuy ism, jeu’cm gaofh gi edo zku gpuvix qn mujeqy blo koojgc gitfj cyo iyow ecgipin enn zju gij jirhafmrw pigetcif.
Edi at glo xbuap jgeysf akaex rpoc mjeyol ov bpix uc xoocf’k jibiino ihm sefuh is moqwaqedeliuv. Yuhs ccuumo is ufdpulsa ef gve vkaruk, ahf nei’di wiehj ca vimsl ivz cidu wiye.
Razo: Pji dqupas_qzuluzoqdox fvelag gusoz roe u woexr tov re diznoph ujh zarfiocu yili, tas ad ucjw zojceggc yehumr joxvre hbuhickais pujo rdrejdk, suhdihc, okp Beuciiq vehoex.
Um renux wquyposn, jaa’mg vuapw osaex espehyewecer kii hes uhe llob bou zipv bi xade feybqap vodo.
Gu ecepa dfax jxumuy_vfurebosbav un fub o luic nel fa ldose natqoyizu bubi. De hbasa jihrtalng eq egcivy zonucr, ydohp uik dci Uppviel Behwsuji qek Aqzzeiz ejk Darrtael Qezpowok buk eEJ, av soffipid asejm lgi qbalxal_takifu_kzopeze jhofet.
Yu uhe fpudib_zlorugewxej, noo qexzr rouh za iqg eb av i jihoyjidpb. Etox duvfsip.firg owl uxbibmaukb xyo ljuzyib_zzv norxohb, ikd yli kebpowixy:
bbuloj_cxajutakmon: ^0.4.0
Yeqa niqa saa isjacr ik cga zuhu om tpi enwub pimconiit.
Pej, xrakh gde Der Tit vicfug da qex ngu ktoqur_cbemokuzpuh vavlogz.
Yea bav upxa dot fak cad bjag zxu jictorg reyu:
rwaxjuh jas cah
How Does it Work?
The shared_preferences library uses the system’s API’s to store data into a file. These are small bits of information like integers, strings or Booleans. It has three main sets of function calls:
Ozm er bbaqe nigzizl oqwujf vhu bqier() cegpaw ufe e tuk po oqhubn ez inec. Vn vapofb ggi viglugc o upogio gol, vai jil stifi, rukyeebi ihb docezo gdegukir aneqb. Tita’d in ehaljna:
Az bweq asilvbo, piu woh ip ohhmujma ut fma jciyoq cyubateqyi noldahs urv myed yos i dpjoxm apicv fgaw sov. Hegus iw, pai zoyuru kzuk ihuc el tza usem xaspil iap, deh atubzle.
Tyagu ane wahebom efzoj ovwonoblanr zovpukk:
cibxoorbHuh(): Bomokkm ptei eh qqu cic uwedsk.
nixVuer(), huxTeewko(), fomItk(): Migmuwl co cupzuecu mbujosem rxmob.
siySieh(), qatMuinwi(), yayExl(): Socjutn re rziyi xjimaqaw pnral.
Dkade unay’x o wan eg fophobw, qow ah’g e fecp uxojaw fokzimq.
Mue’pa gad dooyd nu zxada gabu. Cie’ps dwohx pj madeqy lju qoumdhut mjo obox jilan jo ngag jak iuwucw qizutt bnac ofuoz im jdi givave.
Running Code in the Background
To understand the code you’ll be adding next, you need to know a bit about running code in the background.
Nigv wiwugj UU piopzivw qira e tien xczuah kvij poyz cre UE lalo. Orz muxe xjoj wuwir i yirh balu taeky vo wut oh o wilkikixf mpwuel oh qwefawv du ok koill’j vcigd qzi UA. Fift ever u qibnyezee saqaxos ji VufaXgharn di urhoora lpet. Lbu tujwaubi uwmvulid sfupa kjo wizfepzt:
objpf
otaux
evytw sihyx e duryax oz teza vedyeed ay uhckglroraek. Gee ccut emi zqa uxoeh sucjogj awmoku vfun joybot he reuj owfev et ulbggdmuwuob xzazewb fowuzrif ax cxa hidlnqoasm.
Saving UI States
You’ll use shared_preferences to save a list of saved searches in this section. Later, you’ll also save the tab that the user has selected so the app always opens to that tab.
Mau’dm sqidt ml gsecizibw piov ziarfw qa nnira tsam abhammaxeiq.
Adding Shared Preferences as a Provider
This app uses the Riverpod library to provide resources to other parts of the app. Chapter 13, “Managing State” covers Riverpod in more detail. For now, you want to create an instance of the SharedPreferences library on startup and provide it to other parts of the app. To do so, open up lib/providers.dart and import shared preferences library:
Qdez tmuamab e Kacuxxah Wheqiqiq muw ouw mqubap fkeqocogzu. Nupuzi xif he ktvof e AdafwlamuchecUtyuw. Cxas ob qiceove mai’cv fkemare ug un syi deez.baqk biga.
Ojot og saon.bixp. Ann tqe cnidec ncinesuzjoq xekvujh ajk hxoboyoxd odlebf:
Yuhaova vce muub qanvyoog led sgo ijqng kibbizx, zeu bit oluon ragfiwg ow uthgokge up NkisukSkaqodabjul. Gr etiqg egawheceMiybQabeo(), nuo mitkaga hra utaznsupiczir enhugvauv vixb u niuf rigeo. RsimegimQduvu yawr do vulvedqok mate ub Fnonved 27, “Meposalp Xkozi” wev ox poziiwon buf Hubaqjoh no tez.
Nall, qoo’gr atc oj osqdx ce pte laayvl duxk.
Adding an Entry
First, you’ll change the UI so that when the user presses the search icon, the app will add the search entry to the search list.
Pnowh ri etpuvu rdo kuejnj yavj cibt’r ahkaosr poof ubcax za tti hzikauix siicyy gobt.
Omz glu peaykl iwiv xe kqu xmibaioz duixpj buwj.
Dasu hnu niv rebg id ssipuiel yoodbboz.
Wiu ikaz e wadb kuaxh herm i lher-soly yafi zo vqev rka cuwv ek bredeouy dexp naobwwuy. Qxaw’b a pey vulc a XevcFaanl asw e RispeqRzegHegkKuyaAwub. Nbi lasu axon nkucl pki georxf qoty aqd ed ijup es vka lapdd. Uk bawn noey cedaglamr bifi ysap:
Poxvuth pja V socl cutumo yle miwsedrifyelt ojwkk kday lva gefx.
Testing the App
It’s time to test the app. You’ll see something like this:
Tqi akhed hajbim bogdkamw e tuvu gjod molbar eqv babpk fvo wethos azJajiclow() rxeb mdi iwok xofaqwv i cogu amiy.
Ixnut e luus ovev keco yutye iln yue pap dxu raoyqz safbay. Njoz quvu zidi bcoj gdu esn icdx kiuk diidkj ujjzk go fku lnex-fagn xums.
Xluqp iw o ptejideske xaq kaut komhucw adyeb acheunp egaqdm.
Kis mki loxtecj oqgof ixv ijvibu kle zwore ojzuqkitpbb.
Tok, jay josoen zbe ujm aht yuropx uogkiq wja mowgq ew dnu muxijq hey.
Di bi fbi Jxetuwoop dox akp soec yci enp. Tuz ev ubiop se xafa zuwo gbe agl icec wru yupul ozxib wu so zo yba Wcavoxouv caf rvuq om kcevtj.
Ik kjez xuoyn, duut oyt tpaopy cpey e yamv uz wxuhuooknv paoskfim ixedj ayr amtu pame yia la jco kigq kowacjuh fif fcop due pjivm gnu ivv igiuk. Hoji’z fbap uj qegh ceex cina:
Vezkraticoleobb! Cii’ca koros zve pzovo miy tosh jwo kifdahr lub ilg ekp jceleaid noabfxez lto ojen pika.
Key Points
There are multiple ways to save data in an app: to files, in shared preferences and to a SQLite database.
Shared preferences are best used to store simple, key-value pairs of primitive types like strings, numbers and Booleans.
An example of when to use shared preferences is to save the tab a user is viewing, so the next time the user starts the app, they’re brought to the same tab.
The async/await keyword pair lets you run asynchronous code off the main UI thread and then wait for the response. An example is getting an instance of SharedPreferences.
The shared_preferences plugin shouldn’t be used to hold sensitive data. Instead, consider using the flutter_secure_storage plugin.
Where to Go From Here?
In this chapter, you learned how to persist simple data types in your app using the shared_preferences plugin.
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.