X
    Categories: Flutter

Flutter retrofit POST request method tutorial for beginners

Flutter Retrofit Post :

Flutter retrofit post request method is used to pass a values to the api and fetch the appropriate data based on the value posted.

For example when you try to fetch the details of a student you can send a student ID to the api and the data related to that particular student is fetched in response to the query made.

Annotations are used to specify how a request is handled and they are specified on interface methods.

We can pass the key values according to the API, based on this key the data is filtered and provided as response as in json or xml format.

Retrofit is considered as the fastest network call and also the interface is easy to use by just providing annotations such as POST, GET… in flutter retrofit post.

 

Flutter Retrofit Post Video Tutorial :

Go through the below tutorial for details on retrofit post implementation.

 

Project Structure :

This image illustrates the project structure for the implementation of Flutter Retrofit POST.

 

pubspec.yaml :

Add dependency’s retrofit and json_annotation and provide the version according to the latest version available.

dependencies:
  flutter:
    sdk: flutter
  retrofit: any
  json_annotation: any

 

In dev_dependency’s add retrofit_generator and build_runner

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

 

post_api.dart :

We are providing the model class where the parameters like name and age is specified.Also we need to specify the base URL.

We have provided the base URL json generator, using the POST parameter we are posting the num by using which we are fetching details based on the posted number.

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/cffBLmFKeW?")
abstract class RestClient {
  factory RestClient(Dio dio) = _RestClient;
  @POST("/indent={num}")
  Future<Post> getTasks(int num);
}

@JsonSerializable()
class Post{
  String name;
  int age;


  Post({this.name, this.age});

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




 

post_api.g.dart :

With the declaration of the above model class we have generated the below file.Provided the detailed explanation in video tutorial provided.

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'post_api.dart';

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


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

Map<String, dynamic> _$PostToJson(Post instance) => <String, dynamic>{
  'name': instance.name,
  'age': instance.age
};
class _RestClient implements RestClient {
  _RestClient(this._dio, {this.baseUrl}) {
    ArgumentError.checkNotNull(_dio, '_dio');
    this.baseUrl ??= 'http://www.json-generator.com/api/json/get/cffBLmFKeW?';
  }

  final Dio _dio;

  String baseUrl;

  @override
  getTasks(num) async {
    ArgumentError.checkNotNull(num, 'num');
    const _extra = <String, dynamic>{};
    final queryParameters = <String, dynamic>{};
    final _data = <String, dynamic>{};
    final Response<Map<String, dynamic>> _result = await _dio.request(
        '/indent={num}',
        queryParameters: queryParameters,
        options: RequestOptions(
            method: 'POST',
            headers: <String, dynamic>{},
            extra: _extra,
            baseUrl: baseUrl),
        data: _data);
    final value = Post.fromJson(_result.data);
    return value;
  }
}

 

 

main.dart :

Providing the full code for retrofit post integration where we display a progress bar and load the data.We have provided the body and post sections.

When you tap on the button number is passed as the key value pair to the api and result is fetched using flutter retrofit post.

 

Flutter Retrofit Post Full Code :

Explore complete code for the implementation of Retrofit POST requests.

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {


  bool pressed = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Retrofit Post Call"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[


            RaisedButton(child: Text("Fetch Post"),
                onPressed: () => {setState(() {
                  pressed = true;
                  //fetchData(postNum);
                })}),
            
            Padding(padding: EdgeInsets.all(30)),

            pressed ? _buildBody(context): SizedBox(),

          ],
        ),
      ),
    );
  }
}

FutureBuilder<Post> _buildBody(BuildContext context) {
  final client = RestClient(Dio(BaseOptions(contentType: "application/json")));
  return FutureBuilder<Post>(
    future: client.getTasks(2),
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.done) {
        final Post posts = snapshot.data;
        return _buildPosts(context, posts);
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    },
  );
}

Widget _buildPosts(BuildContext context, Post posts) {
  return Center(
    child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[

          Text("Name : "+posts.name,style: TextStyle(fontSize: 30),),
          Text("Age : "+posts.age.toString(),style: TextStyle(fontSize: 30),),
        ],
      ),
  );

}

 

Output :

This screen showcases the implementation of the flutter  POST request method.

If you have any questions about this Flutter Retrofit tutorial, feel free to ask in the comments below. Don’t forget to like and share for more engaging tutorials and updates.

abhishek:
Related Post

This website uses cookies.