Retrofit API calling in flutter

Updated 15 December 2023

Save
Retrofit API calling in flutter

In the mobile app development lifecycle, communicating with the server(via API) to fetch or store data is one of the basic needs.

So, in today’s blog let’s check Retrofit API calling in a flutter.

I hope you’re all familiar with Android/iOS, and you’ve even heard of Retrofit and Alamofire.

Check out more about our Flutter app development.

We use network calls in almost every app, and they’ve become an integral part of app functioning.

To call Rest APIs by sending dynamic headers, parameters, print requests, and responses in a more custom and secure way “Retrofit” is the best solution.

Let’s start the steps for Retrofit API calling in a flutter

Step 1: Create a flutter project.

Step 2: Add the below dependencies in pubspec.yaml file

Now, run the command “flutter pub get” to download the dependencies.

Step 3:  Now, let’s create an abstract API request class.

Right now, you will observe some errors in the file in “part ‘api_client.g.dart’ ” and _ApiClient.

We need to run a command and generate an “api_client.g.dart” file.

Step 4: Now run the command in the terminal

flutter pub run build_runner build

The above command will generate the api_client.g.dart file & contains all data about creating Retrofit instance and fetching data from the network.

You should never modify the code in api_client.g.dart file by hand.

If you made any changes in ApiClient then also run the command to update part file.

Step 5: Now, create a model class to store the API data.

Step 6: Then, call the get method from your main.dart class.

Please find below the complete code for main.dart class.

Finally, you can run the code, and see the below results.

Retrofit API calling

For more details and methods you can refer to the doc here.

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

Hope this blog helped you for a better understanding of Retrofit API calling in Flutter.

Thanks for reading 🙂

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