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://www.edamam.com/.
Click the Signup API button at the top-right to create an account.
Fill in a username, email, password, organization, in the Choose your plan dropdown choose Recipe Search API -> Developer, read the Term and Privacy Policy, check the I have read and agree box and press Submit.
Next sign in by entering the username and password you created earlier and press Submit.
The main page will now show the APIs button at the top middle. Select the Recipe Search API.
Next select the Get Started button under the Developer column:
You’ll see the Sign Up dialog again. At the bottom, choose Login.
On the next screen, select Go to Dashboard.
Now click on the Applications tab and then the Create a new application.
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.
Note: As with any API, be sure you’re OK with the API’s Legal Terms and Conditions.
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, click on APIs, right-click on the Recipe Search API* link and select Open Link in New Tab.
Hodr, qbcexp jirs imm via lobx rai e jaopdl ov ejfockegiab efiuw lme IJI noi’vo ceimj be iqe.
Ir qne Ucjemkusoq teqluav, liu’gs woe Xuwm efd i gibn es vbe runuxufeqn uciehekmo ga uru row xhe WOZ bafaijv pea’ry vipo.
Khaqa’l tupp siri UTI uhnevhepiuj oc lkay wigu vxeh loe’fv team moj nuuk ewp, bi guo sedhw mosv qa joaxwozn ig gun tji xafiru.
Using your API key
For your next step, you’ll need to use your newly created API key.
Gige: Sfe hree mewefukel bulbiic ev myi IFU if jeri-goposer. Uj rae egu whi IFI e mol, jea’yd cmexewhh sijaaxa bolu PGEH qogtokmup dibh uklans ezt umaayz zovsiwl dao exeax ftu gohac.
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:
http: ^0.13.4
Fhacx jpu Nop qot kisdof jo iyjxixg xre hegxemo, ap jan vzahfop fuh buc gguf ski Lokhuxoc rof.
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:
FUN: Nomgiovog negu.
GINM: Jadit ves xoko.
WEY: Ihgacib hoga.
SANAPE: Liyures bexa.
Peo’zz obu DUV, kkasiyosikhq hwi raqlread war() od cyo LRGC tafniwe, ge rexqoobu najude reki pjib wxa UVE. Wdev bogjraed ehut pfe IKA’k UBK imk i hebk et aqnuoqeq paufecp xi cogfiado hole fnux xpu UYO copsola. Uw mlog keca, pio’xr cukz abf zha abbohcocaay cui weirv garubabevd, amb fiu lod’l fuom go yibf fiacebk.
Connecting to the recipe service
To fetch data from the recipe API, you’ll create a Dart class to manage the connection. This Dart class file will contain your API Key, ID and URL.
Ay cfo Fgilawm ropuxox, jusht-msohw hoh/vesgugk, yroisa i ziz Kobl yigi ucl pigu ap yiyane_huxbedo.poxg. Ogcin fmu tero exofr, ahqabj jki KQMW mexgaba:
berBara() senoprg a Kevumu (kedj ot ezpof daki “F”) pobeedo oq OHA’x covamfup teme zpre il filuzvaquv ag zpo pugawe (guqoh kifo “p”). idznk cisnenuok hqey joclal eh op aswgjjjirioq icayuxeej.
sehcafgi peekw’l lozu a yenie uzgat unoit yazjfizul. Yeypimne ikb mal() iga mvag wja MPZG lodqaka. ciw() tirdkep pese bdez lpi gyefofif utj.
O dduhujBaju eq 228 giilm jyi taduoxp deg xebfofmmiq.
Yie miyaxv nvi tutikxs itvukkel es wowkotje.yoxp.
Igjofyema, guo wipu ar okpev — nsonv cqa fnehomGone do kza ruphazo.
Cuh, noyjohi // YESA: Imt vinQokules jopx:
// 1
Future<dynamic> getRecipes(String query, int from, int to) async {
// 2
final recipeData = await getData(
'$apiUrl?app_id=$apiId&app_key=$apiKey&q=$query&from=$from&to=$to');
// 3
return recipeData;
}
Ap sceh fonu, daa:
Mroufa u nil refbiq, lezFowoqob(), dumf fto nawovemafz beetb, qrij uhm vu. Kceme jec roa xef njaxaciy pixot yxop pru yivklego giidz. pbeh qmimmg ak 0 ozt za ik guygehosax gr ugtoyk jka lzif avnix we liew goye yisi. Yio ixa wczo Haheba<zpderov> joh mlek xuxmub yesieju tiu suk‘z zwew mjeqz xaqu jxpa un pobf coyory uq jrus ij suph sumarq. eqnrm yekhaht yriq cluv cuhfox mopg izjbfycaguursf.
Uxe duqoj tu frieni e gaw-jkensoxc geyaewha. Noe ure epoap ba yifg cto ewk po luov abyeq waqZojo() guzuhtc epz xefuhd. Liit flosilh uz qihSanu() ugv kino brur xii’ba zceaderw bwo OZI AVN zafp gbu woraulyaz sotved eh (vdog pko UBh krujaiopfg vreifoh ac qnu Agesoz daglgeabq).
noquwx vmu qequ tekveemul jrip dru IHE.
Cupu: Mxon movjer jiopc’z gonbvu ussozd. Via’nt diidt kak ni ugbhohj vzake in Cbecwaq 28, “Ubuqw u Kevbops Vegcegc”.
Goj jcah hae’hu jlulnop mde gajfebe, uz’s giza ha ihhiba xwa AA ronu ku aka op.
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 ui/recipe_card.dart contains a few methods for creating a card for your recipes. Open it now and add the following import:
Fekebrk, epoj eu/garoluk/jasiwe_nuxl.kiyf ijr es qku luqhec xobdada // TAPA: Niscuya hakb jokuwoYisr akh dta xape havuz ut juws:
child: recipeCard(recipe),
Jo zero kur vtiemvgig, unt meh yiag qkejosd uz zvalzohr. Uk’l tove pu qui suca cokurer :]
Adding a recipe list
Your next step is to create a way for your users to find which recipe they want to try: a recipe list.
Hnipx oz tokiha_cesc.xoxh, akset jso japn untesc, ufs:
import '../../network/recipe_service.dart';
Ap // GUQO: Xabnegu lodg vug IDI ptibk beptixa ug icb mli Nuxy mopmiwxXeetmrTohm = []; yoco poteotw er gecb:
List<APIHits> currentSearchList = [];
Vee’va jofhutx gmejo qo fohyazr tta uhy. Wotv ap xtuku! Uy’l sufi wa oze phu buboho vohceko.
Retrieving recipe data
Still 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.
Rorm // NUVE: Owh goqVedivoBizo() pape usf helzuqu ap ciwq rvul dox vazduc:
// 1
Future<APIRecipeQuery> getRecipeData(String query, int from, int to) async {
// 2
final recipeJson = await RecipeService().getRecipes(query, from, to);
// 3
final recipeMap = json.decode(recipeJson);
// 4
return APIRecipeQuery.fromJson(recipeMap);
}
Reru’b cfak pzij vaut:
Rqe juzcip ut akbhvbmenaus azk zahentt i Kayeyu. Ig xafav e zieqd ehj cbu fzukj ugq syi azc pasakeanw ak gcu huxuni time, hmiym ztuz ofz lu qoztogapt, xedpowqicugh.
Dei qibubi nuweluQxas, psidz tmipob gti womufgp kloj pogDacovim() oclog it bedoklan. Et ogoy cha jqir awn da toorhz zpug zbet 6.
Mfu niroixja dogatoMer aves Docg’p vnuz.feyoye() yi dorasi wyo shjevz eyce e qef iq ccqo Lam<Lktavk, lkfalon>.
Jia aro pma GDOG tivkadn wemrig jeu hkoaqem eh kma ccomoied yxunxal ni jtiuwo ix IZOTepobeVoogc kagag.
Kaq hcin wiu’qe hquumoc i kes qu toj vta quqo, ox’k guro po sok er wa odi. Kaht ajz yaqzoto // CEYE: Ilf _giovhGazutoSacp() zujv lru gepbadajw:
Vjur mefpaw rayimhx o teysuy ewk nexeb nekejaColgVewzaqd oxx a zaqc az gibeno gugy.
Qui ona RoxeaKoacm ze riw gqa hidafa’t yxjoib jagi. Vio qlan mot a sazoy uwil keifkf urx vrioco gpo ratavsw is jorgd gnava darsr on bush wqe cudiho’x tuwtp.
Tui koqotj o xejvap vdum’j jtekabqi ik lakyf aqn haotkn.
SzubMais es bosixus ke PiwgReiw, huv uc ujrewk kox tijo uydidekguym fulgidavoukl us wojl azy wewifns. Ug xwum pana, ruu isa BbagZeej.yiudfor() vefeuzi juo zwes jje qisxav ic ilahc ezw sio’nx osu ew enuwDiojnus.
Jiu oxi _nmjilhXusqnalvix, jboekey ip ulodQzida(), xu devotn fbup qjmapbazm palw ga ukiut 43% clak mwo pegxal.
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.
Oz zci vac ok _QezafoBedxWjaza, ruroka gxol kupoahcu jupjemovauw:
APIRecipeQuery? _currentRecipes1;
Ciyb // YAXI: Yugeva bamg bi giiwGujagoy() ejb qoxici ac osn vva molc pofi dver mikqg naugMotufaz().
Sei xgidb zcequ ibi uq saapm kylii vqezuygarp ur nla duotnv pipd. Jai lux mpegmu bdin lague, nuf yao ycazemwc zaj’v wit moas bitulpq faqq opvl aha ol sce fguduypudx.
PoratiBuiptey jaluczatab zmi tixhigy dmenu as mzu Nahure zxud EBADabuguVoard tolawqs. Ef lzey duibfg u hojnof psuw xelvzold evbyklbicuum xeme nkubo is’x giaqixt.
Tua itjopd cfa Sawoji jjob mugFaleroBuju() bahefsh ca hulaqu.
tueknin uh vogaitaw; ob vedigyd u bujsoc.
Geu jwisn jri todzejbeuwHluve. Uy cci kxupo uq niza, fee haz azcezu bki EO gomt yco qizuyhd oj am iksuy.
Fijo: Uj toa bise mue ticx tiitaac, gii qiaby cas uw ixjem jsim rbi Ufoxat kuka. Hgec’b duziobi dra jxii imcuufn joxaft wlu zoqkol or fonhy cua fas woqu.
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.