X

Flutter retrofit network call implementation

 

Flutter retrofit :

Flutter Retrofit is a powerful combination for efficient network requests and API integration in Flutter applications. Leveraging Retrofit, a robust HTTP client library, enhances the capability to seamlessly communicate with APIs and handle data effortlessly.

This integration empowers Flutter developers to streamline the networking aspect of their projects, resulting in cleaner code and improved application performance.

With Flutter Retrofit, implementing RESTful services becomes intuitive, allowing developers to focus on crafting feature-rich and responsive applications. Explore the potential of Flutter Retrofit to accelerate your app development and elevate the user experience.

Flutter retrofit implementation for populating a listview is from a api, we use network call in almost every application they are now a crucial part of app functioning.

Network call plays a vital role not only in app communication with server for user transactions but also to know the app status like analytics, usage, thereby providing the better services to the end-users.

Flutter retrofit makes it much easier to implement the network calls in flutter app also it is quite faster compared to other libraries in terms of dealing with network calls.

In this tutorial we will be using flutter retrofit library and fetch the data from api and try to populate it on to the screen in the form of a listview.

 

Project Structure :

The image below illustrates the project structure of the Retrofit implementation.

pubspec.yaml

Add retrofit and json annotation under dependencies and try to provide the latest version of dependency to avoid code level issues.

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.3
  retrofit: any
  json_annotation: any

 

Add retrofit_generator and build_runner under dev_dependencies

dev_dependencies:
  flutter_test:
    sdk: flutter
  retrofit_generator: any
  build_runner: any

 

Flutter retrofit video tutorial :

Explore the tutorial implementation below for in-depth insights into Retrofit calls

 

post_api.dart :

We are fetching data from api through the Get method

baseUrl: "http://www.json-generator.com/api/json/get/"

through GET method

@GET("/ceLGCumWjS?indent=2")

 

abstract class RestClient {
  factory RestClient(Dio dio) = _RestClient;
  @GET("/ceLGCumWjS?indent=2")
  Future<List<Post>> getTasks();
}

 

declare the parameters we use

class Post{
  int index;
  String name;
  String picture;
  String gender;
  int age;
  String email;
  String phone;
  String company;
}

 

import 'package:json_annotation/json_annotation.dart';
import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';

part 'post_api.g.dart';

@RestApi(baseUrl: "http://www.json-generator.com/api/json/get/")
abstract class RestClient {
  factory RestClient(Dio dio) = _RestClient;
  @GET("/ceLGCumWjS?indent=2")
  Future<List<Post>> getTasks();
}

@JsonSerializable()
class Post{
  int index;
  String name;
  String picture;
  String gender;
  int age;
  String email;
  String phone;
  String company;

  Post({this.index, this.name, this.picture, this.gender, this.age, this.email, this.phone, this.company});

  factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);
  Map<String, dynamic> toJson() => _$PostToJson(this);
}

 

post_api.g.dart

We have generated the below file using retrofit_generator using terminal command.The fields which we have declared in post_api.dart is used to generate the below file.

Using this file we can make use of the data throughout the app, which we fetch from api using the respective fields.

dart :

pub run build_runner build

 

flutter :

flutter pub run build_runner build

 

 

Post from json

Post _$PostFromJson(Map<String, dynamic> json) {
  return Post(
      index: json['index'] as int,
      name: json['name'] as String,
      picture: json['picture'] as String,
      gender: json['gender'] as String,
      age: json['age'] as int,
      email: json['email'] as String,
      phone: json['phone'] as String,
      company: json['company'] as String
  );
}

 

Post To Json

Map<String, dynamic> _$PostToJson(Post instance) => <String, dynamic>{
  'index': instance.index,
  'name': instance.name,
  'picture': instance.picture,
  'gender': instance.gender,
  'age': instance.age,
  'email': instance.email,
  'phone': instance.phone,
  'company': instance.company
};

 

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'post_api.dart';

// **************************************************************************
// RetrofitGenerator
// **************************************************************************


Post _$PostFromJson(Map<String, dynamic> json) {
  return Post(
      index: json['index'] as int,
      name: json['name'] as String,
      picture: json['picture'] as String,
      gender: json['gender'] as String,
      age: json['age'] as int,
      email: json['email'] as String,
      phone: json['phone'] as String,
      company: json['company'] as String
  );
}

Map<String, dynamic> _$PostToJson(Post instance) => <String, dynamic>{
  'index': instance.index,
  'name': instance.name,
  'picture': instance.picture,
  'gender': instance.gender,
  'age': instance.age,
  'email': instance.email,
  'phone': instance.phone,
  'company': instance.company
};

class _RestClient implements RestClient {
  _RestClient(this._dio, {this.baseUrl}) {
    ArgumentError.checkNotNull(_dio, '_dio');
    this.baseUrl ??= 'http://www.json-generator.com/api/json/get/';
  }

  final Dio _dio;

  String baseUrl;

  @override
  getTasks() async {
    const _extra = <String, dynamic>{};
    final queryParameters = <String, dynamic>{};
    final _data = <String, dynamic>{};
    final Response<List<dynamic>> _result = await _dio.request('/ceLGCumWjS?indent=2',
        queryParameters: queryParameters,
        options: RequestOptions(
            method: 'GET',
            headers: <String, dynamic>{},
            extra: _extra,
            baseUrl: baseUrl),
        data: _data);
    var value = _result.data
        .map((dynamic i) => Post.fromJson(i as Map<String, dynamic>))
        .toList();
    return Future.value(value);
  }
}

 

main.dart

We showcase a Circular Progress Bar while the data is being loaded onto the fields of a ListView.

FutureBuilder<List<Post>> _buildBody(BuildContext context) {
  final client = RestClient(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(),
        );
      }
    },
  );
}

 

Populating a ListView with data retrieved from an API

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,
      ),
    ],

  ),
),

 

Offering the complete source code for the implementation of Retrofit.

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 = RestClient(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,
                ),
              ],

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


 

Flutter retrofit output :

This screen showcases the implementation of flutter Retrofit

If you have any questions about the implementation of Retrofit tutorial, feel free to drop them in the comments section below. If you found this tutorial helpful, please give it a thumbs up and share it to stay informed about upcoming important updates

abhishek:
Related Post

This website uses cookies.