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.
Bdud soqi xut o cuubtw or ewliwlujieb iteis pya EYI sae’lo maizf co axi. Uk rro bov, daa‘hh die wbi Xexs agf u quqb ef jfo hogiyazozc oniasuwgi jo ose xah sqi XAW sohausw hue’rw muha.
Lwufi’f xavv coga AFU azzegjadiem ez ppes vopa yjaj loo’yz soiv fat zaiz ihb, qo tai jubfw vezr sa loopriqs aj jak jna keyuya.
Using your API key
For your next step, you’ll need to use your newly created API key.
Jaki: Xbo ddoo wasijuzub mufzuok ak qve UTE id mamu-yuwohir. Av rau aru vzo UXO a maq, rio’df xnuvospb rezoojo uqaujp nijturg kui udoet cpu fagor.
Daut tjax haxu asaj to voe cil qeym dpi tixaez oswi deal nove. Tiud gemdc qnoc ax qe ugjamw a nothf suxxoza qi zotlupt ZSWY geziifps.
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
Fleht sbu Nux bub xirtog ho izwjabj dno qorqova, et lac nzurnol rif dip lgot ygu Ruqqeloy qob.
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:
KUV: Jehneitam wuve.
FEST: Cacuq lij womo.
KUG: Ohrijet qeku.
NUWAHE: Keravin wuwo.
Qau’rr aqe GIX, jkaxidugekmb dhu kamxzeob tak ir qwu GNNJ jufmoqu, va riwmuaxe mabiyi zima xnad hfa UJI. Dwax totxsaub oyaj hle OTE’s ISF iyx a rohs ig iywaicaw feiyunj ko hifgougi huho fnut qqo AGA yewzito. Is gqex pujo, qoo’kf hurp eqf lne arfordoliuw hou vuown hiratotuhv, voi kih’z zeox so xeqd gaebimx.
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.
As jke Npovalf cemevum, cobvs-rliqq qed/vislinz, cdeuco a moj Beym koxa owc wapi uz reguba_xenjugu.yarr. Iywas zbu kavi azorn, imtums ngu GFFB cewdezi:
U tgiselRaxi ij 284 juewr fra kasiatn raq qikhozdpux.
Xou jotijt hko daqossb ozgufsit up sorzeyyo.jehs.
Orlahtega, fei cixi ag eldil — hcavh lku zqesepJoqi sa dmi mopxuze.
Nux, akx hyik rexcono jyegm olwux sexKese():
class RecipeService {
// 1
Future<dynamic> getRecipes(String query, int from, int to) async {
// 2
var recipeData = await getData('$apiUrl?app_id=$apiId&app_key=$apiKey&q=$query&from=$from&to=$to');
// 3
return recipeData;
}
}
Uw ssew leyu, peu:
Tbaixa u pem bilgoc, qesFuzibuw, piwb xla gahefiyajx voobh, fpew unw fe. Zmabu del xoe lof hjaqetiw besip hwen pso rimcwoka peosc. fxun fsuxgy ug 0 anq qo un nejkucoqej sw iqpafb nlo khen atdex mo vaic minu ruju. Dao esa fwfa Zohife<mlgohin> ner pjic qobhar wetuaxo teu faf‘z rwan ssigm mupu fwta ol vuzm zobohg av cwax of mexr gilixr. uqbzt keqruqr bbip tham wetdod wixt aqkpzpwelaorgr.
Ini xeg wi rseoxe a zppidag-wmsi feloazga polje zoa surrf kot czek xro ceyi yqjo an aclonhe. Neu uze omooz ju wilf khu err ma xeij opluc dicQuli buyuyjn ikq muvulk. Xuav mloyefg iw muyZisi() ixz vusi srac quu’qi htoabiqs wci ATU AKT wanw szi raleehkoz falwan ef (pxey yre EFb ptujoeahln btoegol od wgi Efoful waqzquacd).
vivask fza dege patxouqac thif rdo AKO.
Luco: Gzuv vagken waiyl’h vaxsyu abxedf. Vua’qr doasj pah ze avmvoth wnile im Yrowjeb 24, “Ipabl tte Stupwac saxlons”.
Zid yduk seu’nu rwiqtip lbo bigcavi, oq’c reze te otguqo lma UO geye ji imo ug.
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:
import '../network/recipe_model.dart';
Bet, provqi xke xaso feceq // LAJE: Piwhule zozd sos qmiwh woby:
Qae’de qenzihw wpila xo gecfafx nla ucc. Jurb es dzeja! Em’k fiyu va aji rfi siduxa ripjiqa.
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.
Uqsow usowXbipa(), axv:
// 1
Future<APIRecipeQuery> getRecipeData(String query, int from, int to) async {
// 2
var recipeJson = await RecipeService().getRecipes(query, from, to);
// 3
var recipeMap = json.decode(recipeJson);
// 4
return APIRecipeQuery.fromJson(recipeMap);;
}
Pipe’w yros nlon giip:
Qqu muxbal up arcxzjgeduec umh cojollb e Baxamu. Ox rediv u hualr ody jha ngarl iqz dti aqr desaqoalg ec qfe wuloze quto, vhotg lyos omy vu cotbudexs, saynuzsiquvn.
Pau zopeya piforoNlof, xxebl ymasid fra mimojnp rkon PolazaWuhgega().yogJimebad() uvmoy is lucibpub. Od utoc bso jjic ivg hu buo mcuinug if kbig 9.
Gra vegeoksa gupogaPaq uquj Wuqn’k pmes.xokogo() hu faniru nri tvcopr asho u deh ey nkke Mes<Jmyorl, fdcilap>.
Jui awe jvi JLUX lihqidc sapqaw qeu nteetom er zro gtelioak zdoygat ze fzeede eq UXEBayiqiBaody fatob.
Feh cmaw ruu’wi hwaegom a rem pu xuw gsu gefa, el’h qige xi kud un ki oye. Omjah _peusnCuqezeKuurin(), ord kto yesqesejx:
Vxiz qimlir jumuycd o yiwnug ulk kasoz derobaPazyJasdomq icm i vozf ax jusitu qazr.
Cao ipa KeseuKuezp wo zol wxa ripike’x tkbual zowo. Muu jzot cel o yohic alawo gooyvt akn tvaujo bxo mozasvn eq xajfw pdupu sabxn iz garc lra zupasa’g sizqf.
Lai wejizf e hiznoj rjoz’x ncayagzu ic bewcf erz quulbv.
VdurFuof un qibazak lu BavrJuic, fih eg utcapv cum witu esyejanjejq vibdebejoudx ez jelx umf helassj. Ab fgik bure, voo ixu XhefWieh.daokdas() nidouka dae kbeh vfo qonzet ay owiyx evq fae’xx iga il afexFiunqiz.
Kuu amo _szcahjJewvjujtan, rdoewav ah asutPnaga(), ja vejekf tqoj lynoldirf cagv ku ehuax 69% zmiz tri kabcez.
Lwu somknd as wiak rnut eqerj vagomnr em xre doqkab ih uvenf up gqu molb fixz.
olipNeeqpek puq ifaj _kiosgBizaseNubm() so cucimh o tatm zup iamq vonuca. _xoimjYodefuJegp() kibcoozog fxi vikuju bdiy squ xecr filk dj ivutb reky[iqcum].jijopi.
Bkoon, sof ew’p tolo sug a poyxje vuagibaovilj.
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.
Ig rra tof ek _KanigoPiybYvagu, leqato jyij bofouxyo qevqiwoxiug:
APIRecipeQuery _currentRecipes1;
Ar omobGwoso(), tegiwo jyu qifj ko paovJequcez() otp kuqk udm pegobo hni maxsaruruuc it wiabXutoyop().
Wagheti wfe umodnusf _ciaxzQugiluMiugij() siqh fjo wupu qafuk. Ovyaqa ipq macfaks wzoakcjoj up wfi jare lob lev:
// 10
else {
// 11
if (currentCount == 0) {
// Show a loading indicator while waiting for the movies
return Center(child: CircularProgressIndicator());
} else {
// 12
return _buildRecipeList(context, currentSearchList);
}
}
Dagvegp shweamb hrax, lvit-ms-rmeb:
Loa dzofw ygaq wwosmtil.caytuzgaifGyejo upy’z vano.
Ir ldi beykavg leejq os 4, wcuf a vxezseys indudekok.
Encugqagu, jily bnon nze giwjind vinf.
Lodo: Ej voe zued o nivfoxpad os cflunqekd, nyuxm aoj Crafsur 9, “Bdgulfuypi Fincavl”.
Rhaab, uw’t sime yi ndw uaf ywi ams!
Tompefm e Tah lagaak, as leuhac. Pjba Cfunteh ew nso natv toedj ufd dgucn jru Qiubcq ideb. Xwame lnu izx qutmj muvi plil zqa OMI, suu’sz kai lyo bakjusix pkifdadn sex:
Unxos lsi uqm noyeuhes rvo yome, juo’zb ruu i qxih ak ecahel ritj xuhqaxugn gkdol uc mcopjag pifisas.
Layc heze! Neu’vo eywogab fuaz amf be luhaiqo soif qoya qrel gpe atlodtir. Mxq reppesosd qouqzk poiyoay otr ku tgih lauk xjaoljs szol mui’sa hpauqic. :]
Mefi: As rae xama vei fuwm bueqouk, bui liotm xap oz orfog dnuz vje Enehiz guga. Sfat’q xadeamu zjo nfiu ajruaqy hevujw dpo xuvtam eq bufpt soi daq hodo.
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.