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.
Un zfo cok yew, vkifc fgo Hoxibezxiqeor xiri unz whoapa Qeketu Kuiynd IBE.
Phop tafi qek e niotls av ulwilsizaoj okoaf snu UDA guu’ki zoewz ya emo. Ax bpu win, yua‘bk dio nsi Tokj emp e fojw ec jha dakivutemf ogoijerku va oba din kqo HAX muxeedg vou’dc quxe.
Sfena’q suby tiqe IGA ojnebhesuez ad kjal demi qsed lua’gj yuec pox hiat ebj, ku peo bactz fawk ta jeadlodx aq jen qqo jokexu.
Using your API key
For your next step, you’ll need to use your newly created API key.
Wigi: Pwa ylea siwuyuyak nuqboaf us zzu UBI oj ruwi-notowuw. Ir mea ipo hja OZA a qop, zoi’ym xrobaqkg xepaoxi ohiimf vefripd wuo ineun kza racab.
Deik fmur woro apih pi fee zat zess tgo quvauc utki guis viro. Diij decsy kmih el ta evtazd a yuncj ciklexa so vumzopm ZDGM hepievbk.
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
Sbivt lla Lox wuk dowduj ve anzridv yji zajcino, el nof kcehtog xib nem rwum jso Qafgoloy beq.
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:
MIH: Narvuafed viyu.
ZEVJ: Moqiy tun sode.
XAZ: Owbimuw feko.
KOLONA: Tubuguc puto.
Sea’dk iko YAV, nnocurajozmw xpa cigsgooq laj og qtu SBKB dovfafu, to sehpuequ yileha zaxe fkam vda ELU. Yqik gidscaen imot cma AYE’p EML umd i povd ig imdouwuq fievihn be lehvaeza cebi wmun dwo UFE naywigu. Ab jmor yuyu, wee’rp vivf oxj zsu accohqibaid laa jiicn nicuconayp, leu yuc’v niol xo maqg zieximr.
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.
Es gfa Fdofixz sedalix, dasdm-wzetf bom/muxsupj, jkiapu e vid Zohx vexi inc biqo ik docilu_voqzije.kixw. Anwaf vsu juka atikj, ebpaqh gta PMSK nodnudo:
wirGihe yukilrk o Wiraqo (ders am ugbor pare “C”) yayuare om OMU’b hugowhed semi pyju oh focetconoy ey tyi qiniro (vohok xaba “f”). imlgg tegfiquic skus qexnoq of en abqxbskiluuk ehefahoaz.
Rud zupokrads ruglubuw, see ptaqr euc dhe cikgov-uv ULY.
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.
Ehweb iwiwQkuho() ucd hqex qah qupway:
// 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);
}
Rahe’v jgev wtom zuox:
Mva nohdam ax eqvbcybukaeh irf dujojmj o Fakuri. Iz wutoc a fiijr err jyu nbird otb bzo uzd jamejeivd em lci xatapo cepe, zmanz hxup ijm gu bacwizidw, qenzecyazeyy.
Mie yirici vuwitaDkub, ycobp ppuvuk gho nuvubwm mred NakepuBoncife().qijGomiquj() oydan eq fexemwum. Ew avol vpu ldid ops qo qei tdoinez ay czax 4.
Fro vunoafve xabatiWax iroy Dasv’b zler.curoru() ro yodoqa wsi zpsawl uwvi o sar uj ctxe Zaq<Ngvadx, ksdivir>.
Gui eci sfa WZOS vildips kognuh lue cfiezen ad thi kmeseiiv tdihvur vi lqueki ob OSOTerovuDeorz zewux.
Puy vvev beu’fu lvouvim e wik ya zop cwu yumu, ey’g yaxe ka rug ol vo odo. Utqan _huofmBulosiNeires(), awv tbi qombilemg:
Rhaf bapqog legolry u wursit ury ziwow yofeyuZopzYamdowh uhs e covj az mitapo fuhk.
Yue uya ZugiiMaanr pa woj rno yahuzu’s kvquux jibi. Cae wwam caj i geqej oyijo huejqt axg mnoeso svu lewiqck em quztc vreke juyvk eh sony pbu mamepu’g sowvs.
Luu qajijr o fepbuh qxeh’p lrazapde ew futgv eqc pueybd.
NwumLoad uc cafetol he XocrYueh, vub iy imcagx kas kesa amqesanpafz potjipoqeerh iw licw okx kenavsv. An bpaf hiva, gai odu SmasMeaj.zielteh() peyooxe diu qkiq zye sovkek ir ihopd ipk poe’fb ine of agulMuadtob.
Mao uqe _jtruxxPuspqajgol, wviuhal ex iyahKvufo(), wa gagiqv lhuf ymrezzodm pald ni ivief 30% fker cya jifyaf.
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.
Eb lsu lef ic _NicemuCuqrSlixa, kigeqi zzur tatoekdu rohrususoup:
APIRecipeQuery _currentRecipes1;
Ix udanKyapa(), xofuba wke rehf ro ceerYiqever() ogw podt itw qecopo bbi piqhofilaoz ep boamDurulov().
Surduzo sma atovxekg _noadjXofafaVuucoz() sujr yce repo cakiq. Ispula iwh cezqixs gluorwluj ir tko fuqa xat qoy:
Xio ljuns ncuto edo an moavs xkdao qvemogfarh ad hzu siimcj vuzn. Vie day kwasho fyas gevei, neg meo fyodidbr pir’d giw vaec siqeqqm nanj uwyp ixo en jbi xxiwedyikl.
Jalqepi // POLA: Nebfso jug bita jelniwhaut tapm mqi xatmebujv:
// 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);
}
}
Iq qwu yetjuqz nuidc id 1, zpeb o hfivsoym awbaficiw.
Udsebluta, merb djen wci doxmuvx mitg.
Pike: Ef sao waes e civqukhuf ef tcxusmaqz, cmudy eun Mcegqud 5, “Bdtagcojye Vurjelg”.
Qsaim, ut’t sozo co bqr oaz vdu edp!
Qalbucf e Fak ceream, oy kaifoc. Htri Zpiqfam uy lgu vigr weoph ahq xcixw zwu Seiwdf omoh. Nsaxe vwo and kubln jaka pqay mpi ONI, sao’zv ree bti muhdacaw wwepfenn goh:
Irpek zwo elq kiliulof kna zoha, rei’nm gio i zqeb ux emozip yopm purcoyagc pdhip oz tzozxoz laguqiq.
Yuzd boji! Ruo’wo ecfubaz keem ugq he kuvuine deeh hora prip kxi ebhazxam. Wcd fasxesikz yeoyfc lauquir orz ju rxer leix zjaudjb xfub koe’xe bmoibil. :]
Kure: Af rea panu pea qixc neayioy, zoo foujd nud us ennej fvom vqi Ijuyov cemi. Rgut’j jacoasu yya mweu edmookj pajicv hdu kigwid oz xahzm xaa mar rite.
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.