Skip to content

Retrofit: Getting started

Ravi Teja Gudapati edited this page Aug 24, 2018 · 3 revisions

Adding the dependencies:

Retrofit uses build_runner to generate API implementation for Retrofit specification. To add Retrofit generation support to your project add the following dependencies to your dev_dependencies sections of your pubspec.yaml:

pubspec.yaml:

...

dependencies:
  jaguar_retrofit:

dev_dependencies:
  jaguar_retrofit_gen:
  build_runner:

...

Example ApiClient specification

Given an ApiClient specification, Retrofit will generate the implementation for you. Tag a class as an ApiClient using GenApiClient annotation and specify all your Retrofit specifications inside the class.

/// Example showing how to define an [ApiClient]
@GenApiClient()
class UserApi extends _$UserApiClient implements ApiClient {
  final resty.Route base;

  final SerializerRepo serializers;

  UserApi({this.base, this.serializers});

  @GetReq("/users/:id")
  Future<User> getUserById(String id);

  @PostReq("/users")
  Future<User> createUser(@AsJson() User user);

  @PutReq("/users/:id")
  Future<User> updateUser(String id, @AsJson() User user);

  @DeleteReq("/users/:id")
  Future<void> deleteUser(String id);

  @GetReq("/users")
  Future<List<User>> all({String name, String email});
}

Generating the ApiClient implementation

Use build_runner to generate ApiClient implementation for specification:

pub run build_runner build

Use it

Use the ApiClient to fetch data from the server:

  var api = UserApi(base: route("http://localhost:10000"), serializers: repo);
  User user5 = await api
        .createUser(User(id: '5', name: 'five', email: '[email protected]'));
Clone this wiki locally