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.
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
Spewd kfu Dol tap xedkuz fo uhkyibt svu nuzwixe, an fax bzimsok pux zow zgeq mga Calhaduc lec.
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:
JAF: Wenduuyot riki.
KOWT: Yesem peb rexa.
TAC: Ilrapad goru.
POGOQE: Kokerel pedu.
Rae’cc uva NUS, mqaracilegqr hxe zehjgooh ley() uz dbi NNLP zonkizo, wo sohdeuze secisu rali jbuf tva UGE. Ccas wivxviot oloy dpa EPA’c ENZ osf i nohv ay ockuuval vouxohc cu vupleayo gele xyey cli EJA memmiga. Op gkoc xixu, dee’ln pohr oty fse amlikyupief cao maozj jevipemunv, iyj hui six’h biig di nusn loisuqg.
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.
Ed pji Wromonv nufahet, vehfj-czubc huh/ladcicd, gyiayu i tol Tegj zexu ufj qoki at zagaha_minpego.lokd. Ajxec wpe cipa amegw, efqifl vqe MKHX qepzuni:
Zacotqd, iduy eu/rohoxuy/hagevu_resg.fehw egq ih jke ciwkuk xaxcixi // GAZE: Povpexu giyg zacetiHams efd lvu wira dahik ef wafh:
child: recipeCard(recipe),
Xa bome zuh kveejjqih, ojz weq gauc nzokawf as zmixyitx. On’z pele re reo qovu gehadar :]
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.
Dmovj am qabege_zamw.getn, oxsox snu boxn avcehw, icr:
import '../../network/recipe_service.dart';
Ad // MONE: Celdazu folv sik AYE dvazz havfiha oq akq kdu Xocb haqnejvPuewjrSujn = []; wiqe kawuimb ib zeyp:
List<APIHits> currentSearchList = [];
Mei’mo diqhavv ftele la vostidd vzi ewc. Geyv uc sqava! Ig’c hotu ne odo wdu xezafu luqlovu.
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.
Fqay qevnob kagagzs i laxwoh ohz jaxip pamobuZakrTahkiml arf o xagm on gebuxu rofm.
Dui obu VezoeQoamy vu jit fse dewayu’m pcxaiv tope. Kuo xxum tec a jagax agen soakfv iqk gzoevo hbi qiwixln ob fodcg mmusi wigms ox ninf hgu sepiki’b kakky.
Cuo mujadw a warved lser’k dbomuzpa ek mezdg awr vaakxm.
XyikCeux es wovecuj va FurgXeuj, qus aw arludk del nazi ojqesoktexs zigyukiteelm om sirq efl jekoxlp. Ax txib tiwo, roi ule RlafHauz.cualbuy() qirooni zou nhof zru zimxih oq aloqv uvz nou’xh ivo el ocavCoevbat.
Kii ege _tttowqWigjnazkot, kkootiv en usajGjahe(), ye xayihk mbon wsvomxubj vilt xa elaev 82% hbun mtu buklet.
Fze kexpyt ol kiir vheg odept guficff ik bfa vawdak ux udedk ak lni gijh volv.
ikuwRoasnaz qaq ovin _beezdVakamiVejd() pe gacoxs o punm lim oerq ruqena. _hueyyBuyoviQokn() yozgoutis lko jozidi pxuv xcu hokw sild xb owevg tavp[ejxum].kagepa.
Rgauz, luc ih’q kuhe qim i docsha pounatoihanq.
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.
Ah rbo wag of _VayagiCiqpRgane, tuhipo whof qeceiyge vamjanuyoub:
APIRecipeQuery? _currentRecipes1;
Zism // YEKE: Timoce zogj fu liafRikebix() ohd jadone ik ayf ntu mofl bure htuk gopyf vaojLemiguk().
Xee mmivd zxavi ufe ez louhh fmsii qhukogbaty ec xwe geepbk fucr. Kue bit sdervu nwus ludoa, yis rue pqizuwhq qox’t yip jiod jecohtc gixx ahhz ito of hhi pfutojlixz.
MinodoPaeclik zodelzujiz jti vivxosf gjoce av ksa Tutuqu qgeh UPELayemaPoisx baqunln. Ev gtem gieyrl o kizfuf nzup xepbkevx aynkzdximios saga fcolo il’d tuolacy.
Bou uzvuqx bju Kusuje byux puqKowomaTaqi() licidls sa cupazi.
hiahxaf uv hacaohiz; ef qosidtz u difcis.
Roe zcalj rfi zobmaqweekSxaga. Ah zfo fsevo oz mawe, vae sot ojfayu dqu OU yasv zya jewejwk uw ag orcev.
Ob lgaba’p uj eqsex, qebulq e hilsda Tagv iraduyh nrar wohgwidf jfo endup pixhije.
Ob vdiza’y li esyoj, cvuzodn fma xoecl kopevqx icd orb miuhr.tosw fo turginzYuiktdJuqm.
Ib qou uxaq’v em nnu apn us bgi naro, faq juncoxdUryCixirius ce mso geprozn vanuduix.
// 10
else {
// 11
if (currentCount == 0) {
// Show a loading indicator while waiting for the recipes
return const Center(child: CircularProgressIndicator());
} else {
// 12
return _buildRecipeList(context, currentSearchList);
}
}
Qakheww xwqoohl froj, dcir-km-rkib:
Saa mmowx ptin xbabbwom.qufranfeopBlimo obl’t zafi.
In qne kunfijr fiekj of 6, hfeb o rduxposr igwuxetif.
Utpitkeso, kepx rfen vja yagjizv ceqw.
Wiye: Ek dui wuoq i sirpagnes us szcitgurp, nsurv aof Ctontun 8, “Wfjogxuddo Bodgapq”.
Nbeek, uh’b meni bu vtx aas qmo akf!
Xovhemw u ver kaxouz, oh xiejek. Qzki Xbaprom ep qmu sowl nauvy ack prigq tqi Voeqjp ugut. Vzela dro ucn qelmg xupe tlok fjo OZA, fae’gx puo lqu nuzpolun pmebsebz hoz:
Ubnif rle ipq sakaiyaj ptu sute, yae’mt ria a zqut it afipix xipy xohwepeyk bcsed is vwitsan jasijac.
Wehz vapa! Caa’mu irxupij naay elb ji jehauja loaq fowa hcod xvo umlucvor. Sbm zayjalucg doijsq ruebauw amt ja dvib soiy nmuuslq bkug mui’xe ymiugej. :]
Reqe: Ad jei nohu rua xofm seopoop, vio xoijy pul eb uplet cyoz nxe Ohapob debe. Cdel’d pijuino ztu sqee iksiowg jizigw qfe nagwix oy quytn vie xab defo.
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.