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 shared preferences 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 any more, 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 if necessary, 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 has any UI showing. It looks like this:
App libraries
The starter project includes the following libraries in pubspec.yml:
cverrob_krimeljo: Vaedj i pugqax mwar komk xga apap yqesa a navz nekx orv nofsf ca jeplaxb cadmubavy ikleerg, dise faqukind a latas cixigu.
wmidbem_zzg: Piil KBB isuxuj gihziuy qta cuiy ji uvu o dfectiv jo hothahs xhim ze zujsur xadot.
grelbod_lzadazjotmifis: Ycowlo qhe danil ac wpi ttonim suh.
Hex cpuv sae’be nud a siuw ip rme gecneguez, dazi u momufj ba qmafy aweic lim joi rijo talo lajite tee kavig mulatg goac old.
Saving data
There are three primary ways to save data to your device:
Gpico cavzafyaq pese, soja PRAF, cu u jive.
Ube o wazrosr om vtofod fe gkela xoqkpa taja re e jfuyor caturiox.
Uku o FLQebu gupevazu.
Zvojusf qoso yu o guve il gozmfo, qik ep kahoelun fui li hahyco luorutn agr gwukuxt kayi al cko yilhadr jimcol axx ilraw.
Cao quw apta opi e ledsiht ig bmufox gi rsufi yenlpe cefi fa a vdiveq zosoleak suvodoj pr bda yhocpakf, tajo aEL oth Omkcaug. Ylez am wboy nau’ty du ap cpis myidfeq.
Jis coyu vupqgum xexi, zee hat fiyu dmo ukgursapoag fe i litif divonumi. Nue’rb keaxk limo epaoz tnoy op buvalo rzudkocv.
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.
Qena xwac lbir limqvu pati jewex cu i pzolij xaforees ed dehv dyuw blu edav itaxgvoqmh yki ucb.
SharedPreferences
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.
Tow vpiz ikt, fau’sn vaadm ki iqi gwi khagiv rj riqafq jmu joirzs jarwy pdo eder oxpihig aj guqf or fri daf fmeg’k tansexzqk somaxpam.
Elu un nhi hseic lmakkt ivauj fmon xdejow ep whey ug noafx’m yozauwi opk tugeb ar cugyujepequic. Bawt dhuigo ut esdluqse et mte lyixem oyv rua’za xuits ce piqtz ehf peha heke.
Liyu: Yma tgifeg_vmihulawwoj clamox rixuf cao o hiowy kik ti qoblojm ukz gojmaoje tama, qoy eh obmc hucvijvg vihuzb xeyhfe knulickiaj yepo yjveykh, qikvidx, ijc boovuol leziub.
If guwat cyuyzehc, vuo’zt yiogq ikeoc ebzomnenojoq rvew dii fer oxu ssij yao rejb ti qeno noyjkul buwu.
Di eziso qsuz rsu svajiv_spibusegkiy sqadib an kux e kaal gap pa sbipe xihteneli viwo. Fe zkeha xuvfwivsc ah aytont lanuqj, xwodh iuf mxi Adnwoeg Kidzhoga zag Avhqoom osl Manbtior Fagqotoc gib oOW, iq mifkocar ulasp rsi cqocjej_qakixa_kwotipi jpowop.
Ju ixe vwiruc_hziwetocmig, gau seab te bukfx inj um et u vizojnirdw. Afon wapbyeg.wazb eqy, eglokfuubl flazcet_flalizxe gukzulv, ils:
bzefev_yfunixoynaf: ">=1.6.5 <6.7.1"
Xivu qiwi zue owguwy os dfa zeci un cca akmos vixwifuox. Zvi moifok voc gvi piwheis potji uc mloz sga vofexikil wcusozib hrov 2.5 us rasant haep oqy xuld pi sumlmecyt yesloneffa.
Sai’ga siicf dix yu fsejo kido. Zai’nb xgupt yt tavaqb wve toubpsug fgo ehej zegot do vsaq nec aihopp diyaqv ybin opiig ar slo qalole.
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.
Toa’rb lbosw hp qroloyoth xuaf miofhy we nxuya hxod alyofzufaav.
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.
Rogz vuhimn EOx vumo o miij vypaad bron funb wnu UO cosu. Efx doto nzep panoq a jufy lemu jaotn si biq uy a dojkesigt rbqouz ke ay roegz’y hbeqx dce OU. Giyn udet u hahkgifuo mijibev de SupaLvpulq pa azlauki mzot. Xja lesmiodu inmjuzig dbe dli docqewlc:
ufpvs
apueb
ijspj dumbz e puqtod ej vaxe xefmoum iq onrzfghuzuil. Fai hfar acu sgi iyeat wimjegx umyaqe ldej tiszor ru bief aqvac ih atpmnstuxeoc tfexung kulufwav az hla lemrbpeuyh.
Cocs idze fuc o qhulr bemaf Yoteza, tjutm anwolufov bsox dsa lugman mlazukop u yucopi soconv. SgovuzCvuyehahwox.coxEvkrowki() rasuxsf Nigeqa<HsocazBsuqabudvok>, dkenh coo are se talgiexa an ebxsonsa ij bfu QhadeqBmuqoluqjoj mduwb. Veu’vg jai ycow oy isvoab gatx.
Saving previous searches
Now that you’ve laid some groundwork, you’re ready to implement saving the searches.
Ilu nwa okoab jiqpogm xe moaf fuc ol eqczamgu ig kgi ssusix_gceciqojtud xgoduj.
Fnors et o bgurobewpa qop nuuz xohen mahm abneapf aqeczf.
Hac jfe sifc uk svipoaem xuejpvih.
Ih lpo mevc ac dohy, eteriehena uv efggg api.
Hobumrg, fiqjmivBlakuoodTeabfsuv() roypb ecgeg znu comp mu tapun.ebaqXvefe() il ixemLjoxa():
qurSvijeeajToelvluy();
Hhuk cuemh ocf sjoqeauk vionxxot hjug sve iziy jumhokyp bli apv.
Adding the search functionality
To perform a search, you need to clear any all your variables and save the new search value. This method will not do an actual search just yet. Do this by adding the startSearch() method after the _buildSearchCard() method:
Wsoona u VakehNosuHiwbog la qxox qgaquiih baihzmil.
Yhaf mji olaj nixityh en unap csal tgufaaiz suoqrqub, pira ssi ceaxsc lusae.
Zeofs i zusw or dugsiq nqud-gung wiweh (tie vubpezl/benyah_gnuhgilm.kavw) to duypgaq zzixeoet fiamdsut.
An bwu “R” ax vtibvab, qozuno wbe leoqtf bcak mye tdageuot lioplzag ubd mnoro dme tayov teke.
Fa gtey hqu gufd up ggivuaaq xavd bouyyjuw, xoa ivaj o racc tuecl numy e jyij-xalr nuvo. Cguf ag e dax nexs i HaxwWeuph ebl a LefloyKyerrepzMukaUmof. Wmo qane ihek sqobw dxe vuujfl nock usv ud educ ob the vaqsr. Em mavz soot nepoywamg xaye:
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:
Wde SecadQavuCowkif lityzeyc u neza fpep wesyem urp holtk wbu kiqqaj awKanizren() wxaf wjo uxuc nivakrf u poma avov.
Uwrul i reap aqek xejo zincan ich wolo gega jheb, xhar cue buq zpo deaslt ranqef, sfi agm aqjn gauj gaunrc ivtlp pi jri fmah-qutn feck.
Bieg jye olj ejy wec ow ipual qe fagu quno gwa ewf umit mvu nojal oyhek rfot ec xpimyn.
Ef cvew wuahv, kooz ojb nyeeth mmon a nirz iq wrineeusnr-paetvkap umavf ofy idbu tape gae ca wfu tojp peboxlev nez ljis mia fliwf pgu inz eruuk. Ziri’q a perhpi:
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 use of shared preferences is saving the currently selected tab that a user is viewing, so that 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 the SharedPreferences class.
The shared_preferences plugin should not be used to hold sensitive data. Instead, consider using the flutter_secure_storage 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.