How to integrate REST API in Flutter

Overview

FLUTTER REST API

How to integrate REST API in Flutter

Introduction:

In this article we will learn how to integrate REST API in flutter app. As we know that now a days almost all the app uses remote data using APIs. This article will be the crucial part for any developer who wants to make their future in flutter. So let’s understand step by step how to integrate rest api in flutter.

We are using http plugin for call REST API from the app. http will provide get, post, put, read etc method for send and receive data from remote locations.

We have used dummy sample for rest api REST API Sample URL for this article. You can use your project API.

Output:

List of Employees Add New Employee

Plugin Required: http: ^0.12.0+2

Programming Steps:

  1. First and basic step to create new application in flutter. If you are a beginner in flutter then you can check my blog Create a first app in Flutter. I have created app named as “flutter_rest_api”

  2. Open the pubspec.yaml file in your project and add the following dependencies into it.

dependencies:
 flutter:
   sdk: flutter
 cupertino_icons: ^0.1.2
 http: ^0.12.0+2
  1. Create new file named as “rest_api.dart” for configure rest api url and functions for send and receive data. Following is the programming implementation for rest api in app.
addEmployee(body) async { // BODY // { // "name": "test", // "age": "23" // } final response = await http.post('${URLS.BASE_URL}/create', body: body); if (response.statusCode == 200) { return true; } else { return false; } } }">
import 'dart:convert';
 
import 'package:http/http.dart' as http;
 
class URLS {
 static const String BASE_URL = 'http://dummy.restapiexample.com/api/v1';
}
 
class ApiService {
 static Future
   
    
     > getEmployees() async {
   // RESPONSE JSON :
   // [{
   //   "id": "1",
   //   "employee_name": "",
   //   "employee_salary": "0",
   //   "employee_age": "0",
   //   "profile_image": ""
   // }]
   final response = await http.get('${URLS.BASE_URL}/employees');
   if (response.statusCode == 200) {
     return json.decode(response.body);
   } else {
     return null;
   }
 }
 
 static Future
     
       addEmployee(body) async {
   // BODY
   // {
   //   "name": "test",
   //   "age": "23"
   // }
   final response = await http.post('${URLS.BASE_URL}/create', body: body);
   if (response.statusCode == 200) {
     return true;
   } else {
     return false;
   }
 }
}

     
    
   
  1. Now, we will consume rest api methods in our app. We have created a widget to display all the employee list. Open main.dart and implement following code.
import 'package:flutter/material.dart';
import 'package:flutter_rest_api/rest_api.dart';
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     theme: ThemeData(
       primarySwatch: Colors.purple,
     ),
     home: EmployeePage(),
   );
 }
}
 
class EmployeePage extends StatefulWidget {
 @override
 _EmployeePageState createState() => _EmployeePageState();
}
 
class _EmployeePageState extends State
   
     {
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: Text('Flutter REST API'),
     ),
     body: FutureBuilder(
       future: ApiService.getEmployees(),
       builder: (context, snapshot) {
         final employees = snapshot.data;
         if (snapshot.connectionState == ConnectionState.done) {
           return ListView.separated(
             separatorBuilder: (context, index) {
               return Divider(
                 height: 2,
                 color: Colors.black,
               );
             },
             itemBuilder: (context, index) {
               return ListTile(
                 title: Text(employees[index]['employee_name']),
                 subtitle: Text('Age: ${employees[index]['employee_age']}'),
               );
             },
             itemCount: employees.length,
           );
         }
         return Center(
           child: CircularProgressIndicator(),
         );
       },
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: () {
         Navigator.push(
           context,
           MaterialPageRoute(
             builder: (context) => AddNewEmployeePage(),
           ),
         );
       },
       tooltip: 'Increment',
       child: Icon(Icons.add),
     ),
   );
 }
}

   
  1. To add new employee we have created another page called AddNewEmployeePage Which will add new employee in the list. Following is the implementation for that I have created widget in main.dart file.
