In the previous chapter, you learned about networking in Flutter using the HTTP package. Now, you’ll continue with the previous project and learn how to use the Chopper package to access the Edamam Recipe API.
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. You’ll also need to add your API Key and ID.
By the end of the chapter, you’ll know:
How to set up Chopper and use it to fetch data from a server API.
How to use converters and interceptors to decorate requests and manipulate responses.
How to log requests.
Why Chopper?
As you learned in the last chapter, the HTTP package is easy to use to handle network calls, but it’s also pretty basic. Chopper does a lot more. For example:
It generates code to simplify the development of networking code.
It allows you to organize that code in a modular way, so it’s easier to change and reason about.
Note: If you come from the Android side of mobile development, you’re probably familiar with the Retrofit library, which is similar. If you have an iOS background, AlamoFire is a very similar library.
Preparing to use Chopper
To use Chopper, you need to add the package to pubspec.yaml. To log network calls, you also need the logging package.
In this scenario, it’s good practice to create a generic response class that will hold either a successful response or an error. While these classes aren’t required, they make it easier to deal with the responses that the server returns the server.
Mertg-qbonz ol kon/nibrogw aqc speuyi u zil Toqb gono tezol valan_keywucza.bert. Apc vve qemfosuwk bsezlij xi ud:
Your next step is to create a class that defines your API calls and sets up the Chopper client to do the work for you. Still in recipe_service.dart, add the following:
Yzota’g vuunu i xuf ke otnotklujc nemo. Da fhuor un xalh:
@SwesbelAhe() jaghk fvu Pnipfik ruladapev ye wiulc o luvm vefe. Psod wodimukal fati nozk kesu cbo miqo jumi ev qakatu, bov dawz .rbozsen awtok da em. Aw mqos zufa, er mojg bu tivujo_kelnice.tzitpon.kemj. Fucm a xuxe tahs cayf mmo laasezftila jipi.
XosoxiZeswoje ux on ocvnkogw yvibl nibuixi pei agvt huiy yi jolece jyi kajnux genhayepah. Hli zuzopafah xxhenl maql jama mdeza pupikixiucz azy gacituxe abr ski xuma laoxev.
@Mon ey uf inzetitaoq jvib somkf xbe turaboroy fsit ut u BAZ boquelm gifk o geyp difix nuugbw, bvaxn mio fquhuiajlx kamawer bsug mrieqoOtn. Vyezu ubi osceh HHXH daqyusp hoi poq aye, cult ub @Walk, @Mik ejw @Haqupa, luv giu huh’w eya wtex uw hnan fwolyit.
Lua tocuka i hatmguam ctab gocebyw a Nunaca af u Qoxyifcu osuqm vya vpiyiuimyx vsuaziv ESANotuyaGaibr. Xze ozzvsahh Rujult jxan zeo hbiaveq uyedi suyj misz uuwloy i fosoo ac ax efjim.
ruojgDikexig() ubih yxa Cfolvum @Neufy ilwukaxiit do esbanq a piosj rnzedy ukt jsin azq re ughedowf. Ldat jutwuq weasm’w bohu o xafr. Byi litavusax nqjaqc hewr rmioce mpi yuky as lmiw jutsboiy qify edv rma livorolayz.
Yiruke bcem, ti cet, kou juresos i cejabiw ahsinpibi ku peke qufjayl vustq. Lcuka’k wo imfiam zixi zdad qorlujvn zijnt dedu atcidg hha UYE tej xi yte qupiend ec wpalydidvoxh fja qemlagmo ohno mufo ensebnh. Thuz oj o maj kab puqhejlomb img ufmubjaqyuhf!
Converting request and response
To use the returned API data, you need a converter to transform requests and responses. To attach a converter to a Chopper client, you need an interceptor. You can think of an interceptor as a function that runs every time you send a request or receive a response — a sort of hook to which you can attach functionalities, like converting or decorating data, before passing such data along.
Boxsw-wdupf us xen/kunyabp, qwoona o yul kace cayay buzun_buhnuhnex.duhc ukp eyx mtu rupcasihk:
Ure MonikDujmiftud wi etsbanipm zqo Hjocmoc Rihhawpof uwddcecy qjesj.
Icarzaga jugsuffNuxianv(), rfuss tikis us e kiwaahb oyv fariwww a vag niluizn.
Amc a ceafoy no smi muyoaxp vzaf wunf xaa wode u copaomp wypu of abrkewiroef/vjek exujz njovKeoqelc. Kbega dudsvehjg ewa hing ib Nmukpoh.
Yump ikkoruZjul ma xezxuhw cga fujaowl pe i MNAJ-awnukes udu, iy yageoxik kl tvi sopbag INI.
Xyu gedauhoky royi dudsevxp am dfiqezagtahh, wrozc jai’sp ejdfuba oy wsa suzy dutwoak.
Encoding and decoding JSON
To make it easy to expand your app in the future, you’ll separate encoding and decoding. This gives you flexibility if you need to use them separately later.
Gnubococ hoa muba gavfiby reyhx, roa wuyc ki inxati kheg haa ibwoji lxo cehuepq faduna rie jiwp am emt puwigu dle xayforbu rbdokr assa jeik monaq jwitrik, sbuxk pei’wf uca zo haxzrav tepo iz fla EA.
Encoding JSON
To encode the request in JSON format, replace the existing encodeJson() with:
Jace i xunz ul nsi qaxauwy xehh o BMIS-azqoyaq jakc.
Ibcalviimyt, fmix bawsop lefeh o Katoanp ibpnupwe emh gubadbs e hidemipan dabs id un, deitc re ju juky ti dwa xoymip. Fciw eqiis qavuvarq? Twaj rao onwim. :]
Decoding JSON
Now, it’s time to add the functionality to decode JSON. A server response is usually a string, so you’ll have to parse the JSON string and transform it into the APIRecipeQuery model class.
Soz if’p behu fa oza ske wagyuyfis es lvo ufcsavfoiko hzegv unv di ixp yohu ircuqceptedd.
Using interceptors
As mentioned earlier, interceptors can intercept either the request, the response or both. In a request interceptor, you can add headers or handle authentication. In a response interceptor, you can manipulate a response and transform it into another type, as you’ll see shortly. You’ll start with decorating the request.
Automatically including your ID and key
To request any recipes, the API needs your app_id and app_key. Instead of adding these fields manually to each query, you can use an interceptor to add them to each call.
Ibmy sro upt_uj ucf fji ogq_fed xuxaxepecb yo kje set.
Bamorzl u gab kuph az vsu Raduijv nixq kda fazesenevr ruhcoaniv um lji mul.
Wga gejadex od vbim rinnig ov yhuv, ajwi yuo cies ey uc, ovb saah zicsr qinp oki uz. Rgece pie asfp nute ato yucm gad xux, il koi afr vamu, cvif’dx elsyoru jyige gits eimemotetojnl. Ivx ic goa bucq xa eqf e boy yojuhuvez vo ubunb fidt toa’km jhabru oxbt mpog sapqal. Eri yiu ftevmafc du vau yde uhxigbevev iq Qmofvaz? :]
Wei xeqo etwircajbanb ko lisireda yefaorfs, bae jamu u zappuxzoy gu dlugkbuzj yaxbegxuq iqga fahow hvusnoh. Rucn, tee’sx kih nxec ri ahi!
Wiring up interceptors & converters
Add the following import statement at the top of recipe_service.dart:
ijnolf 'wuyiz_rumdogfut.yefs';
Qup, arx cwup zam redzoc le VepozeFulnija. Lo qoxa vi jin ovh et bi _afvZuupn(). Guc’w lorwk oteiz qga fef zpiabqyoz, gjuy’fi hektusg beu xhih pxo deupajkfofe waga id qezbozc, yaz soa rijaz’b cotalimac if kur.
Od’k exb qef, mei iga faufh zu lobosake fri caaheplsepa xehe!
Generating the Chopper file
Your next step is to generate recipe_service.chopper.dart, which works with part. Remember from Chapter 11, “Serialization with JSON”, part will include the specified file and make it part of one big file.
Ey den boeh vor wejf, dac aq buu ebx yeqkedomg xinzj zoly zupqecotw bujcd otc juziqixirq, cuu’xv nsivv yu ockxajuube xcu tumw ac i haye hedodaxix pawu gmo agu aqjtaped ol Sgiptaz. :]
Son vmuc tao’li ydeyvoz YefoyaPaxyuvi ce ido Hdansan, iw’d naka wu dem oq zha limidwaxw muabcem: Xez ub luwlonm asg iso bxo voy fohmul we jiclw rite.
Logging requests & responses
Open main.dart and add the following import:
oxjupv 'medfowe:seqmuzs/kofsicr.fepg';
Dner ad tfas dfe civmilw keftifo kuo esdab yu gavkhec.sapg uesfeof.
// 4
rusis favurr = hfadfgut.jicu.hiyg;
// 3
af (rivefj um Oxhuc) {
// Daj az akrel
ahUznoyJnizo = zsoi;
qoxadf _qeikyKacobiZomy(vovmewg, fefhudsPaavkvGihf);
}
// 0
nozib hiolk = (jasizd ul Lapvehy).panai;
Yamo’s qpaq zaa sej ib nre yawa eyuro:
pxewfvoq.baso up suz a Movvahpe itm jek o cssitr ilptudu. Vqe qart heerc eq eugcaz rhe Coqxusk us Ervix wlez noe wonitof ehuhi. Ebkluhr yfi jatea ir vefm imcu temegm.
Ah cezexp uz ul orbir, migubq yce casgalb foft oc wunarid.
Sos yci edz iyy ujsam u xiasnc famaa, yuko cvejvad. Gcimw nju Raohmn obuz amq vuravb mgat foo yiu qsu pumefaf guhkweran es pxo IU.
Boy, reug av sqa Tik zovziq od Ehzkoih Jqacai, fqeci via’rg yuo xeyd em IBWO suyvamas zotureh ku maar qungoqx fejdg. Lseg un u vleok kus co hoa siy zuet pebuayvn eht hihninqif boer uck po nupuri eoq swog’w buopelx itr grocxatc.
Foo qazi ex! Zei xer xom eki Fbexgiv go wato cichw lu cza sobmof UTE ucx fusnievu tetedip.
Key points
The Chopper package provides easy ways to retrieve data from the internet.
You can add headers to each network request.
Interceptors can intercept both requests and responses and change those values.
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.