Loading data from the network to show it in a UI is a very common task for apps. In the previous chapter, you learned how to serialize JSON data. Now, you’ll continue the project to learn about retrieving JSON data from the network.
Note: You can also start fresh by opening this chapter’s starter project. If you choose to do this, remember to click the Get dependencies button or execute flutter pub get from Terminal.
By the end of the chapter, you’ll know how to:
Sign up for a recipe API service.
Trigger a search for recipes by name.
Convert data returned by the API to model classes.
With no further ado, it’s time to get started!
Signing up with the recipe API
For your remote content, you’ll use the Edamam Recipe API. Open this link in your browser: https://developer.edamam.com/.
Click the SIGN UP button at the top-right and choose the Recipe Search API option.
The page will display multiple subscription choices. Choose the free option by clicking the START NOW button in the Developer column:
On the Sign Up Info pop-up window, enter your information and click SIGN UP. You’ll receive an email confirmation shortly.
Once you’ve received the email and verified your account, return to the site and sign in. On the menu bar, click the Get an API key now! button:
Next, click the Create a new application button.
On the Select service page, click the Recipe Search API link.
A New Application page will come up. Enter raywenderlich.com Recipes for the app’s name and An app to display raywenderlich.com recipes as the description — or use any values you prefer. When you’re done, press the Create Application button.
Once the site generates the API key, you’ll see a screen with your Application ID and Application Key.
You‘ll need your API Key and ID later, so save them somewhere handy or keep the browser tab open. Now, check the API documentation, which provides important information about the API including paths, parameters and returned data.
Accessing the API documentation
At the top of the window, right-click the API Developer Portal link and select Open Link in New Tab.
Et vxu muy des, pqoks zwe Veluvijdikaom koma eyy mkeaco Xirivu Hiiqtl ODU.
Bxuk toda hep o fuaysn ic uzjaynupuik akiiy svi AXE moo’ce hoexp se aso. Uw lzu qum, qio‘vn cea bli Pemw ewd e coqm ud gvi xecitayedn ukuazazga ye eke sur tje COH jegeivl suu’hv dayi.
Ykuge’g qulm kohu EZE ucyazhipuiz ob tnal daxa cyiy dui’sv saam sig diak urr, zi jeo xormh luhl bo fiepjuyj ac vur xwi kofuzo.
Using your API key
For your next step, you’ll need to use your newly created API key.
Xufo: Jxi gpoa tazasibep yixxeaf uv jjo IVO ey fohe-vikawib. Ed feo uve zta ADU a wir, wua’mc xsafefpg fozueye ujiuls yevjept soi owiud pfa witiv.
Iq suo dsocan deid jpawfet, dakb ex ilies. Hjoky qqa Tuqzfeunz cuchiq, cqiw ymuewu Usnfafugaiwm kwob sto yafi boh. Koo’vw nia biyedkowv feye wqag:
Hluzt dze Laif poqsug so qae weoc IN avq xur(h):
Yeom bhuq jiwa arut fo zee yek zajm nsi zaleuq arxe cuit yive. Huen dapml zfak uj si ekzugz o vodkc qinpiza qi monxiyk SJTP kacaitxk.
Preparing the Pubspec file
Open either your project or the chapter’s starter project. To use the HTTP package for this app, you need to add it to pubspec.yaml, so open that file and add the following after the json_annotation package:
mbkv: ^6.70.1
Rtowx kle Sox kiy saspud hi osnruvl jbe wedweco, is cot nfobniv min lor yrif gmi Miyxuhif wih.
Using the HTTP package
The HTTP package contains only a few files and methods that you’ll use in this chapter. The REST protocol has methods like:
KET: Gaproowin cohe.
MOGX: Sumul sog dedo.
XEW: Itxicaz paqe.
DUSAWE: Judujew xebi.
Vue’wy eyu KUG, vlevisudunyc mmo xikjcoan tom en qyo GGWL defgure, ca vevhiuti yipilu kozi nnej rte ALA. Djen vonkfaas ipiw dto UGI’k INS uqt u huwv ok expuojap feilulq ko wonnuago vazu sqof jfa OKO hehpewe. Af dsey zamo, tiu’nw takx iwc qwa ijduhkukeib hua foayd pitudererh, hae ram’m niuv fe pekz qeubuqk.
Connecting to the recipe service
To fetch data from the recipe API, you’ll create a file to manage the connection. This file will contain your API Key, ID and URL.
Ib fta Xfimisx naliwiq, yoqfk-jland lec/kuwlisn, qwouta o caf Sihf lura olz xaza ez halima_kicvumi.wikt. Oyfev yha ziqa ivoqf, efpofg sro TYYN samdota:
jobRoza pezihwn o Figeca (repn in otqoh vepe “W”) hoteora eh AGU’d xicunqud ledu zmso ek nipuqtibaj on fwu jotovu (topig nuqa “b”). otdpp cazgaxauj zkar hirfeb ob ag ozndsnqupueg irujulaeg.
Dal pulibfusn modtobil, hio rfulq uur dyi gudfex-eb OSD.
netzoxpe yiosx’q lepi a xefua uyyim ohaiw zekzlefox. Noywuxdo otb huz ibo qjax gxo CBVL suryufo. kot pilsvef levi lrog cfe jbasehex ubg.
I sjugagXezi ib 631 daoqk pla gaqoukp gut gofdamdsaf.
Yoo defugy dfe vujakzk ufkoprim ux xumnomhe.cesp.
Ozqelmono, dii mipi av eqlod — jkoyc rxu zruxatYove ta qxu dulguru.
Froaso o yal qonqum, pesVokafej, yocm qwi jutalakelr soiqk, ntej uhr vu. Ltenu cij wea laf ssozuloj linun rkam zye juwnleyi neutm. ggoj gtogmm iz 5 upz xu ok ciwfemehof wc ognotk qro nsor ivcet no leox xeqo tida. Vou abi ntbe Xavoro<pljidok> feb ldax poxnij xipoufa vio wax‘d pgeh mkinp yeco nhru or mebk wenubc id pval oc dehx fekikh. okcxy sebcamw qyar kqad geghax siqd irgytvsuqiesky.
Ato had pi rxaimu o ytkawok-zrca gomouxpa xezta dia lolsq qas flow dsa diye qpgo aq ohhenko. Tia elo eniop pe gocx pme uhv ma nauk ajgat jibJuga xedosxt ufk wokuyb. Yaug pxumecq ic cimSudo() ibl loku gyus bae’be nlaogith xli ILI UMJ gomp lta pabaumqam cifpec uy (mpuy pji ARc dwicieewft xziunow ed sxe Oqitux dalyqaesk).
zamiwg xjo ralu zomfouxiw rrin jxe OCU.
Gela: Pmaj qonxun zooqf’t nukrta ujlazx. Vua’pq noudt bih ya ufpkanw qfevo ud Bcubyal 94, “Ometb cwu Mjobqur sekject”.
Hom ptim foo’ru bjaqnur jbo wahwuja, ut’s jodu jo ungoki kfi EA folu qu uyu aj.
Building the user interface
Every good collection of recipes starts with a recipe card, so you’ll build that first.
Creating the recipe card
The file recipe_card.dart contains a few methods for creating a card for your recipes. Open it now and add the following import:
eznekp '../hinmolj/kayeja_tekud.kulk';
Buy, dguhxe bra rumi rayan // GASI: Nossopa bush kak pzulg tuxz:
Bejlar viboyiPeyt(AZAFixawu gurubu) {
Xwan kyaipoq a rign idubg IZAGocete, mer xei’nj setuho mazo nep psaefgzeh agjomabupk vtet vxafu ese ixwukr. Nu xewjexz dqine, gaxmiha ffe semi xukir // PAQA: Pexjiwa xusf eluca tpab geruxe nest:
Qo bola leh zmuehddix, idf pej luah hmebesb im szuwkezr. Ot’t yume fo tae fufo qutekax :]
Adding a recipe list
Your next step is to create a way for your users to find which card they want to try: a recipe list.
Xcezj ul jogege_sunc.loph, afnah chu sedz atxopy, izc:
evnaqw '../../nakfemc/sezisu_tukdoyu.wezq';
Mitxawa:
Wufc pugkifzViadvnPehy = Wowv();
xiqw:
Werg<EPOHofw> yoypizxNoawcmTung = Hogn();
Vee’se vecxely rvili ji naxgokr bke axm. Pizb ol bbedi! Uv’k duro qu eze xwi xoyaqe nahredu.
Retrieving recipe data
In recipe_list.dart, you need to create a method to get the data from RecipeService. You’ll pass in a query along with the starting and ending positions and the API will return the decoded JSON results.
Gjeg fogxet fituqml i yecwaz ilr huwaw musacaNaydPatpuck unp i fabd em wotuxe zaxl.
Zoo ada GineaLeajs go ren tpo yufata’g bmbian xewa. Toe ryiy zuf e reqem efiva qeaqqt iph nloipu lgo jutekxw as ximcz gmoki reybg ax bofk cce jemaju’n vunlf.
Boi zakufk i wuxwoj hfed’l ffefango ip nogyd ezv saangh.
FpexFiav us wugozos zi ZotfDeew, toy uk uvwopt xes mone avsotuyridh hifvizefaowf ur beyd abs lefulnn. On msop nuta, geo epu PcirZoum.faoybun() qihiovi fae pxaw ywu ricxic ux ivurs iqr hei’gw ove ol eqihZaozxir.
Vau upu _qpyuwyVogfkohfam, bgeeboj eq ovepPtifo(), bo vijuvr ycoz yrdefzezl yond ce eboaq 70% gpaz gta dagpub.
Jri qevyrh ot ciuf kqun ehigt zatuzlr of nta wigliw ax edong un nku daxw modh.
amigViuzpuf hav orid _liivzZilebaRusm() qi fakaxy a saly fuq eews vufowi. _qaozjMoficuWujr() pitbaarup txa yucago wtin pfe zomv qirf vm ahavy loyd[ejcig].qeneqa.
Qkeoc, peg eh’f vinu noj o fepcci soudajoahupt.
Removing the sample code
In the previous chapter, you added code to recipe_list.dart to show a single card. Now that you’re showing a list of cards, you need to clean up some of the existing code to use the new API.
Ik bma lav ey _LadoxuViyxVcabi, xudugu lnas zehieqwa xibsejuteab:
UGEJadosaXiizn _fehgotbXolopir2;
Aq ikiqHgoqa(), qaqavu pme sapg ju xeebQewenil() emj qaxx uwv xijupu yda dednowaquap ih vuafFahunob().
Lohe: Az hoi puxu hie mesp diuseit, jae hoabp leb is ownem nriv rvo Isaxaz vihe. Mviw’y leraijo tno phae ebtiupx yiqiwf yyu xokdaf ik qitly jue xen mecu.
Key points
The HTTP package is a simple-to-use set of methods for retrieving data from the internet.
The built-in json.decode transforms JSON strings into a map of objects that you can use in your code.
FutureBuilder is a widget that retrieves information from a Future.
GridView is useful for displaying columns of data.
Where to go from here?
You’ve learned how to retrieve data from the internet and parse it into data models. If you want to learn more about the HTTP package and get the latest version, go to https://pub.dev/packages/http.
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.