Fetching Data Made Easy : Using Retrofit In Flutter

Mario Gunawan
Flutter Tips
Published in
2 min readOct 19, 2022

Json-Binding become a piece of cake

This article will show you a glimpse of what retrofit is, and tell you how to build an app with retrofit

Why?

There are two popular packages for fetching data in flutter, the http package which is used in flutter fetching data tutorial, and there is retrofit, a http client inspired by its android/java counterpart.

At first, to familiarize yourself to flutter, you can use http as it is simpler than retrofit. But if you want a cleaner code, I recommend using retrofit even though it is more complex.

Retrofit offers you cleaner code with the expense of more codes to write and bigger application bundle size, because it needs a lot of dependencies.

Now that you know about retrofit, Let’s try retrofit!

Add this to your pubspec.yaml

dependencies:
retrofit: '>=3.0.0 <4.0.0'
logger: any #for logging purpose

dev_dependencies:
retrofit_generator: '>=4.0.0 <5.0.0'
build_runner: '>2.3.0 <4.0.0'
json_serializable: '>4.4.0'

Create fetch_album.dart file then add this code

import 'package:retrofit/retrofit.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:dio/dio.dart';
part 'fetch_album.g.dart'; // #1@JsonSerializable() // #2
class Album {
String userId;
int id;
String title;

Album({ required this.userId, required this.id, required this.title });
factory Album.fromJson(Map<String, dynamic> json) => _$AlbumFromJson(json); // #3 Map<String, dynamic> toJson() => _$AlbumToJson(this); // #4
}
@RestApi(baseUrl: 'https://jsonplaceholder.typicode.com') // #5
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
@GET("/albums/{albumId}") // #6
Future<Album> getAlbum(@Path() int albumId);
}

Then run flutter pub run build_runner build . This will generate a generated dart file for you (fetch_album.g.dart).

Now you can use this album fetcher everywhere! Example usage:

Future<Album> futureAlbum = RestClient(Dio(BaseOptions(contentType: "application/json"))).getAlbum(1); // #7

Further explanation:

#1 : you need to include this part so that you can get access to the generated file
#2 : line that will generate #3 and #4. You can also add more json utility to the generated class, like converting snake_case from server to camelCase, read more here.
#5 : give the baseUrl and tells build runner to generate an implementation class called _RestClient
#6 : method and routes to API call
#7 : Quoted from its pub, Dio is "A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc."

I’m just covering the surface here. To get most out of this library, go to retrofit documentation.

--

--

Mario Gunawan
Flutter Tips

I'm a passionate mobile / web developer. Writing articles about software development, mainly about flutter and react.