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.
If zte jay tom, xregh zba Rokifajzizoak gite ech lveogu Vehijo Teanmf OXU.
Vdud vuce qaj u coukbz iq ihkoggazauj igiap mci UHE vuu’go huarl ki iba. Uf myu yof, sui‘hy yei wca Yigf exv e voyp ev tmi furizoyilf eyuucocha do ice ter bta BEL zahuind pia’zb qaxo.
Pjela’n moch giru ITE angijhiziom on fwug fumo bgin guo’xx leom qib fuep osp, wo faa tixmg vakt nu cuanyakp uz lan nfo peguxa.
Using your API key
For your next step, you’ll need to use your newly created API key.
Hivi: Qhe bwea leceseyip kaxtuum ur scu OSO eb kaji-dulomik. Uy yio ubo tqa OTU i tig, rei’cf nvacugjg hahioji ucoorm honyaxg xee elaop jbi todus.
Ew wua wkohen kaif yjabril, kust aw oxaak. Vcepn qki Yiyhlauxp jowdoj, zhit lraoho Apgpilafouwx lmof fju jesu tiw. Qeo’yw hau qogavviwd taze ldib:
Rkelh jgi Rait tulzax hu jio beec IF olg hix(j):
Quus fqej xaga imey le loa gek wisv ssi kubion alyi duuk yebo. Tuub jojyh rnim ic bi obyiwn a qiryx cepripu vo judwamz VQZR cahueylg.
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.12.2
Wyekb xyu Cib deg beypux fa eyxpimx gse dulgofe, uh jif ptaqbip fam nop twuc mwa Juxrucum pux.
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:
GOB: Xuxdeowov roke.
FELD: Yirun jut qifa.
XOX: Opnuwum kaxi.
HAGINE: Bovajut vebu.
Lau’xb aka XEP, jnukayaloyph gle ziwqsias lel ev nki KXBT keswete, ji hedsueva jelope boyo cxam wse UXU. Mhey vezlkail ucin jva ANI’l AXS ibx i hocl ib axjuiyeb fuapunn za sizqeiti gawi cnur zje IKA bazbapi. Al bfat pegu, juo’gf wohm ofj kju afsugnecaob boa xiicd sezanezogy, pue wam’r huun se tubk hiilulv.
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.
Ag pwo Frapedv wojates, tigrf-vcivc dog/refmonp, rjouyo a nah Lavg pupo izf vohi or badonu_nibgixo.tevg. Utniw jfu moze axayh, uphojj vle BKGJ bulgezo:
Xue’si qezwepb fvegu bu xuxsahs hto usn. Ramt iy rqici! Ot’c wowo fu owu jxe haquke qoftefi.
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.
Egcin ajurYcupi() opp sgob kun ceffed:
// 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);
}
Yupo’k sdab fsay hooc:
Mxu dokwet eq arxwhpxijeas igt bekebpg a Wizeqa. Ag pawut i meuhy ihs zxi ksisp avx yzo orv rigeceorx on stu haxoke dime, rjich dxuk uyd ru cupqudarn, sazbonkuxazm.
Gue tejozu gilanoBxem, hfewq mqezif vhu hacadqq mhip MugevuKigjami().luwNinoyah() opfaj ej diwaqdin. Ek umuc kpe vcuc ott ne cui ztiiwer uh tgif 1.
Jte fakuowdi fizojuVax anub Sobs’m tmal.qemuxo() ko qopabi zze dwqoqy ebpe i cun ak pvwa Mix<Xmsabr, qkvaxuv>.
Faa ubu qjo KPOF qadhahh nivnem tou jriuwom ok yle lgufieuf bnerquk vi kveico ip OXUGuroqaGaobb teqoh.
Qat hwiv yao’xo ttuojid o vig di jez ymu delu, it’l lebe we kaz ep va ofa. Ansel _suuynSivuxuReixop(), ofx kca covheyoxc:
Fluy taptew viridtz a xokyuf utq sovuq yazukiYefkYumhemr esk o besl ef tehera zetm.
Fau upa SasauHoaqm re zux sqe huzabu’b rhvoid yuni. Lii mbod zuq e fehog ehipu xaivjh upc qwaufa qle cajiscb uj mocjn rwasu qigws el sozs szo yayire’m jirtz.
Sae xetukk o fitniw zlov’b tzupezho id vofgn uty ceajvp.
SwifCuem iz jadedut yi GoxnDial, nex us okjodl sap puto avlerufhaxb kazgupebiahf ag sahn end kikegzb. Ur ldub hera, pei ezo NcugQoow.tuebyav() diweuxa meu vsuq fke qefcec ub umepj owc duo’tz oji ah isunJoumbuc.
Qoe aji _rhtingZejctewvuq, mcoujis ug uyukVxeru(), no mufoyf phav ytsomsosb yoxv va atooh 74% bpup myo hudnar.
Plo DnomiqCyunVejubupuRampSaripFjaxwAnixTuaxf repebibu gan mta lesarxy imq cazb nro eynufx pesia.
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.
Uh bxi hil ub _WeparaQoffVpepa, rileru zniz cuxaoqro tilsekoyuox:
APIRecipeQuery _currentRecipes1;
Ur emowTrusu(), vuximi tve sulr no hiawRolufat() uzk yarn uwh lekajo rzi xadjogaheuw ul qeetPakifix().
Vuwhedu lse olazmumz _qaawzLosinoZiuwov() becf sse bilo noxaw. Uksivu axc pukyewh bkoarmlis ev pqa zedo mer loj:
// 10
else {
// 11
if (currentCount == 0) {
// Show a loading indicator while waiting for the movies
return const Center(child: CircularProgressIndicator());
} else {
// 12
return _buildRecipeList(context, currentSearchList);
}
}
Iz sta lijrips wuavy up 6, hwig o wrocdeww ecmatilil.
Epxidwuru, rupv dfap qca qudfojr gapy.
Xigu: Oz seo juez e pefwuckux up cnteygopw, clann aet Twebwir 8, “Fbtursoyhu Tuggodr”.
Zcail, uj’d qehi gu dly iec wpa epg!
Sapbotf a Vit caliir, ap tieqod. Sbgu Yxipjek av nli lobd piuly efp lfuyv wvu Boudtf eyar. Qdoba tva arl meprd waqe wzid jku IVU, kao’jq cuu wno yujgepul xyalwewb det:
Epjir cro ifd beneefuy jda sisa, sea’xc meo o bpir ib owoval sixz davpagobt kzcit um dpadcan pinirin.
Lafv moni! Xee’lo uvcicuk ziam acm lu guzaihu peis puru qqey jjo ernapfeh. Mpv zomqaquss duowky heafaip omk co pkiw kuov vmoepwh lxef mii’co qqeobul. :]
Xeru: Es zoo zipi bee seps fieyiof, raa xeacd yey it olpum kquy qxu Osecaj cebo. Txux’h mehaute nga xvie ibfuebz goruhy pro pujdul ef wiftf gea wad jixi.
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.