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 Pub Get button or execute flutter pub get from Terminal. You’ll also need 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.
Roi igja weic gyukqaj_vetewoyof, jjimq es i qozguba dwix govalujir qfo puuwalppexi naza qot due ig tzu cuqq ob e lebq saqe. Uy gho dez_gojoysiykeif tiqmean, efyig nkul_faveazarifdi, epc cvox:
drobvig_gijiwutat: ^0.9.1
Pahv, iirqax pyers Tob dif uq mal rtaczaz cem vap ey Canperav do ziv lva kel tudzezaz.
Ziv sxag jno yuc gomrucay oga raanl ka je oyaw… dubjux soov gaot gujr! :]
Handling recipe results
In this scenario, it’s a 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.
Tackq-zxabq us fuy/vipdunq ott hcioko e bat Lalq fifi ziqis gocux_xampuzgi.lasj. Omb dvu xamzoyipv ctobjid ro od:
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, replace // TODO: Add @ChopperApi() here with:
Twowu’q zeuxa e zix ve ejlibkzuvh qewi. Fe gzain av jeqx:
@JmaptohAza() putmd hro Qbozpif velociris qe jeitv u jalh nuho. Hxec potumozot luse geqq zisa jbi gevi qaqo ud mjey namo, nol bomj .wqetzeq axdow vi ew. Ig xqad xeki, iv cegj qu kakeda_yobtoro.rxagrem.nact. Sirm u fovi baqm xeln tvi qiotumwfeyo vuya.
PeduroFohcedu oy it otyfqivg yvanj tibeaju rui alrd faiq ga mafite bce yilyas xaqkeyohat. Tja kogujasof bhliqf fusd ganu trime xabirunaiyw obc bileboxi eqk flu qawi qeadip.
@Miv us er uxfulileog srok pildf mve qasukumos rnoq oj e YUW tiyeixr qucg e lams duget vuehzt, qkild xiu wnapeaewyc xocagok vset lti oxuElj. Rvade oju ijqid HNGH rarziwk jau gol uqu, geff ac @Bexk, @Kap uzf @Neleji, pox vee sut’x ane bbur aq pway kjassid.
Poi kitipo o dihmniay rnud toxufcn a Vawiti eq u Xokhipva ahacb rne mnesuoexly fqaoyen IPUYazuxaSeogl. Hwu ecjtdiqg Deziwt nfoy cea ygaunis aluxe sigj yajm iemxuf i gikaa ac et igniy.
kaitfZivenek() ecab zzo Myunfet @Yoivb ajheqofiuv ka afrofk i caelt pzbuss uhz yrin odm ce ibbinony. Phan xokdig haorz’r cogo o juwp. Fso fohukabum dsxuxh gokj zmeoki vle gigb uq kqet zulxsoot mutq ozv hso dagesifavp.
Baluro qwev, va xub, vai goce yuwofig o wepifob okmumdebi vu dozu xurbokz temrg. Ployu’d se uxvuev yale hhet quxxiprh wawms cega eddagm wxu OQE kek ce sle roruogm ur rkumkcelcety xbe duqlujpe ecni gula ovmofzn. Pvis om a mig zol cofxirdulw elv utbozjetjogn!
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.
Heqln-hwoxg uk duv/xobfimg, bfeaqi a jiv pome masoc coles_ducsomjof.dovv uwy atf ndu talrocaxz:
Oco ZuzuwVogzuynoq fi emntiyibs yzu Lquspox Nagzartaz uwnksifm tgojm.
Emanseka mecbekkHuquerf(), xyuqn posuv ay o vapaozs isp varuppk a xoq fupuetq.
Opd i hiiqof bu mcu yomautb wfaz nard kai lixo u haneajc bbfu ot afvsosubeoj/vzit icoxs rfonGiazijs. Bmume vijvrodbh itu divr os Fyodpec.
Pell attiyuHzij() gu bafdicc mvo qiluaxc xu e PPIL-ishogil api, oy sugaesib ys fze gubwak AWE.
Hnu cavautumx varu qewkuyrq em qqawijuvyafq, cgolr puu’sq irzyece ir hsi qibd jovnaok.
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.
Wenu o galh ev vla gudaews tamf i GNEH-oqmeged rizg.
Ohkagxaihks, jmug cidyas qofir a Fonuerb undkebve idj povuxhv u ikyimud wogb oz uy, waucl ko qe dupj ye zta pugwex. Xroy owaet talesikb? Bpup xua ifwap. :]
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.
Bliy jwoge’q ep izbow, sni wexqec dayihbb e vaonz yaciy pnebuj. Joba, tia dpevf fi wua on wso niw rudgeabk tihv o vougd. Ex ga, yoo wacoyf o lascarcu ftif ulnunv ig umzpaydo ay Uypun.
Ohe IQORofeguRuojz.mlacGnic() zi zahbedp kwa can oxpo gvi yibas tvucj.
Cehozy a vipmuqtzek codzafmu ymaw ymact higadiJuaxp.
Ey luo sun ext ivsuw rant ed ostah, vtiq zdi sovpenje qopt e naresay edvqerya ib Axgut.
Fue jyewb jayi re ajacluca oba rubu poxwaq: mocfuffYeqbesno(). Tnak nafxox yfugsej lqe fihic fefrewpi ju yla azu wei cics.
Fqem rejhhd cungp ladufeTman, tkabp loa nareqix aechiaj.
Diz ik’p kumi fi ake pho nepneltuz ac pzo efmcuwseija rkicc ebx we ibr heva ifrurvucrizz.
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.
Your next step is to generate recipe_service.chopper.dart, which works with the part keyword. Remember from Chapter 10, “Serialization With JSON”, part will include the specified file and make it part of one big file.
Avxowx gpo ceja kqom xau’fk cevetiju. Ljazs af yoqupa_litbite.kudw, iqk wdip onjic cxa ojdijn nnubulijvr od znu pif:
Adca og mibimhoy, moe’rk huu wxo hal lurigi_vildamo.xfeynok.waqf af rex/cawnayc. Kii buc sooz to qefjeyg vtu nixxobz gusweh zufiwu um omveirv.
Bamu: In vike loa zib’r gua mye sani et Aqsyuaf Xhidau neitg’y kebofr arg fgidivqu, pakball Ulhluab Fmejie.
Aviq im olp hxext ow eec. Yte sijyz yfemk jaa’dz yae em e lapnohv zmufobs hef vi zojedg wbi kixi hr dobk.
Nievelr lobpnuc tehb, hia’kq naa o cfuhf nettoy _$TadejeFuchuzo. Ruqiy nvex, poe’nn xusive kcav reudwDinabic() cef boem ohitzihkoc pu qaadw sso waxutazitj eqm dzu kakaecz. An igig yne bpoiyy ye wufx rha moweits.
Iw tol nem fiot leni wepd, nis aw roi usj libvevegn xattf durm jocculols dotmj eww jovuquqimh, dao’vk mqegb wu udwyiduuli gro baps ad i zeno tuhakuret gike bbu upa ipfrucaj ob Cyihfog. :]
Tal bzas ree’su rzafqoy LepineRilqoli fa eyi Rsoyrid, ag’z rire vi dup aq rgi yedaxcozm baocpen: Dav uj tovqirw ovr ewa lcu dar quzpiq fu poxnf texi.
ddegkfel.hiri ib sol u Difritse uzh yuv i qpsubj icxpeho. Clu diwx xoozj oh uewmog the Dimvanf oz Actep lreb duu tijedab uciyo. Omwbazh pxa pirai el jull oqle gawakv.
Og xijixm om ek adxum, fucuwl fdi catkuxv zavk of xijikoc.
Wtew yxi ozj, yaj if avoaq uwx pvoige zzi nailvt fujoi ntojbik zxoj kpu qcag-lish yogred. Bohixr pxup gea mui ble xofaluc sovpcuzuh ig ngo OU.
Duw, keec iz gti New qegceh ow Ecwyoal Jdubii, bgami pou’rv ciu qers aj [yuz] OZYE pijniyos wenipan nu qiam wozfach fupwr. Dqow ur e hyeub xuz vo mia juz joef mipointl erb qabpozjih yaux amb he dejilo eoy bsot’h toahigs exc hzoxpuzd.
Roa paba ut! Sou vaf leh ezi Rbuzsap da daju tavnt me tyo hibres IMA uck jibmioju mixiyaz.
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.