Integrating Retrofit in Flutter

Updated 26 December 2023

Save

Flutter retrofit

We are going to learn that how can we use the Retrofit networking library in our Flutter projects, It might be possible for you to hear about retrofit if your background is Android app development.
Don’t worry 🙂  if your background is not Android development we will cover this blog with basic in easy language.

Read about the variety of Flutter App Development Services offered by Mobikul

What is Retrofit?

Retrofit is a networking library that is used to call the API to fetch or post the data to the server, It is the most liked network library because a lot of work is done by itself as JSON data parse into models, easy make GET, POST, PUT, etc requests by using awesome annotations.

How does Retrofit work in Flutter?

In brief, Retrofit creates .g.dart classes from annotation at compile time which has all the logic behind the annotations like JSON parsing into models, etc. It will clear when you see the examples below. 

Retrofit Integration in Flutter

Let’s start Retrofit integration in Flutter, First of all, we have to add Retrofit dependencies to include its lib classes in our project.

pubspec.yaml

Here, we are using retrofit dependency along with helper dependencies like dio, logger, build_runner, retrofit_generator, and json_serializable

Let’s take an example to understand Retrofit

First, create an abstract class where your all API request method will be declared.

APIClient.dart

From where you call these request methods.

RepoClass.dart

SplashResponse.dart

Same as SplashResponse.dart you can create LoginResponse.dart class as per your response.

Run this command on the terminal, Please make sure you are targeting the correct project dir path in the terminal.

Description :

Here, we created APIClient class where we declare our request method to get the splash data and post the login data. The Repo class where we call these methods and use async and await because the request method returns the Future type model which will get the data when the API response gets any response from the server.

flutter pub run build_runner build -> After this command, the respective .g.dart class automatically generated for logic to parse splash data response which will come in JSON format convert into SplashResponse model (Internally .g.dart are using the toJson() and fromJson() methods to achieve this), etc.

For more interesting blogs check out here – https://mobikul.com/blog/

Happy Coding <:)…/>

I hope this blog will help you to integrate Retrofit in Flutter, For any query comment down!

Thank you

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home