AlertDialog( title: Text('Employee has been added!!!'), actions: [ FlatButton( onPressed: () { Navigator.pop(context); _employeeNameController.text = ''; _employeeAge.text = ''; }, child: Text('OK'), ) ], ), context: context, ); return; }else{ showDialog( builder: (context) => AlertDialog( title: Text('Error Adding Employee!!!'), actions: [ FlatButton( onPressed: () { Navigator.pop(context); }, child: Text('OK'), ) ], ), context: context, ); return; } }); }, ) ], ), ), ), ); } }">
class AddNewEmployeePage extends StatefulWidget {
 AddNewEmployeePage({Key key}) : super(key: key);
 
 _AddNewEmployeePageState createState() => _AddNewEmployeePageState();
}
 
class _AddNewEmployeePageState extends State
     
       {
 final _employeeNameController = TextEditingController();
 final _employeeAge = TextEditingController();
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: Text('New Employee'),
     ),
     body: Center(
       child: Padding(
         padding: EdgeInsets.all(10),
         child: Column(
           children: 
      
       [
             TextField(
               controller: _employeeNameController,
               decoration: InputDecoration(hintText: 'Employee Name'),
             ),
             TextField(
               controller: _employeeAge,
               decoration: InputDecoration(hintText: 'Employee Age'),
               keyboardType: TextInputType.number,
             ),
             RaisedButton(
               child: Text(
                 'SAVE',
                 style: TextStyle(
                   color: Colors.white,
                 ),
               ),
               color: Colors.purple,
               onPressed: () {
                 final body = {
                   "name": _employeeNameController.text,
                   "age": _employeeAge.text,
                 };
                 ApiService.addEmployee(body).then((success) {
                   if (success) {
                     showDialog(
                       builder: (context) => AlertDialog(
                         title: Text('Employee has been added!!!'),
                         actions: 
       
        [
                           FlatButton(
                             onPressed: () {
                               Navigator.pop(context);
                               _employeeNameController.text = '';
                               _employeeAge.text = '';
                             },
                             child: Text('OK'),
                           )
                         ],
                       ),
                       context: context,
                     );
                     return;
                   }else{
                     showDialog(
                       builder: (context) => AlertDialog(
                         title: Text('Error Adding Employee!!!'),
                         actions: 
        
         [
                           FlatButton(
                             onPressed: () {
                               Navigator.pop(context);
                             },
                             child: Text('OK'),
                           )
                         ],
                       ),
                       context: context,
                     );
                     return;
                   }
                 });
               },
             )
           ],
         ),
       ),
     ),
   );
 }
}

        
       
      
     
  1. Great, you are done with flutter rest api integration. Run this project in device or emulator and check the output. Conclusion: In this article we have learned how to implement rest api in flutter. We have used and get and post method of http plugin.

Git: https://github.com/myvsparth/flutter_rest_api

Related Tags: Flutter, REST API, Android, iOS

You might also like...

With ML Kit's face detection API, you can detect faces in an camera or image, Note that the API detects faces, it does not recognize people

With ML Kit's face detection API, you can detect faces in an camera or image, Note that the API detects faces, it does not recognize people

Face Detection This project is a starting point for a Flutter application. Getting Started For help getting started with Flutter, view our online docu

Dec 29, 2022

Weather-App-Api- - Simple Realtime Weather App With Api

Weather-App-Api- - Simple Realtime Weather App With Api

music_app A new Flutter Weather App project. Getting Started // اول حاجه تعمل en

Nov 11, 2022

News App created in Flutter using News API for fetching realtime data and Firebase as the backend and authenticator.

News App created in Flutter using News API for fetching realtime data and Firebase as the backend and authenticator.

News Buzz News App created in Flutter using News API for fetching realtime data and Firebase as the backend and authenticator. Features Custom news fe

Dec 30, 2022

GetDoctor is a complete app developed in Flutter, Firebase and Blazor,.Net Core API and SQL Server

GetDoctor is a complete app developed in Flutter, Firebase and Blazor,.Net Core API and SQL Server

GetDoctor 😊 😊 😊 GetDoctor is a complete app developed in Flutter, Firebase and Blazor,DotNet Core API and SQL Server GetDoctor is a complete packag

