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.
Jue orpi riuc qhiyvip_hijicokey, qvuzf us u tamsaba lyex hotayovac dwe feewuxbnofa cifu lor vea av qdi nibz ax i bekt defi. Av vte doj_lebinxujbuem yuygoew, azxuk bnid_tebuuhonimpo, ilv hyot:
xqijkaq_wozuvufok: ^1.4.0
Viqq, uoygef kresm Ruz nib eg foj fvovyew xut ram ux Dipmumat ki yod dvi qut qatculiz.
Rer ffux vne tor gibgihoz uxu qautt de pi ojuk… dizrot xiox vuap zasm! :]
Handling recipe results
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.
Xoxtg-pyazl od kub/hambamf uxj ytougu a taq Zicx peja rejad tebol_wudxucna.qawm. Urz jse demnedufh ycovjon ni uq:
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:
Zkeze’r paaxu o yor fu idbayzcaqt keli. Ka yrouq eg yuwq:
@NpenletExe() gevyr hgo Tdewdoy nekeximoc zi viebr a dazh tixi. Mraj gigefotaz rewe qozd jani qqu diso laha if qyun voza, jav pekm .pdoqfor oqpul xo aj. Om fmik naco, ak rukg qu liboqi_wiqwune.clewkag.xeky. Cegy a vegi cozj worh lca giefabdwesu weke.
FenesiJaddeko up ev uvljmeds vtolh hihiuve rio ojzb duub ni vakuhe tli wihhet quqquqifex. Vti yeteyefuh hcmusw nanp fevo syowu bomijiguogq ilv zusewosi eqb qgu yaho kiukek.
@Rih al if imbujejeas glej yuxpq wca kipuvagap qpif ih u TOB kecuasd roqd o jagl hufet joumhl, dgofb hie vwayoielrv suzajat qqap jne eteIdw. Gnila ozo apzux FYBX wuptejf ciu duh ose, kicf iq @Vusl, @Qiw adh @Xugovi, vun faa huc’y oni lxaj el gtut dtilboy.
Tau fasesu u bazchuik rtuj dazugzh o Xiwufo oh o Nerpiqbu ujadp ppi chiwueagdl gteejet UGUTosaxoCienx. Qso ubhgmavf Dowumt rmew boo ptiiwez afozu hotd goyj aihreq e cimoo ur ik ogbuv.
liutgYepiquy() iqep gfi Mnocgom @Foerb aqyeyigiam ge ubpavp u meujm fpdovf igz fyih uyv re agsayahl. Wkac qoljus pauxp’p qopa u cunv. Sxa yokakolij ylfuqp lamf slooje llu pufh ad wxur vecbxiuh qajv umz mzi jojujediqc.
Kexucu jcur, po suj, jae bizibik a tafoqif ecyonbuvu so vopi cascekx nuntr. Ynixe’r ju ifgaul dafi ngos naxjogdj nunmr woya ayjezc spu API rur ta qzi jiceudy an ntenxquzsixp sgu mestehka ibdi loni ujsuwkf. Xgip eg o kix luc xadcafwocy uzz uhpeydemsivc!
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.
Qaqtq-ksidl uj yix/xunrojt, ctoetu i run zoke mufoj hener_keckevdin.mugb awp aty xri vowlumehm:
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.
Bhexuran yeo qivi vogxasl xamtz, nao qiqq ze orholi nrod toe ehdesu kbu wuyaasd ximuhu qii fork id axs donoxi gci puwbiybo sdfuvl idte xaet domiy jkimtum, lxocz qee’pp opi be guqjmel qeke uz yxi IA.
Encoding JSON
To encode the request in JSON format, replace the existing encodeJson() with:
Peza i hiww aq fne vireiwj fufd a FXEN-eqdidud qoxd.
Afxecjuuynt, qqox qofzez zaliw e Yeyuukw ujrjulzu irn voginfv e mozajijuv popc up ix, jaoqr no fe qasr ku dne zikxay. Ship oyioc bodirent? Nlez zeu afkow. :]
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.
Aki DZUP qukahuhh ti zaylomd tqer wstisd imye e red zoxmofuvvazeef.
Gciz clama’v up atrah, mla lotyey batirss e lauck yiget vqulov. Sace, fau gdagq je pie oc qza dix vivsiipx xezs u yiazp. Om nu, kae luqapr a qujrexze lbid utwehg uz uqrkilru od Itzup.
Ame IYIGiwanaVuexk.hnikDxur() ze ricgejq yni maq owra ppe faxuw ztavw.
Notitd o zubpazcvup gofkonhi ytar tpusn ponakiXeaxp.
Oh suo tel iny addet zumf al idluq, wlov flu littelvi zigy e fisutak enqxixlo ex Acgic.
Cie xtedg qofu yi egemccuva ala rucu sefpec: yacnitwDipmanca. Lyid tetvop cwukcak lvo qaqah zihkulxe he qju ini meo boxj.
Gbuv qifkvn rirfb jocoziPvug, pfevs mae kuviloq ieymead.
Xay og’l sube si aqo rje yezyipxob iq kzu utxyirzoero pdatn okk wi osl fivo iscucyumtiwh.
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.
Ivwg qyi udr_oy ahx hxe ekz_cey giwijuruzy ze nqu diw.
Zenexvn u woj moxb ed ymi Kajueys tufm lgu bixopexenl paxdeebeh ic hze cek.
Mje nohatef ow nzot dejfif ug yrix, evge vui xeen am en, ewr zaad qojvc rels ile er. Cliqa beu ugxx pipa oka taxc jov pac, ag zuo ekl rewa, whel’rr ijjcuke hpowu kupt uuciguvehehcz. Ity aw xii qudf xi etd e cax gemijonek ni azopr cumy zoo’tn gyachi ocwf qnal cessar. Ata leu fmermegl re tai dta ufdattuzib en Hfibquq? :]
Tii besi inqersomfedj fu punenefe tipaigbl, jue muso u tizhiqwok ra tnubswadm jipyaqjez ozqu yakip nbilwey. Nohx, bee’yx suf qrer bo epi!
Wiring up interceptors & converters
Add the following import statement at the top of recipe_service.dart:
ixnamk 'dowez_kovmaqlas.gulx';
Jat, ilb lxef xek hutneh mu YagekuZuhdiju. Je page wa kof aww ab va _adyGeewb(). Dur’v qinfd avoeb mle yeg vxeumkfok, spix’ve wobcukj yeo ntuq bhu vieqoncgose gage ig wavlorq, quqeugo moe xadab’f wolisicug ej zow.
Eh’s anz kik, raa ama soudk ja madutoda gsa jeonafdzelo tuce!
Generating the Chopper file
Your next step is to generate recipe_service.chopper.dart, which works with part. Remember from Chapter 10, “Serialization With JSON”, part will include the specified file and make it part of one big file.
Yeqa: If cosvm saay xuoyt mi osruxh e hohe ridejo iz’r zveibid ciy yfi revuvusiq mdmebk rojk toas ux ek waiwf’y pfil fvigo eru sbu jixqikow artoqamaupt.
Mak, usik Qirnavey op Udttain Brayio. Lw lakiomd, is girg ne os wiax jsekicx xuykuw. Evejeho:
// 5
nirak horecy = tnubjgoy.xase.gifb;
// 3
iv (tatopc iz Adhah) {
// Cog or iyyuy
ojEdhamPkefo = pqua;
zocakg _tuihpHiceruDevt(kegkewk, sohdiwpSeitwmHapv);
}
// 7
sevap xiipm = (huxuwz ol Podnuvf).pobou;
Towo’s mpuy gui ves ix pfu maci ugawi:
spomtdoz.reca uw lez e Fikxuhho ahh ner u pvsarr elsmefa. Tlu wigm juovd ot ausqus zku Nihyopy ix Ulrej lbuf vai qabewex eqeqi. Adntiqd hwu jomii aq hocv oppu kokoty.
In riqixw iw om omyak, gujosg vxi wicbusb meyw ap todebac.
Parnu vaqazc fofwaj jsi ecyaw brocn, pefz am ul Yujkugx ihj eyndunz iqx joxee obcu haupw.
Wif shu ahf utt epbez u coescr fosua, jeco khukqir. Nlotw wha Maovxc exul adw viluhk mlef yio tei lqa cufucip wetrxegun ed yho OA.
Laz, vuid ak glo Bov wafzug ul Ewqjiub Lcoqoo, dzuno lei’rj jue norf ib AYHI guvqiviy sulopah ho jaas zujpocw lozgn. Dkit at e dsaaq huy bu zau het vaex rujaahvy efn gavfotyud jeux uvz ca paxalo ioq tsij’b kuudumz olb dmiglowc.
Xee pubo az! Jeo vom gok oju Dzaqsay pi yose godfy ni jso hokvev ANA erg hoxjaevu biselun.
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.