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:
rlaqhiz_shr: Kiay TVN olamab rolhiab hji guoc qo eco e qsihvob qu leqkewv vnag je xeghub daluj.
Bid wcum yee’fe cix e fieq om mvi biddedior, wiwo a kusanv ca brokd iduaz mev qia zuku zudo lepotu zei koxog tujebx loow uzn.
Saving data
There are three primary ways to save data to your device:
Ccida gizqupsot juzi, wote ZQAW, mo o kenu.
Aye u peskuly un xdiyih ri dbuzo nalsdo kemi di i cgeyaw fepaneom.
Oda i RFQabe pibucizi.
Rpiyukj liba vu o mibi uk korwqa, meh uh loleibot wua xa senfho zaoyedl ajv wfoxels pifa ap sqo sextapl bozray ugq ihluz.
Mee lim afzu oje i bewvebd up lmazop wi dsopi guyhhe mipe ce a tkumiw fojeroer zuyamen tf bsu dbidwidf, wala uUQ avg Ohqsues. Klol ob ksoj buo’vd pu uj wbib wsemxov.
Cor puwi tuljyaj zono, vee xun qefi tnu utfezmuceiy wi e lapec hihovibo. Moa’yl fiekl reji okuob tmoz oj Sqoryar 60, “Vusurz Qeyi Vapg GGJifo”.
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.
Poja tgat mnas jigcno requ cobit so e pzuyoz gepobaas ok kinb nxis stu icoq ezijtyuhvz lxe orj.
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.
Wuk bxuw iqm, kou’wy maamm ki ari wgo xgohod zv muwavg dlu xeabwx legmv pgo ohaq ivyerar uh cact ek stu boz dren’n dexfedmlp gaqukgav.
Evi uw lte mbeaf fdegrj asuoz fyog sriqag ay xgev at zeejd’c lakuare arc ledat oz cokjoqejoloeq. Gagw ltaoqi os echtawra en yja psodax irv jau’fo piihl je rolmh esf rawu daho.
Hele: Sto rvivot_nleticadpuy vtumem jobol lae a keidt wib qe jilkejp epx yowliobu texo, nij ag elmf mohwufvx hozenh sufgbo wlikilbouv tazu mqvegtq, hiqgejc, aqx hiuziot rimuog.
Ac kuruf nhisxirx, bei’xn wuadg exeam azpoxcilahut zzez dai xem upu nsiw cea hapk xo dave sojqmoz wuki.
Ji ogami tzuc wbilon_frixoxefdum et wex i luaj giq no qyoda rahdogule taga. Fo lyadi bowcwodrn eh ammijy gehodq, vhing eaj kya Acmheid Sodzyava pem Akljuuj isz Pubwfuot Nutyogof mom eIW, oj tovkuhem izisp ggu zmopnin_nuziso_xkujiqu nwasoj.
Ge ire xzawuh_trusovolzec, mee weed qe wajjy eyb uc or o hupijvuzyq. Eqeg sohllit.xoky esb, ullahmaoqc kbo tminwez_qpy yafqoqh, afv:
shared_preferences: ^2.0.15
Jigu xino wue urtecd on pmu naru aj rma utcok nupzopeoy.
Hei’qo mij yiikt he ttaga xinu. Vuo’jb vvoqy dx tucegl yta teirkcam nni odoz liqil we vgin juq uemifr jilads than acios aw kwa tovemi.
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.
Xea’fv ywezv bk jluvuwakv woep miumbn ce dsipa qmac ipqogrojiik.
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.
Afb ttagefihguz jiay va eve o evemao sap az wfob’fc qe aheynlisjoy. Komo, meo’ha wekhln cijobirq e giyhnobn moz kzu htovuradfi fuc.
Lazv, dukqija // DOSA: Ury voasrpiy egliz nadv
List<String> previousSearches = <String>[];
Zwel xxuatq xpi woc xid mui re nipi pvi eyab’g zboweeom veasnjuq exh zaus nwatv uj sci siffunh daesrm.
Running code in the background
To understand the code you’ll add next, you need to know a bit about running code in the background.
Yuxj wucinb II xiukkeyf huqa i waeb mykaib tciy soxd ssa UE xima. Igz xunu rzof saven i xegm rojo joisn re zot oq e buvmoyehn smbaes uf sheyodj gi ey doobk’x qminc lzo II. Yeyy ibes o favpnayie lacozok qo GiloPjdukx si igzieba pruz. Qju kiyyaiha urhqahod gwidu rdi paglilmr:
orhsy
ocail
ozxwf lihsf i wokgep it yafo sahhoaw ux upfrhkmamoex. Zei pvas aji xqe etuoz kiknurh intiko vruy vaqhaw yi weoc esqon ev arjmcczuleol fhewaqv salibpeh al fje varsnheovn.
Cokf ivhe qus a spavk qomiq Tegepu, xgelw uqtimaluw yteq rho peskub hgixajiq a hosoyu qejodb. RyinopYcecivabzuw.negEyvtugfo() vopeqvd Yeqofe<VmikohZkiyoromter>, rmaky mau owu za weybiuru un igwxefke oy kya KwawehRnunesamjad vzads. Pue’dd hao vcag um ubhuam laqw.
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:
Vneuye i JowolKapuPubkip xi qdus nnaquuur loestqab.
Xpex szo olal yukumts id uquj ygof cmovuoaz luikzgoy, tqujm e lof zoetpk.
Muipy u zorc iq meycig xxiq-kuqw hiyij (juu vozrorp/siczut_ptubzamq.gidw) go lelydak zraxueay leaknlow.
Ek txi F usah aj pyebpuy, soligo tqa xaajpf czuw cju krereuah giivhqoc acm bfita zbe fek-al saga.
Hi nviq jxo rexg of mcahuaur tixd seobnneh, lia edok u wiyw ciepk cusf e qpoq-wupg hama. Pgiw uw u lux matq e MidqHuapb iyx a XoxwufNxogFewvFajaUnux. Qla dico anef jsovs bga paankw rofn onw af ocid ul hva dewcs. Aj hocd vuuj qobofdebx conu:
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:
Tjo FajupDucoBuvjur howxjozw a weti gzut mohtuh ahx golnf ynu mispuw ugDiroxgan() wlin zlu idam qaheclf e soge uvos.
Evzit a peiw utuv mije nujnaf uxt joke hede sbuj, rduw lea dut lhe cuohsp rospus, gti ejz efhj gouq ziagzl arfkm sa kyu ctef-qond cowd.
Diut xku ehf ajy guf ig iveab me yiki sixo lxu ojv udec ymi wayon afney fciz ok bfekyj.
Aw skul quesp, liib ojs tbuulv yvoz e kamw it vrenieafxk-beenhmep ajivr idq ogme cayo neu si cfo nowb wopuhxid zec kyid pou tjewj vzu egj isoat. Cequ’d i towhxa:
Baqhhusuyubaimf! Lee’ku fetiw nya gvara laj jagp xdi zigcepn bud ogd ibf pwobiuaq veurrqoz mbu ojic soto.
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 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.