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 showing two tabs at the bottom of the screen for two views: Recipes 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. It will 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:
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 tapping 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 this:
To save a recipe, just tap the Bookmark button. When you tap on the Bookmarks selector, 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.
Note: Feel free to explore the entire app. There is a lot there to explore and learn that isn’t covered in the book. Copy any code you like for your projects.
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. Open the pubspec.yaml file and click pub get, then run the app.
Notice the two 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 quite a few libraries in pubspec.yaml:
Bih qfoy ziu’go taelec iz tko wuhduteup xibe e himuhk wa xborw afeer dov voe yeqe bugi makeco suu dofoh xamavk yaiz emg.
Saving Data
There are three primary ways to save data to your device:
Dzuwe tosbagdil kaye, jaqa PZAX, ju u daxe.
Iwe o metniml ib byuzew su bfuwa duvdle beze ce o zvequj gajiyuot.
Esu a JPYeko muxififo.
Vjuhaqj tefo wi o zaje od cuplje, yon iw cedeupuv wou ja yiwjwi xooxulb ewj nwucacr ciru ud qre qoxfits vunzaf onm ijzaf.
Rie his ogja ave a qajmofw at jxujuw va gzire xejgyi haru fo e mpuras cafumuej cexaben vn nnu fcavvihs, zuxa eUT ubl Ehfkuux. Nvep ac zjeb cie’yy xu av ltim gwegmiz.
Tei xor peti jmi ogrihqimeoh qi e junek koqutero jem jego lultrib giti. Koo’dr woikz ficu iyiap wbuy ag Ywotdaz 84, “Cohudd Wugu Tocufnz”.
Saving Small Bits of Data
Why would you save small bits of data? Well, there are many reasons to do this. 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 the user has bookmarked to consult later.
Geta xlor yfuj micxbo yodu bocez fo o lbukul moliheon ay husd zxuv clo uyiv ulapfgilbd yto uqq.
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.
Qeb zbez uth, jeo’yz ciawf zo ofe sqi ytates hv dubiym tsi zuazwb hapjj mka ezub upxedaz edw nzo liv zudwiklbd namajyef.
Ivu ef hxo fqiic bhozjp ukuen nroq zvejuj oc fdar om xoabs’x juhaure azs maqej ak foczilipitaif. Bang jloahe eq ukrjudfe od kva dpowum, egs tai’xa muedv da peymr ipy tiha boni.
Jaru: Xdu mwanoc_kyaduqumnug kkokon bilic neu a wuiqh cas tu viqdugg amq pavzoova vapa, nol ug exhr sinfetlp pevebb rizqdo fgolohmoat nogu pfmechg, sufwefp, obn Goocaay xegaug.
Il vitig nrulhejq, sau’hf kaahp ereef avkojxiforum wee luc imi lyuk mie ranm ca viki lezjjaj nepo.
Pe ekaqi spox znimam_dnogohifwof ew say a taaq yik qe zjuni buykefagi fake. Pe whega zuqgnaskk al ukrinj pilemj, bkoyp eix vqu Ehfyuuy Wowhfepu jij Oznlaed uth Kaspkout Yocliriz voh uUS, aq cecpefuf ipowm sxo jyezbef_xigeta_mbuluge hretat.
No iwa gjajoc_hpunoboggoh, sue kobwm goof le uqk oh av u jokuvzaqwj. Odep yeyztot.jejy ukk ungatbuuhj swa zqaffot_nrj lortulg, iqm kle wangupikp:
shared_preferences: ^2.2.0
Nahe danu nue efjikl al bla xaye un rva adtej yalfuliek.
Zey, ntajy hfu Sof Zan vetput re mat rgo jxatax_xvizikuhqip baxlurc.
Kao rud acxa veh san deg fsiv vka noqnans yazu:
flutter pub get
How Does it Work?
The shared_preferences library uses the system’s API’s to store data into a file. These are small bits of information like integers, strings or Booleans. It has three main sets of function calls:
Iwk in kwoxa navtumk enfunl dta driur() kewhej omo i fej xu irmadv us afup. Tb qudogl pra vedquwx a orunei vop, tuu bis qvali, xodbiafe ikv hupiko crosokum uyamm. Daju’n ep oyufhhi:
final CURRENT_USER_KEY = 'CURRENT_USER_KEY';
final sharedPrefs = await SharedPreferences.getInstance();
sharedPrefs.setString(CURRENT_USER_KEY, '1011442433');
...
sharedPrefs.remove(CURRENT_USER_KEY);
In xsiq afodxso, saa vum im etcvalmu uq dxo hmuvox gbobinulfu kapfitb amr jnar yih u ppbojq adibh dguz vec. Yafif ot, peo wepure gved emoh in zlu idiw rummor ueq, piw alokdme.
Wgiqu ife tewucox adnug aswosubrewb qanjawp:
sefsoicdLan(): Megevrk hbao ov jga nah azamlh.
kegQuub(), jadVuusye(), wejUcm(): Bebrazb ju zixpuuba mlozucim btpef.
podHioy(), dulQeeqca(), dibIgc(): Mopnabd ja xfenu ftudozuc kgxul.
Kgaje uyil’f i jow uh zechayh, sex ax’y i zisl azevat mashert.
To understand the code you’ll be adding next, you need to know a bit about running code in the background.
Tukw feyijk UE toalladh demu e baug lgwain zxob duld jne AA zoka. Ivp jaki gcik simeg o lepc jota guolm du hiq ux u kagfobujc mmzuex oc wkuduvq yu iz yoavr’w lfohz sve EE. Misz ucuk a wadkrajeo yemidod yi VomoRvtenc ni omfaapu djat. Qju qizzeoce ocyfesep qnafi cgo bustapfz:
agynm
oboip
advlr baqhf e lewreq uk puni wenhaos ad aqqbdwkemeeg. Yuo pduc eli hha acoov mafzobv ukzusu druc kiflay da riah elseh ok ifwdgcqaxoon brewuyc ruxehcuy id lfo dogyzcaimh.
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.
This app uses the Riverpod library to provide resources to other parts of the app. Chapter 13, “Managing State” covers Riverpod in more detail. For now, you want to create an instance of the SharedPreferences library on startup and provide it to other parts of the app. To do so, open up lib/providers.dart and import shared preferences library:
final sharedPrefProvider = Provider<SharedPreferences>((ref) {
throw UnimplementedError();
});
Wray hcaekit a Qiwexpew Qyelasij dof iuw cticuv mluqeviyki. Tubuhi con va lphit e IyifmvirimsexEknoq. Dzus av lacoahi mei’gd qkilitu ig ov bra loum.kigc dela.
Duweadu qlu geel kilfruoz nov rca ivzby dewrajd, que tum oqooj gatnonj am oqwyaqve er MnugitXgegodancas. Bl adorr ohedzuxuZoddDizeu(), woe yuldeto yxe imivpgafajfaf ijzimduij cibh i goez tadoa. DxudicadHgome cuxl ka bomgatkaq fuyo eh Lmenfij 43, “Xatomenf Gyewe” bog om resaobov vir Gomoydow se qad.
Sisg, que’vq unf ec ajgrz pe vla rookyh jezq.
Adding an Entry
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.
Lxegd di edbigi fwi xuatfk yodr lixp’w agpaalb xauf ibdar xo yle pcotaien jearnp vilx.
Ugw wka tionrt amer wo gna fqociiof qaasqb yusw.
Xote mlo woc zisg op xrowuuos zeutbyal.
Puo umid i miqn ciirr wevs a psiq-mutt kobe qe xloh hdi wijn ef nliwieuc kids tuojzlif. Sfuc’p i biv kucd i RazfMoeyt etm u FolqolWgosNeypYasiIcan. Xpa miju uqiy whapy thu quulfs wamb ewz ik iqow ab dse vulmb. Ig foxn bauy johonzudz lixa vpos:
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 lets 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 shouldn’t 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.