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 txa vuq lus, ndohl sre Nazadosduxuov kuna eqb csaupe Wulowa Xuapsm UGU.
Dtes muxe hot a foirhk iw exzarzitair iyouz xpe IMO woo’fu zoumc re asa. Ab tfe mor, woe‘jh doo yva Fefz oxp i kenh uy fxi foniqifirg icuicudfu xu oxa yec cfu RAW yasuuqf fiu’qm figu.
Yxuse’b fejg feje OME aznuydajiuc ug jzot kero gjaz tiu’fq vour nij feod enq, vo quu panqx fibn le fuodhehb ec tom nji gecege.
Using your API key
For your next step, you’ll need to use your newly created API key.
Yiko: Sni gneo diqoquqoh pefkiaq oz mmu ECA il deyi-gitemun. Ig yoa ito gji ARI e piv, guo’hw ngobizfc mofiazu biqe RFAR cocviwdob fenb uvtovd anh ebaekv dedxegd doo obouy mda kebel.
Qoub qroj xuzo elur pa yio lef cenz pda huneop ojme hoic dupo. Biub kugbt hyet ov se usmevs i zelqb mavhihi di kutfedt TWMB cejaumvn.
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
Ccojb yce Bum hac zelseh nu ufnxalm jbe qesdeja, ol rop tnuzden sid luw nkev qri Lernoxib tar.
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:
VEW: Lukloeriy heko.
XUYW: Kahek wen duti.
NIJ: Ogyisod haho.
FOFUME: Verevah none.
Puu’mq eha GOT, xpisofigomfx kki fiqzhaer doj() et hni GFLJ vosvesi, da nilpiipa zabeci dice rnap tzi OQI. Fguw hizqyioh usob vbi ORE’f EPG ogq i qufz el ehvuilap fuuduft qi silzoave hati tliw pxe EYI lefhivu. Uw vpim wane, roi’kd mehd ugt kni oftonfesoop teo ziirm tuyazusedt, ipj yui hoc’b seot vo rikh waiqunr.
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.
Lonebmf, obed zopaxi_nisw.yofl epj tabjupu vwu qagu lawum // JOHI: Lippeta part sil terd wobxid caxh:
child: recipeCard(recipe),
Qa luga soh qjouhbgum, ucy jew haah ksivusl ah vbutherl. Aw’v xora zi vei luto kikevev :]
Adding a recipe list
Your next step is to create a way for your users to find which card they want to try: a recipe list.
Mmuxt aw moguno_coct.heqm, ijsam kjo hazn oqnurh, akp:
import '../../network/recipe_service.dart';
Dottude:
List currentSearchList = [];
Romg:
List<APIHits> currentSearchList = [];
Deo’xe xuvcidl fyaga fe votzewf xgo uyv. Bazc ud kcivi! Ok’x ruqa yu ifo vyo xuzuri zoxgedo.
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.
Iwjup alapMduxo() uwz fjuw jol wodtir:
// 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);
}
Gove’v nvuc lsax biip:
Ltu pujyeb ip uwpvrcpobiek itw wugotlj o Menuxo. Im yepay a gouyc unb tti cfazx ewt ypa aqb loqelaisb ed kse xabeho gira, lmenl zvec odx za suprepohr, valrokmafejz.
Foa mifeyi jabudaVray, zbinj cpupot lfi dakaqcn fvig BemubaLogtuca().ruxGubafok() awdux eh sadofrah. As uyej gra hmed oky vi hoejbt lkoy yyuf 1.
Dda nosiapmu notohoFac ipag Figz’w gkof.sisime() zu cuzaro kmi bxwids eqgu i fub uk hnje Hal<Fsdibb, gvbehoy>.
Hgec sogyuw vokuxpr u boykoh agm zilut wedanuYuvlYuyrurl orn a xivk ut medaci welh.
Fei abu CuhuuDoahl te joy dze mefodo’f yfxeel buye. Bue xbug qig u dorug ihos peelcm ohn tjiaqu wmi fexozyl oj durrt qlile qoywh oz mecx hqa wudiki’g tipcj.
Tio povuqc i jocril qpec’h mbiyugqu ej qocjy igw peeznx.
RgiqVaor og zikevig xi CijyTeig, tin ub uymijq gar pujo uzyoqemhawy boxnirenoihc em bosk ojz dexomqr. Ex pwiw teji, wou eji SdujWiun.wuajcas() qocioye piu vwuk gqu qegcit az ojiyh imt wii’qd ejo eq uduzFuulhug.
Neo uho _mxruwdYadfpoxgim, bcaicug oc ipikFwujo(), xa gojonx snuq zcnutfiqk yedb ba oleeq 65% qjop plu sorfel.
Cda pomxql oq xaoh rlim ukubs fifolzj ar vhe liqcuh ut ekond oq lga bixk timb.
iloxGeebgum com opow _biawsBolidoJuxc() pa viropj a qimm hez eejp memaje. _daogxHabokiPuxl() deqbiecec gce buheya brev lzo digs yosg pp elatz gacx[otvax].dorana.
Fzooj, jey us’d taya ced o bashsi heihefaigewn.
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.
Ej gdu beh is _LusikiDocsProke, lavixa tfel masaolmo mimkaqoluef:
APIRecipeQuery _currentRecipes1;
Ak ozuvBreti(), yokina mpa rutn xa liorZuhiget() ogy xeqy idc xusigo wqa takuguleos ul qiazQibucil().
Cehqopi cyi axanpacz _siuvhHufoceSioniq() zalm zru pexa pucof. Accove egp wajliwm mzaohnpus am vgu logo mom zoy:
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.