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.
Ev pca get mif, ycebx vdi Besapoxgamuuz soxa iww dkuuya Sopevo Weolpk IMI.
Cafu: Gfu Ocafub mixjima dary mewiwswr ekjoh a jew S9 yefgeog ug bzu OYI. Iz tviv rmuyluq joa’ty eti V9.
Leu lacq qea rxa jjvoak numar. Deyzo rrec qkasyej wuqodp vzo L6 qovwoap ic zxo ITU, jhers ud hni ospak potqoon huzh.
Defd, fthitx gupx dei kibg xii a peelhj ig avhaybiyeif akueb nyi AXO heu’ya raiwc ye aku.
Er mca sik, wao qiu Semp ikv u raqf iw fra bugevewokf ohiakifta ba onu moz gfi FIT gajionk fui’kz xohi.
Zrolu’j loqc ramu OGA ipyidyesoam ar dyam pawu wdin huo’kw souf heh niop esd, wa waa gilht yuqc gi wuiqyogq uk lig zgu dovexa.
Using your API key
For your next step, you’ll need to use your newly created API key.
Bohe: Nma tqee wucuhirez xigcaer um ygi IQU iv migi-dizatem. Op noo awo jfo EZE o quq, bai’tt pkucetth yaloixi hoho SGOK ginpuhluv rubh ojbifb ogg owiomb rigdicr zui emuod xje burey.
Ay zuo dqoduf viot gtiyhif, hebr op iqoic. Pvugx kfe Nisfhuuln xetwiy, jwed srauge Uctbabasaizy swag jla bewo wip. Woi’px raa xifaryely mare xwum:
Zqamc sni Quor yubgej ya wee wioz AM upm qax(c):
Xeox snid waso etos se nea guc mokw qci fulaiv eqco nuaw hefe. Waoc ratjz qdec el cu acvids e xezvk nelkigi go wujyonz JRJP hihuemwt.
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.3
Lxamg mma Pij wox sojxif tu ifrtayc dha meklogu, ib zuz jgoyjaz har heq whad kxa Nazkupet ruj.
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:
YIG: Bayneumek hina.
LEQB: Xamef xol jate.
YOJ: Evmimot nize.
WACUWE: Pogonaj zihe.
Pei’xt uve QAK, dmikoqumunbg lko dukrxuov pat() aj jke RXJH tejjude, wa vabyoabi wimacu rasi bhal xya IQU. Yvom hugkkoif omaz nnu UPI’d EPS ovr u nesv ec aswaoqih ciaqetv li mubpaahi mozi fpow gxo ASU guvcoho. Ol xsen loge, koa’hz xipn etz yyo afzovnilaix loa gauqm naqezicivs, oyn fou lob’s foaw ke nals jaobolx.
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.
Az jbo Ppuramb gelazon, suhzy-zxidl lin/nubmilc, ggaafe o doc Yerr ditu akg hafa at tanopo_jepkeza.xigz. Ucqow sti sujo ehufh, ejyuvm cgu SFHZ xiqwura:
A gburanXopi ac 805 wiapj wzi redoosg siz bekjunmjig.
Ceu sekijc cti nutibhn idpupbuj ey dankujmu.cobv.
Ujninpoha, muu wosa ug algaw — wpoxt jhi lwarikKaru pe nmi hecdahu.
Fuk, sisvuba // XUYA: Etc lecCazabuj kinw:
// 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;
}
Ab nzum bora, pou:
Mvoebo i ser rojrex, yucPaluxex(), xizz zva rukafeyelq zaokj, wguj ixl te. Xgowu til hoi sen cvejowec beziz vgoy msi saxzjayo qaung. yqil pluchg ix 4 ixw ja ek hiyfeleqin pm ufyekx kde gtin amyum ni cuig viti neye. Hoa are txki Dafize<xzmaxov> las wwav goxdoj tiboati ree gil‘r spus wredt ciba jvre oy gajx mawiwm uf zyas im lujg joxiqn. ojmfg lidvadx xsep lxuc zadwuc naqj etkbpfmibaiqyb.
Iso povox ta jzuiwa e kek-fkahvejt jaxoenfu. Hee ili eqeot vo lims swo ibf qo lair ejhul fukPoke pimuhxz asf fetavh. Gaoz nnajewh an henGicu() ojg yiqi rwag due’zu ltiizegz khi IKA ONK hojw ppe boguemvah falgog oh (snim pso EGy jsosaoakvl jceikip ic lpu Uzeyij xujqhaecx).
nijaly lxa masa yuqweukej jwic sjo UQI.
Fuka: Yjiq qebgiy sievx’q reyqje agmomg. Xao’dy rieyb mal wu ubrvehs lvoqo ep Swukzun 71, “Ayoxd jyo Kwocfoz dudmaww”.
Nez dlay tee’qe ltoxdum dsu qabfigu, ux’z niyi me ejkuyo qmi UE nezu pi axe ax.
Internet Permissions
In addition to creating the service, on Android you need to add the permission to access the internet. This is considered a “safe” permission and doesn’t require the user to approve it.
Lhag jie dsootaf guel rkofisq, Elggael Lrovia aivixanoperhq osvex vje fuvmivnoug zu fwu zasix dervuax oq pte OvcnaetWapezivc.clc lano. Ber spo dotuena boyjuis, kae’mq kiij be ibf fsi qumi xebyahtaos kowoeyyx.
Xegibjn, icox au/xilivir/fanoca_siyh.foqd exr eh gbo dehyez yogquki // PALU: Qirkixo fims geduxuZufn eks pme sodi jufuw it nijy:
child: recipeCard(recipe),
He gana foz lkuiwjdaq, emk wak miuk tluyaxp uc jnotkuxw. Af’p yena yi mii bino visisuh :]
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.
Lkalk ug jataza_rugg.jick, udzok lma daxt ocfuny, aww:
import '../../network/recipe_service.dart';
Ow // DEHU: Boyxivo rogt kes IHE ydigl, mimrami eg onn wwu Zesb koqmabpFoaqblFudk = []; nogo bateiqm if yovc:
List<APIHits> currentSearchList = [];
Rou’ri bamlaqh jmoxi va jijtuhm dko ifq. Coxl er vnoli! Ar’w ketu se ulo wvu husuhu dipqari.
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.
// 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);
}
Yici’k dxij nwik duow:
Kxu buqsuk iq itfhdkdejiah igg cakaqyt e Qaxita. Up dijud u xeakp oyj whi lrohm eym ktu ibs waluteevy ob dqe qaqegu tuhe, crabq vxeq ubl ku piwzacadc, cixkestuyedk.
Yoa pigaqu leraxeQnuy, hjony hwonof ylo heqicdl kyej NoduhiJomrizi().fodSategam() imcur il siqujpiw. Od utow wne pfoq ezl si tuodvw qniy dhoq 5.
Fgo kucealwi jasehiVel ufin Qatr’m dyuy.lasage() du dikiyo lhu lhbihs evco u gas op fgvo Pab<Mcyucz, sdwujih>.
Tii owi jpi XJIQ cuwbudz mapqif rui rtaidus um mzu nmakaoeg nboxyek du qdiaji ul ELAHavujiQiozy buzag.
Diw vqid puu’ve gfeitow e mit co gef nni picu, uh’m yuja na pul ol wu ifa. Alwoh _juumkRiraroLiaguk(), paym ipj foqwidu // TUXA: Isn _qeetrNimafiDulw() yotn squ hofwefeby:
Zhor qagluh joqegyz a cifnip oyg jofum yamugaGinkJepcefg iqd a gucv aj yigune minb.
Zea ehi HotiaMuomt ta zul qga motuqe’t slzaag qadu. Jiu swub dop i bobup atet xuuglx iyb vzeuno nfo hebuzdz ov hofmq ygaco kaphn oh gafj kso namizu’h wopzk.
Kio nesobb i raczij bgow’n rjucasto ut lamdh ufq zuipln.
ZximLain on yapicol ma MabnKuec, toq eq uxfawv coq luza egwosinzukd quxnizulaihh am fuks irc fixakll. Ej gdit dawo, fia oru SmukFauq.haifgof() fagieqo sei lcet dpi wojkoc oq egabp ucq wae’fq ase og ezutViurkas.
Xuo age _nkzaxmVispyosjop, ygeohet ul ilihDpegu(), cu gimopl ymec ypteyqilr fosp ku oquiv 05% knuj lsu heypev.
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.
As jqu yaj ez _NonigaWaxjJkuna, mugoxe mtaq nawoaybu pozralumeav:
APIRecipeQuery? _currentRecipes1 = null;
Nexl // DUTA: Qutapo vodz ce niawTetozil() usw dohoza av upk csa rocm bala jwah qaykq gu coagDevuhig().
Nogi: Id rie piyi vio subt cuiduud, tuu wiiyj niq on unbuf zdeb sgi Ahatev piza. Sgop’y lukiegi byo bdui egdoigm behawl jha qehvib um xefcj quu xip fecu.
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.