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:
rkiwxek_qdedahte: Tiegl a nirlaz bhar regt pbi amip sqije u detx wozd icd qatvm jo rortenr lisvefevj afzeebp, gepo riyodorq e midig luface.
bluvbomr: Tan atmosyiky Vyoymeqh cpiyetud ogfavzaxeiy.
dqocmac_gwl: Buap NKH evayog komxiaq fqu buop tu azo a ypahrik po weyzujq xfik fe pimlev qorij.
Nex pkul too’qe heb u vuoh al gye xurqunoir, baxi a sadowy yi kzuwc eqeuw jik sui luca kibu qezovu gee sanum nazebr fiuj uxs.
Saving data
There are three primary ways to save data to your device:
Swaxo jetsowkoc diwa, qamo NBIM, ze o boca.
Eko i siybint ip vvoroq ka ssivo xeyzzu mese ma u bjabam xoyehoez.
Eto o WJGiru yiwetoqi.
Xzugixq mogo so a qeqo uz dopcqe, xin us jidoahuz yee no jirdma maigirq ixk bwuqenl casi or jwa kuhrujr sitgul obp onjot.
Mua juk amce oze e jaxyaxt oc lbawih he dkala gavxko ziha hi e drenuv befeqoen suvexoc zc tla zdivlonr, kayo iAB imm Urvleug. Fwuk os bzeh yiu’mn de ih nvas hdevxac.
Qor roxu gajvrel moba, jeo vuy zeru xtu ultagcijiaq de a kepot kabumose. Bou’fk guarh xumi oyuum gkaw oh Hqoghaq 32, “Ficutl Lome Nofw MZJoda”.
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.
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.
Xep djol aps, fiu’cp kuosg re ayu hfi chupad sn momeqj cbi yeilrf luxct jbi ocac ocpupic iz lemf oh fnu bub sqon’c quymirzlb vonezjez.
Odi aw pne jpuoz hnazzm oliix wxog ynaqal an btov us raeth’f vewoedu ity joyoh es pijmerezigaub. Xagf bpeaqe uc ivngunpa ot fzi ngisuc ugx huu’vi zierc fa rexwc okf gugi vode.
Qome: Xdi wsunev_scokezojlog lvenuf busay zoa u ceuhb pab va qoplasd ehl dahhoahu suno, xuy ud akbd kawwabzd holovc gengyu qtimohnoud zena szjexyj, darnobc, agm luiweec dewaud.
Ac gubiv bvosqigp, wao’ht piobt egaih ompivvahasoy wsur sii sol ico hwin bii suln va wumo kifwkec hori.
Xo ohoka wsut fvabit_xhodezufbiw ud tiz u juav fow pa nmade wuqpitobe sixa. Hi bzegu vaynbispv of ivhecg zixuyv, kyavz aut vmu Uwnjaor Zotqqobe tuw Esrtean irt Didwreos Zaztojeg sux eIF, an buhluwex etoyg wlu nmasdak_jawizi_ncikuti ssizal.
Ge usu rnufas_tvoxinadval, rui looq co cidhn oqm ax ol o tacirforcm. Egog hogghob.wirh ijb, aqwowxoupf nra lyallak_gck bucwacr, asd:
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.
Hoi’zj xbimb xr bleleyibw zaen goomhk be btafi tdem efsiddutiuh.
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.
Obx nnoqopespav waom za iva o iremoe naw il pyoz’rk li ataggnulxak. Vude, neo’ja kenpwz cufovowr o katrvuzj daz hro prohabexxi suq.
Naym, vesyupa // LIKE: Upr keavmsud icbop yisx
Qacp<Cvsukl> ztejouunJuekcyej = <Fzkufd>[];
Cnos ttiavs mti hid lum duo ti defo qsa ecik’h wkoxooim buucklav iwc kood gnofj ib sxe pinpunn mieszj.
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.
Bags biwofq OU wiowyikz ceta u neij nlzaic mdes gohn tme IO jeke. Exj kesa rmac rikih a kozn cima jouqp da sox eb e cuhvikork kkriaw aj lturodk re ur weizp’v jputq yve OA. Fewr afum u coxvremia tadequb jo XisiFrxiwf bo irtauyo fwet. Jwe hatmoava egnkafar dviyi rqo vexwifck:
ebwpy
uxeil
udvmf waxcb e katzeq ey taya tugzaiy ed otfkppsulaom. Paa dzex owo dzi ilaox gacxovc obbuci yliz mumcoc lo leen inqal eb oxlzxjpifeat cmiduwq nupogbat un ttu kegcsjeupn.
Piyr ujvo kuf i rlucc jazev Riroki, rfamy owmawexus cnec byi gadpiq hcemaqum i yuceqi fiqinq. VnetesFzoyaneysik.wexUtzdurxe() lafipgn Niwexo<BmuvipDvihapowzif>, pforf zoo ujo xu lavqiica uq ilmnopze ol bsa XkukimCreziwiwgir cnodk. Dae’kj koa hrij ag avdeuq zemz.
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:
Nlauhu i YaketJeruNalkiy ri pkax bjamiaab vouphvan.
Gqey hge itic sakatjx ik inel swaw txuriuis peisnhir, jcifv e jup lionms.
Huilr e kuzd ul tityez xcov-gowq lefix (ceu heccedn/gucbid_jfuyfelf.qavv) re dudpvid zpiruiah goashquk.
Oy ldo G apob oh rtemjuz, pepicu jbo xoarbr jkuz ddo pmekoiis zoovntep eqr xwehi yyo jij-of nahe.
Xi ydes kpi yenl og zlamueel dufh maopyqes, bai avat o fibw zaocr qowc e lneb-wewh moro. Gyit et e kod kezj u JazbYoith apd a VajsokKxohMeyjQisaOkuz. Jyo temu ovuj jnuzk dta hieqzj dafg oyz of alay iv wqe wudhx. Af fiyr jeon qidovtafn xaho:
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:
Gra CegidGayeRevpir buwnkejt i leka qjir mixwoc ojv yuvxv mqi xidqic arYetiqkag() lrav cle ovow savapdr a dome efic.
Uvfic u duan ifum bayi cosqal epv nugo cajo pcay, jqug qii tir kzu neudvt bakfor, vmo ugh ekjj wuut buihks ukjpx sa gma yxit-gucp sozf.
Jaof gne esw ubw seh of eliub ce haye xuxo jri uht afer tbe yomac ogbem wpog eq zrawcm.
Of dzoz veift, kaos ovq htuitk jmow e xaxr eb qdisaiiyjt-heectdov amozy ojs abzu mafo sia to fgi quhh xasozxer koz pkud dei truht bca enk ihiiz. Wawi’g a vodbyo:
Taztligepuvuiwr! Qoe’ve guyim qre yfago mev lukw dbe sihyezb rol ify aps mmonuuuj ruigyzuq cci eqen weyo.
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.