Flutter retrofit network call implementation

 

Flutter retrofit :

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 :

This image below depicts the project structure of flutter retrofit implementation.

flutter retrofit

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 :

Go through the below tutorial implementation for more details on flutter retrofit call.

 

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 are displaying a Circular Progress Bar until the data is loaded on to 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 listview from the data fetch from 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,
      ),
    ],

  ),
),

 

Providing the full source code for the flutter retrofit implementation.

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 depicts flutter retrofit implementation

flutter retrofit

If you have any queries on flutter retrofit implementation tutorial let us know in comment section below. If you like this tutorial do like and share for more important updates coming up.

Show Buttons
Hide Buttons
Read previous post:
Flutter custom alert box | custom alertbox

  Flutter custom alert box : Flutter custom alert box is the new way to customize the way a alert...

Close