Getting started
How does Chopper work?
Due to limitations to Dart on Flutter and the Web browser, Chopper doesn't use reflection but code generation with the help of the build and source_gen packages from the Dart Team.
Installation
Add the chopper
and the chopper_generator
packages to your project dependencies.
Run pub get
to start using Chopper in your project.
Define your API
ChopperApi
To define a client, use the @ChopperApi
annotation on an abstract class that extends the ChopperService
class.
The @ChopperApi
annotation takes one optional parameter - the baseUrl
- that will prefix all the request's URLs defined in the class.
There's an exception from this behavior described in the Requests section of the documentation.
Defining a request
Use one of the following annotations on abstract methods of a service class to define requests:
@Get
@Post
@Put
@Patch
@Delete
@Head
Request methods must return with values of the type Future<Response>
, Future<Response<SomeType>>
or Future<SomeType>
. The Response
class is a wrapper around the HTTP response that contains the response body, the status code and the error (if any) of the request. This class can be omitted if only the response body is needed. When omitting the Response
class, the request will throw an exception if the response status code is not in the range of < 200
to > 300
.
To define a GET
request to the endpoint /todos
in the service class above, add one of the following method declarations to the class:
or
or
URL manipulation with dynamic path, and query parameters is also supported. To learn more about URL manipulation with Chopper, have a look at the Requests section of the documentation.
Defining a ChopperClient
After defining one or more ChopperService
s, you need to bind instances of them to a ChopperClient
. The ChopperClient
provides the base URL for every service and it is also responsible for applying interceptors and converters on the requests it handles.
Handling I/O and other exceptions should be done by surrounding requests with try-catch
blocks.
Last updated