retrofit in Flutter

Jan 16, 2022 flutter

How can we use retrofit in Flutter ?

Welcome to Lead by code .Today we are going to learn abut how to use retrofit in flutter. In retrofit Flutter we need to add the dependency in to the project.

Today we will use retrofit flutter to call the api’s from the service. Most of the native developer are well known with Alamofire in iOS and retrofit in Android . In Flutter we can use retrofit to fetch the API’s from the network service and convert it into JSon.

For most of App we use REST service call which has GET,POST, Pull and delete service in it. WE can call this services using flutter retrofit Api call.

Retrofit generator Flutter

In this tutorial we are going to study about following categories for retrofit in Flutter

  • Api service Call
  • Parse Json
  • Convert Json to Model

Lets Start with the integration of retrofit api in flutter

Step1: We need to Add the dependency in the pubspec.yaml file

dependencies:
retrofit: ^1.3.4+1
built_value: ^7.1.0
<span class="hljs-attr">logger:</span> <span class="hljs-string">any</span> <span class="hljs-comment">#for logging purpose</span>

dev_dependencies:
retrofit_generator: ^1.3.7+5
build_runner: ^1.10.0
built_value_generator: ^7.1.0

As we add the above dependency code in the pubspec.yaml file . We need to run the command flutter pub get to download the dependency. We need to add the retrofit generator

Step 2: Create a Api class were we need to declare the retrofit Api call .create a file apicall.g.dart and save it

We need to import the retrofit package to call the retrofit in Flutter

add the following code

import 'package:dio/dio.dart';
import 'package:flutter_app/Model/User.dart';
import 'package:retrofit/http.dart';
part 'apicall.g.dart';

baseURL: "http://www.leadbycode.com/"

@RestApi(baseUrl:baseURL)

For GET Request

abstract class ApiCall {
  factory ApiCall(Dio dio, {String baseUrl}) = _ApiCall;

 @GET('todos/')
  Future<List<User>> getUsers();
}

For Post Request

abstract class ApiCall {
  factory ApiCall(Dio dio, {String baseUrl}) = _ApiCall;
@POST('user/v1/login')                                         //Userlogin
Future<Response> getLogin([
  @Header("DeviceID") String deviceId,
  @Header("AuthorizedToken") String authenticationKey,
  @Header("AppVersion") String appversion,
  @QueryMap() Map<String, String> parameter,
]);
}

This class is base class for the service call. in above we will error of ApiCall variable. So we need to run flutter pub run build_runner build command.

Step 3: We need to create a Model class of the json which we will get in the form of json from service Api call

import 'package:json_annotation/json_annotation.dart';
part 'model.g.dart';
@JsonSerializable()
class User{
  late  int id;
  late String name;

  User({required this.id, required this.name});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

So create a class named model.g.dart file and we can add following dart model in it .

Step 4: Now in main.dart file we can add the following code to call the flutter retrofit api call in the main file

Code for retrofit in Flutter app code

  FutureBuilder<List<User>> _buildBody(BuildContext context) {
    final client = ApiCall(Dio(BaseOptions(contentType: "application/json")));
    return FutureBuilder<List<User>>(

      future: client.getUsers(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          final List<User> posts = snapshot.data;
          return _buildPosts(context, posts);
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

Step 5 : We will get the final code in main.dart file

import 'package:flutter/material.dart';
import 'package:flutter_retrofit/post_api.dart';
import 'post_api.dart';
import 'package:dio/dio.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget{
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Retrofit',
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue[300],
          centerTitle: true,
          title: Text(
            'Flutter Retrofit',
            style: TextStyle(
                fontSize: 25, color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
        body: _buildBody(context),
      ),
    );
  }


  FutureBuilder<List<Post>> _buildBody(BuildContext context) {
    final client = ApiCall(Dio(BaseOptions(contentType: "application/json")));
    return FutureBuilder<List<Post>>(

      future: client.getTasks(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          final List<Post> posts = snapshot.data;
          return _buildPosts(context, posts);
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  ListView _buildPosts(BuildContext context, List<Post> posts) {
    return ListView.builder(
      itemCount: posts.length,
      padding: EdgeInsets.all(8),
      itemBuilder: (context, index) {
        return Card(
          elevation: 4,
          child: ListTile(
            title: Text(
              posts[index].name,
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            subtitle: Text(posts[index].email),
            leading: Column(
              children: <Widget>[
                Image.network(posts[index].picture,width: 50,height: 50,
                ),
              ],

            ),
          ),
        );
      },
    );
  }
}

Thus using retrofit in Flutter we can call the Service api’s in the app

Index