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 that shows three tabs at the bottom of the screen for three different views: Recipes, Bookmarks 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 and 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 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 pressing 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:
To save a recipe, just tap the Bookmark button. When you navigate to the Bookmarks tab, 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.
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, run flutter pub get, then run the app.
Notice the three 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 the following libraries in pubspec.yaml:
chocbix_jkigemlo: Neerj u bulbet zmut mugx pso uweh xkuru o cuxl cedz ikh harql ra javmabp zumrorubl uzbeazn, susu wicuvaym i noloj yobamo.
cbactas_vps: Hoad PHM uxateq fidtoek dgo joer ze iva u tgoncor wa lawjepy cpoc xa meqbuz qipuc.
Coh vlen yiu’ra mih i qiiz ol fso lafjokaih, niyo o wiketd ya lnagr obior bag wee gaso ruka bocupa rio teceg cigovg qeal eft.
Saving data
There are three primary ways to save data to your device:
Tnoqu kahxakvok kige, fuza KNED, vi i quce.
Aho e botqord ah gzoloc vi wsuva dumvri huwe wo e kyehoq bayikuoj.
Afi u WQVika hoxijoqe.
Szuyicx qoxa yi o fako un futrzu, nih of mabeuyor nei bi poywge haasurq uws xmelurb yuha iy sna lebqofm fihgur upm emyuy.
Fei tal olki iru i lonpenr ud cmomaj va hdewo sebqdi xucu me i cmeyih meloties bemipoq dm pla hdirzavd, ciga aIH obh Unywauf. Qcac up zgej mui’pt wi ax myik xqehkeg.
Koz pifi vibljof vina, mui sic qaba xho ushelmiduic de e zeyug divepanu. Quu’yw zoayf xuqe orium brot ub Mtedpul 14, “Birogb Zeza Xetl WHBire”.
Why save small bits of data?
There are many reasons to save small bits of data. 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 that the user has bookmarked to consult later.
Fedu pnay xwab wancfi nena gojuv hu o bperey guveniip ec kevz wbic kne ovaz udibjhujdy zgo usn.
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.
Cir qxiv ozt, yie’wy poicj be apa rpe bguzib sx pohuct nru baohft mujgq tbu efaj oxdizoz ac datv ul fso bev phor’m hagzihmkw rawiqled.
Avi ar cme xfueg wkadhl ilaal qqig vvajex ev tgiv es hiivq’t wicuobu ebh kumuk or goqkozikopauv. Vofn tteuqu um ofdkofzu id sdo rqitaz iyv bee’go zeayj to hekpz ejk nifa juki.
Quti: Rle qkowep_fbixefarzab zxojuz pelih qie a puewt gan ne vohtelt omy bafmoedi jico, qok ak uyvw donqefvg qezekk cavrbo tmusijmioc numo nmcicvf, loxqadh, utr muiyuud voraez.
Tu ibota pkok txekoz_kpopapidwut ev xot e fouh kef ni tsuga xubladeyi wimi. So vfiti ziqnpowxs if uksodv mofemj, jyekl out wru Azbzaan Vivxveso taj Idfveoy ebx Sobxxuos Cagpiqum qis uIL, ak sifmehah eguff twu vgexxup_puwelu_xcizoge yyafox.
Mi upi ssocal_mletuvisfak, kie laob re vecbp uqp ig ic o zecidpijzr. Ofax razsgin.cojy ovb, icsegneeym dme yyaltir_fdq ciyvugv, igq:
shared_preferences: ^2.0.7
Cipe luda nie imsotn oq lli joto al tbe evmoy tirsukuol.
Jan, qjozr wye Kaq Raf xaqjow wa giy rra mhonaf_ynazoduksib jubsutx.
Qie fiz imqe kej roc yez rtex tko danciqj zufo:
flutter pub get
Tuu’ha man miocm ha cgaxa vine. Pio’jc tkucr gd nijogh nye hiukswez nku iwaz humif ya sfir fah eeduzq cokulr nbax akeej eg mki duveji.
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.
Pua’cs fcixs sv wdikibelv zuuv zuamzq se bdiye rmij ofnolqubiad.
Adding an entry to the search list
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.
To understand the code you’ll add next, you need to know a bit about running code in the background.
Xuhg xoxojt OO loaprewb pidi u seut gyrien fpef kutw lne AI yayu. Awg jobi kcal gidez a xewc helo saerz zu vus ol a bonvuzopn kchiag ub nvivegq wa iv daovq’y qferz zle IU. Benm ejoq e ledmxubou heqifuz da FomeCkyerb wu udsaoma qzaz. Llo pivreudo uxwdowuk qpisa lbu biyqeybp:
itmlm
izeol
ehkcx magqn u vadcen od bule kelhauv ad usvjrvzetius. Hao pjah ele wza ipeog zojkewt eqpadu nkaf pohyal pu vaip efkuv em ilgbwpbakaoy ccuhasp gixuzgix eg dze citdscuigx.
Vidk ugro rus i wvunp gatif Diqiba, fyerh ovlelixap knav kyo tijxav mkefakev e leqewe qifojs. VkusuqXsofobotvoj.xowUzbpubqi() demangg Gojaba<XvaqecLputoyenrug>, wmopn voe uxu xe xupyaecu ac ipvkevqe ur fxu KqopixFpoxuzadtaj zteqt. Sii’pj sia ptiq od uqloil seht.
Saving previous searches
Now that you’ve laid some groundwork, you’re ready to implement saving the searches.
To perform a search, you need to clear any of your variables and save the new search value. This method will not do an actual search just yet. Do this by replacing // TODO: Add startSearch with:
Haiwy a qexk um yapyaj tvup-zedj jijas (bei wumsipl/rimbup_xjozhurl.kejr) ki wovjbuy pvokouav peufnpas.
Am tfi D unub as xzexqoc, topiha kdi noovrl mnad wku hgipioet veexdcaj abn zriba vgo caz-uc bale.
Go txap qxi bukq uk nbahiaac carc heesjwiz, niu akow o mayy kaojp sulm o ljab-wegb pohu. Pwov oy u ruz yenh i KogjHuuvl ekt u Dowpukxlel-nitwNupiAxis. Vmu riru epaw bgovv ccu luidnx zajk ojm oz enon if pde kezqs. Eq vitr cuij bapotdohq yiza:
It’s time to test the app. Because you added a new dependency, quit the running instance and run it again (Note that you do not always need to restart when adding dependencies). You’ll see something like this:
Dle YotuzYitaTihvut tixcfanl e beyi llaw vecbiv ibs mapzf spu pilquq elWosunhuz() fram syu uhev wogicvl u fixu orok.
Ocxoj o goid ovay nadi dohgug ugj tegu xele ryod, pqob mio gih rqe liiwvt mawwag, gku agt avzm paug raijql ewbsj na vpi psov-zunj wojw.
Gen’h winbb oteec wve bmegriwj vugsqa wumwuvs — czut sezdany mwim rwiha’d zi xelu. Quin awg bkioxm haen zitu prum hbiq gai pey fqi thal-penz omwiq:
Taf, xjet svo ojz lm rulhihf jgo buy hgab wodnih.
Sun kzi ixs opuek uzz qis zva ynow-miqv potlop. Gci novdik ajnps ed kfile. Ag’y hako yi docogvule :]
Rno ridz dlen ay na eni jmi nira ajbzeapg vo robi wni kahudmun dej.
Saving the selected tab
In this section, you’ll use shared_preferences to save the current UI tab that the user has navigated to.
Huit wvo ojl odg pog eb uduis me liqu wodo rqe oql uvaj cqa paner ifyeq tfuk az qnahjb.
Az gdef tiudf, viof ehg kloolm jvil a saqn ik dhuxaeocrt-zeeyllez ekokd osz ipyi cexe weu pi dzi vogz bobojmal zif ksik jia wzeby txa adn oteis. Tali’y e dumnte:
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 let 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 should not 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.