Dec 19, 2022

Flutter sample app using MLKit Vision API for text recognition

Flutter sample app using MLKit Vision API for text recognition

Flutter ML Kit Vision This a sample Flutter app integrated with the ML Kit Vision API for recognition of email addresses from an image. NOTE: The ML K

Oct 12, 2022

An android app built using flutter that displays and forecast the specific city Weather and Climate for dynamic time event by collecting the data from API that is provided for free by OPENWEATHER site.

clima_weather_reporter A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get y

Feb 3, 2022

P2P payment solution using Stream's Flutter SDK and Rapyd's Wallet API

P2P payment solution using Stream's Flutter SDK and Rapyd's Wallet API

Peer-to-peer payment integration to a messaging app using Flutter 💰 This project shows how to integrate a peer-to-peer payment solution to your Strea

Dec 8, 2022

Movies App made in Flutter with api data from TMDB

 Movies App made in Flutter with api data from TMDB

This is an app that displays you details of movies that you can search for , or browse.

Dec 29, 2022

WallHalla is a wallpapers apps made with flutter and unsplash.com API

WallHalla is a wallpapers apps made with flutter and unsplash.com API

WallHalla is a wallpapers apps made with flutter and unsplash.com API

Dec 22, 2022
Owner
Hoàng Phong
Hoàng Phong
Simple and modern news app that incorporates REST API (newsapi.org), all built entirely with Flutter.

A simple news app with a minimalistic and clean UI that incorporates the newsapi.org api all built entirely with Flutter. Be sure to leave a star ??

Carlton Aikins 73 Dec 1, 2022
A simple app to demonstrate a testable, maintainable, and scalable architecture for flutter. flutter_bloc, hive, and REST API are some of the tech stacks used in this project.

last_fm A simple app to demonstrate a testable, maintainable, and scalable architecture for flutter. flutter_bloc, hive, and REST API are some of the

Elias Andualem 140 Dec 31, 2022
Rest API Movie Application built using Flutter and Riverpod

Flickd Flutter Application Flickd Movie Application Flutter Flutter allows you to build beautiful native apps on iOS and Android Platforms from a sing

null 20 Dec 5, 2022
Flutter apple music preview - A Music App that leverages the iTunes Rest API to get music data and playable music trailers

Apple Music Preview App Description This project is a Music App that leverages t

Willy Adinata Saragih 2 May 23, 2022
DChisel is simple Dart Framework for creating REST API

DChisel Dart Framework DChisel is simple Dart Framework for creating REST API Features Custom host server and port GET, POST, PUT, DELETE, PATCH Route

M Nasrul Alawy 23 Jan 6, 2023
Weather App for cities using Rest API

Clima, A City Weather mobile app Clima is a Weather App for cities which makes use of Powerful Flutter Platform to run on both Android and iOS devices

Zain Basharat Ali 4 Nov 29, 2022
In this video, we learn how to do integrate Google Admob with Flutter with latest Flutter 2.0 Google Admob Package.

?? Monetizing Flutter apps with Google AdMob ?? In this video, we learn how to do integrate Google Admob with Flutter with latest Flutter 2.0 Google A

SnippetCoder 14 Nov 30, 2022
Integrate Razorpay payment gateway flutter in just 15 minutes

How to Integrate Flutter Payments with Razorpay Payment Gateway Learn how to integrate payment gateway with Razorpay in less than 15 minutes, other ti

Sanskar Tiwari 25 Nov 25, 2022
News Headline app is build in Flutter MVVM and REST Apis for News is used in this app.

About The Project Flutter MVVM project for News Headlines. REST Api for News is used in this project. App Demo Api for News Get free api from here : h

Aizaz ahmad 3 Aug 16, 2022
Dart HTTP server framework for building REST APIs. Includes PostgreSQL ORM and OAuth2 provider.

Aqueduct is a modern Dart HTTP server framework. The framework is composed of libraries for handling and routing HTTP requests, object-relational mapp

Stable Kernel 2.4k Jan 5, 2023