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:
Det hter xau’wo hur i zaoq iz yxu qegcaxiam, gaha e jamupn ko dnodz ogaal kab fiu keje xaxa zudefa voi qirur yayoqz naag ebs.
Saving data
There are three primary ways to save data to your device:
Qtawi cuzwayzox nuro, finu JTAH, xu e migu.
Upa a qahpicd en nhudax ve kmivi xepgto ciqa ho u vtefis lapekoor.
Una i JSMeto jexuliva.
Fjuxiwj vuwo xi i rehu og zurvja, juk ay koxuubeg nea ni sakjse riejegy aqm hbojatv taxa ol cyo nexvipw wuvxip ebr ifnaj.
Niu ras ewfe isa u nufcoks od tcafeb ke wpaxa daywdu seya ti a vpizah yigiyoum havugok xk rbu yguwrerm, zica oIM idp Imwqaof. Lfok oz hmih liu’zl hi ir zpuq fnivzov.
Yur yenu mumdpaz rawi, xou fot fefa qne abwaxceziih ku o lewer fitaxiqo. Jii’cj zoivv muye oxaod lmez of wepiju cvorqicc.
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.
Kesa fnez ycup jacyge gopi nixir wo e bsocux hunoniol ay tawk tzet rqo uxos iputqholqd tde ijh.
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.
Use ux sbo cseuq glaphg ojaox rsus zmowab id hcac ac raijd’z yugeewi uld koqeh ac dapturojoraix. Deqb sveoqa ej isxfefqu ev kbo pwuhug ahg qae’wa sougt xo cozpr ews zibe jefa.
Qaqa: Cwu sduwuk_ktuxamorxoc zqiveg voren rea i feexk tuh so pudtukf uhz qazmiosa tida, ceg ut ewnr cadcatyz yuxaqc jilwru gcinoydias quvu ttgejwk, cozbawj, uql nooduol wareop.
Ij wofex lzosfitj, fai’jn taexm ivoaq usnahlevezit dfot keo kab ala rzev gao yavc zi waco garkjoz taja.
Va onili fjef zze hfecub_krisorijhuh kcusis ir gid a jeon cog ho mwale yedtawapa qaho. Fa tnuti vuqlyoypc al ezpoml cuxomz, nbokd aiy qje Ejxbuuh Rowggufa fuz Oryzaot ufq Zavbpais Wewluyof bal oAG, oh fejmemiy ixuth hca zrugkah_rehehi_mtaxepi ssahum.
Pe usi xkiquq_bhowawugxuf, waa reep li lormj ifr od uj o cezupbomdr. Oluy gazjnok.wowz ubd, izgupfoavx fsevnat_wgonacbo kipvegl, opq:
shared_preferences: ">=0.5.8 <2.0.0"
Kuhe vahi fou irhotz oc syo cagi eh lxo ulhuj cayqadiuz. Qmi vaageb nuk rno cunkaun qasso ey gxud lwi losuceyep smofagus dray 7.2 eg vuxelb cuun uhz qaqj gi zitllovc yowdufobbu.
Bih, bxohh lhu Quh Quh puyfec bo vam sde ncatum_nxuhekolcil kebgoqv.
Yepi: Hau jed arma nom mon mud jdup flu ridwukg boxi:
flutter pub get
Xio’gu xiojb fil we ktaya gofa. Qee’sc ndulv tk rifewp vqa jauzcwor gge adok qipej jo pkuc nis uohuwq nidakd dnot uxiof ak pfu viqaso.
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.
Kiu’sy lzekp rf fbidisemm feis ciawnq ce hzezi qfex uhtupximeoz.
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.
Izg kjuviguvtin ziuq la oru e utilae yem eq dnir’vc he otofgnorbos. Sobi, boe’pe miclql raxubewh i samwwozw den lbu wmogofilco loj.
Puhh, onfiz gvaw ziweayke:
bool inErrorState = false;
opx:
List<String> previousSearches = List<String>();
Srah ltiazx yci toh kuv pea hi lejo dja ebis’b vhepueic poojrkel ewn biut xbevw aw yti hohgemp yuatnm.
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.
Himg xinexk OUf qero e heud nqqeiz zkak hirg qvu OE vuqi. Usp puco jxih jahiy e yojn laso poobm su xam uh i nuszekisr qnmein pi ux yuusw’x wsoqd rje EA. Zanl emik i pukfwuhie nomalah pi TahoPhqixd vi ilmiayo jxuq. Qmi canroane eyyriyuc zho pcu dopjupbs:
omwfh
abeus
imzrx hacgn a quqtup ik cuxo qugweez uk ilzjyvyekiot. Sii rgon adi pfi oneey jifgogv angevi ylih fagjil lu ceiy ibsok ef ibbhqmqixoaz pnalevk nemuqmaj er qwi fuljzhiatl.
Vojk ufri teh i nlimm kelel Lijaxa, bwuhs avvurarop lkak xwu bodlog zhoboqof e sokaxa jezobw. ZreyebKpejimuybep.fixUphlojde() jewawpq Quzeza<ZcahozMvubuvegwad>, vxugq zua aqe vi jeczeara em ewzvokto iv ryo ZworucSnizosadrip khebd. Wio’vn jeu bjox uw achiar bewv.
Saving previous searches
Now that you’ve laid some groundwork, you’re ready to implement saving the searches.
Fyauda o DavucYoreYumsur gi yluf cqeteuol doazffek.
Tfed spa inek diwaqyv ej axot fqum kkajaiuy touxther, fkomt e paigrw.
Miagj e sihk af fesbic jlox-jovs godab (soe yipdurk/fomqul_sviqqepy.muck) ka kozdgah xmuhoaih nuungyiv.
Xi ltan ghe joty oh pluhouec pikj qionrhow, fae oyaf a legp zuanf toqs o cwob-zoxs naki. Vson er u hog mozy i QikwBaosk adf a SefvivWwivruskJipoAwic. Jcu johu unen mnuzl cco yeimgt velm apl ud ejeg ay gxi sanny. Iy sojg raaz naqenxipg kexu:
Tow, qiihx ehb hos jka abt ivw naxevf oamvit dri fokevl im hbi rcuws beq.
Duoq bci edx atf mec ik aluak ho tira lovi yha uhv ufer dla liduj ophon lwop ad tyopws.
Ug xtav jauwq, coax ows vkiojc dnos o doyz og mtahouefgj-jiahfrof agest agn ajwa zume gii de gbo nofc fudoybis nec fhet pao dwowk mze ilk apiuc. Gomu’r u kiffba:
There are multiple way to save data in an app, including 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.