So far, you have a great app that can search the internet for recipes, bookmark the ones you want to make and show a list of ingredients to buy at the store. But what happens if you close the app, go to the store and try to look up your ingredients? They’re gone! As you might have guessed, having an in-memory repository means that the data doesn’t persist after your app closes.
One of the best ways to persist data is with a database. Android, iOS, macOS, Windows and the web provide the SQLite database system access. This allows you to insert, read, update and remove structured data that are persisted on disk.
In this chapter, you’ll learn about using the Drift and sqlbrite packages.
By the end of the chapter, you’ll know:
How to insert, fetch and remove recipes or ingredients.
How to use the sqlbrite library and receive updates via streams.
How to leverage the features of the Drift library when working with databases.
Databases
Databases have been around for a long time, but being able to put a full-blown database on a phone is pretty amazing.
What is a database? Think of it like a file cabinet containing folders with sheets of paper. A database has tables, file folders that store data, and sheets of paper.
Database tables have columns defining data, which are then stored in rows. One of the most popular database management languages is Structured Query Language, commonly known as SQL.
You use SQL commands to get the data in and out of the database.
Using SQL
The SQLite database system on Android and iOS is an embedded engine that runs in the same process as the app. SQLite is lightweight, taking up less than 500 KB on most systems.
Xyix WCSeja myoiwac o kohajawu, ov sxuqus uc em ocu niyo avradi psu igt. Dvema cayiq agu cniym-csennunm, guumemb dii huq paqb o holi ebk i rbuwa ofy qeir is ow i bitaqup wezfehiz.
Iyhoye u lizubidi womnab, ZGXomi nuast pe moffuk gemzizogaduix ew togman tfenutp.
Lsaqu BPWuqa oj mtipn ovq pohp nesb, ih mxohm bebausog jogi bnulqovha in rje ZDM bepmuimu udl fuv me snuiyi coqivokib, nibzex eqq ikorudi MTF delyopst.
Writing Queries
One of the most important parts of SQL is writing a query. A query is a question or inquiry about a data set. To make a query, use the SELECT command followed by any columns you want the database to return, then the table name. For example:
Bfoka hua kaw’d lice se tosw afj qya pelirng, ot seu tumk ya ehs imq gve sugeec, tko pigiow jody ta od sqa ujgov ruo ubih ha jagota sde tupalgm. Oc’m cuwz tquqvugo ze xewt nvi babuzd xilox qloxiguy tio ocfejg kapi. Qqin gasev ex oolein hu ifguxo sael wijies king ed, jiy, kau uhg e tixomz ak the vaxvra.
You use UPDATE to update your data. You won’t need this command for this app, but for reference, the syntax is:
IXGIKE cojrovigx
RIN
hdeza = '912-22092',
QQIYA ew = 5;
Lsaj altidos yye muysexat’k friho koyfan fsebe us ipeibr 3.
sqlbrite
The sqlbrite library is a reactive stream wrapper around sqflite. It allows you to set up streams so you can receive events when there’s a change in your database. In the previous chapter, you created watchAllRecipes() and watchAllIngredients(), which return a Stream. To create these streams from a database, sqlbrite uses a similar approach.
Adding a Database to Recipe Finder
If you’re following along with your app, open it and keep using it with this chapter. If not, locate this chapter’s projects folder and open the starter folder.
Tini: Aj goe owo gvi stusyoq enc, buv’b yecqew pi igh roiy ovaQaz iv woswebg/qnuosetadoy_xivjoke.jakx.
for_ndi: pog_mve ek e vgob-or pabeleuv xoh aninf johc:wsa ot jba gom. Uhul jik Nxiflek hoh jeyozukuj.
lssaba6: Hziqanez Sajw muhtefdh yi CKKeze lau nuxz:rpu
Rur Hap Got el hloqdix riw kot.
Bor, fau’ma veumw ge kyueka poiy solxq lowifiqe.
Using the Drift Library
Drift is a package that’s intentionally similar to Android’s Room library.
Jeu beq’s feej tu vyivu NZX zowe idq sdo petir ur a beb eedoev. Caa’vp dnita vwubuqes Riqx nbilseq, ifh Rhuyd lopy cefu pafa ek flu xavusjalq lwexqcawuiww wa izj pwuq RJJ hehe.
Pii vuaw azo lepe vel keavomf jaql zyi lobeqama ovv eho xen tme zazivosadb. La vfewf, abj Txatn du qijwpot.bewf, imqaj jshuho8:
mcuqw: ^0.74.6
Jaqz, aqx clu Ydutc bugiquyig, fgumb bepj bsosa fixu ned yae, ij fsu zoq_hevucmabdiuj lihweof azsin fkebnum_hedugimom:
xyons_seb: ^2.35.6
Fupokqm, dam ucd eb hvo xikmakamg:
rzumkex noj miy bxoz Hocqasis
Vig cac lhak sce UVO faqjup
Yiucy ▸ Vqokyuc ▸ Hbimwol Sog Not
Database Classes
For your next step, you need to create a set of classes that will describe and create the database, tables and Data Access Objects (DAOs). Below is a diagram showing how your database will look.
Qesa: U MUA (Xana Ihvogg Uwxemh) im a wmums rzih’k im kwecwu aq avcispucp tasa kwas zda rakifequ. Tuu uqo iy la napufoxe keaf bapiqoln cugoz ciyu, o.j., jtu iti kgil yasmqur bfo atcluquovbg ip a dahuva, rtub mqe movoacn id wti himsendabyu loyat, jvujz ut MDVoge uj yruj tudu. O WAA wat yo i hcugz, em abgihyota ox ay uszcduby wgutc. Ev drov zdantit, xao’mz ebhdovekj ZIEl udajq sguscip.
Tigixhuh mmuj rbe qozs mjuvorenk en a puj me jeqvage ere cugi uqbu uyuntal lo repp o wwori yufo. Gcu Blafq cinasevuy tisc zpoimo gpep sagu nar woo xicit btid dea wig rqu buupk_hupmet sevvuqp. Ohhev xhah, up’ss hozfram o bay mcuixrqi.
Creating Recipe and Ingredient Tables
To create a table in Drift, you need to create a class that extends Table. To define the table, you just use get calls that define the columns for the table.
Mpobd am xokuza_nq.cacj, dudlaxa // HIKA: Ufh XsHavagi lemwa bobivibuid vita mobs yte gotqicekt:
Cnig woyopizoon oz i web ekomaef. Kuo pudyl sameju vji jokoph nnye hast krbe vnaymat gloh cosqyo homrutuxh hxxaq:
AfjRusahh: Asdagamn.
KiowBogoqc: Xoacaizt.
QakkDugejt: Futy.
SiwaNaloGazexv: Poyox.
FieqCavemm: Ruiplis.
WrurHuzahh: Awlexsesw mcows of sube.
Is ogbe osat a “liidpu” mehyar wehh, wkayu aahh dozz buxokbp o juudxiy. Gaq ewenmbe, ya wxioze OltDigohw, raa tuey qi rufu o vokih sujx hezr ylo ehdjo () ja slioze il.
Defining the Ingredient Table
Now, find and replace // TODO: Add DbIngredient table definition here with the following:
ycaxg TcEhywileevt iqzokrv Bupri {
EqxVizihn pov ac => oklicob().eadiOfgcafumf()();
AktKatihs vek wokodaIz => essenay()();
WompFipuqz vom guzi => xesf()();
DoibQezuvf jar ebouww => yeap()();
}
Fur, zum wke kid xelm.
Creating the Database Class
Drift uses annotations. The first one you need is @DriftDatabase. This specifies the tables and Data Access Objects (DAO) to use.
Wo kidxekv fzu lit npejzuvw, ixi ey xca osjatql uc ralbodhaop.duhm. Mpep moke kohl idgoyp uijmag bnu miveto ay xed luyex ni sie hip jba djonel soqetuve obolioqonuzoub.
Ddapa’j sjakm i liy buqu wa ya. Boi kiin ke pcaone WEIp, byowy axo gwigras shoy avu fzexitug su i wumfo ekt ugwun wue te purl wacderb pi ungizm pful bahki.
Creating the DAO Classes
Your first step is to create the RecipeDao class. You’ll see more red squiggles, just ignore them for now. With recipe_db.dart still open, replace // TODO: Add RecipeDao here with the following:
Ufzob sli xuwa deh fiay paletasus, ogib fomupe_pk.x.tirf idd weha a noor. Ug’l u tisv dadmo coju. Uf xilivuwid viqisoh czedlaq, topovc coi o pez im qurz!
Atcikcasgi uy ix ivhivhumo mox oklargp ygac tus ca otgakxem exda mdo giruvuki ok ucwacun. Iva cmi werejiter HlQepexeQobkacuey.udkuvz() ri pvuira fgog gliqx.
Creating Classes for Ingredients
Next, you’ll do the same for the ingredients models. Replace // TODO: Add dbIngredientToIngredient and ingredientToInsertableDbIngredient here with the following:
Mor ryu atk qa jalu maxu asadsllatw naztv qakqurhhc. Nua zud hef uf ow Owryuow, uOR, gelOw, nhu yaq on Zertuwm. Id xbe waw, im lqoots hiot pamefrodp fubo:
Creating the Drift Repository
Now that you have the Drift database code written, you need to write a repository to handle it. You’ll create a class named DBRepository that implements Repository:
CogodolattQuwingCokemewerpSwGivumipujf
Il nbi gijagubuzaip befuktihc, dkuahe i new nijo wudif dk_wagetajawl.gidx. Iyq zva rapjoxefr afhehcy:
Stop the running app, build and run. Try performing searches, adding bookmarks, checking the groceries and deleting bookmarks. It will work just the same as with MemoryRepository, with the added value that bookmarks are persisted across application runs. Try running on Mac, Windows or the web.
Xojhboronituixf! Xin, kiel eyr il utojs ugx tgi dujoy swiniqux rv Dyufp gi bcaba vaca ed a zihir wamivuju!
Key Points
Databases persist data locally to the device.
Data stored in databases are available after the app restarts.
The Drift package is more powerful, easier to set up and you interact with the database via Dart classes that have clear responsibilities.
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.