Flutter REST API

Introduction

 
In this article, we will learn how to integrate REST API in a Flutter app. As we know that nowadays, almost all the apps use remote data using APIs, this article will be a 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 an HTTP plugin for calling REST API from the app. HTTP will provide get, post, put, and read methods to send and receive data from remote locations.
 
We have used dummy REST API Sample URL for this article. You can use your project API.
 

Output

 
Flutter REST APIFlutter REST API
 
Step 1
 
The first and most basic step is to create a 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 an app named as “flutter_rest_api”.
 
Step 2
 
Open the pubspec.yaml file in your project and add the following dependencies into it.
  1. dependencies:  
  2.  flutter:  
  3.    sdk: flutter  
  4.  cupertino_icons: ^0.1.2  
  5.  http: ^0.12.0+2  
Step 3
 
Create a new file named as “rest_api.dart” for configuring the REST API URL and functions for sending and receiving the data. Following is the programming implementation for REST API in the app.
  1. import 'dart:convert';  
  2.    
  3. import 'package:http/http.dart' as http;  
  4.    
  5. class URLS {  
  6.  static const String BASE_URL = 'http://dummy.restapiexample.com/api/v1';  
  7. }  
  8.    
  9. class ApiService {  
  10.  static Future<List<dynamic>> getEmployees() async {  
  11.    // RESPONSE JSON :  
  12.    // [{  
  13.    //   "id": "1",  
  14.    //   "employee_name": "",  
  15.    //   "employee_salary": "0",  
  16.    //   "employee_age": "0",  
  17.    //   "profile_image": ""  
  18.    // }]  
  19.    final response = await http.get('${URLS.BASE_URL}/employees');  
  20.    if (response.statusCode == 200) {  
  21.      return json.decode(response.body);  
  22.    } else {  
  23.      return null;  
  24.    }  
  25.  }  
  26.    
  27.  static Future<bool> addEmployee(body) async {  
  28.    // BODY  
  29.    // {  
  30.    //   "name": "test",  
  31.    //   "age": "23"  
  32.    // }  
  33.    final response = await http.post('${URLS.BASE_URL}/create', body: body);  
  34.    if (response.statusCode == 200) {  
  35.      return true;  
  36.    } else {  
  37.      return false;  
  38.    }  
  39.  }  
  40. }  
Step 4
 
Now, we will consume the REST API methods in our app. We have created a widget to display all the employees' list. Open main.dart and implement the following code.
  1. import 'package:flutter/material.dart';  
  2. import 'package:flutter_rest_api/rest_api.dart';  
  3.    
  4. void main() => runApp(MyApp());  
  5.    
  6. class MyApp extends StatelessWidget {  
  7.  @override  
  8.  Widget build(BuildContext context) {  
  9.    return MaterialApp(  
  10.      theme: ThemeData(  
  11.        primarySwatch: Colors.purple,  
  12.      ),  
  13.      home: EmployeePage(),  
  14.    );  
  15.  }  
  16. }  
  17.    
  18. class EmployeePage extends StatefulWidget {  
  19.  @override  
  20.  _EmployeePageState createState() => _EmployeePageState();  
  21. }  
  22.    
  23. class _EmployeePageState extends State<EmployeePage> {  
  24.  @override  
  25.  Widget build(BuildContext context) {  
  26.    return Scaffold(  
  27.      appBar: AppBar(  
  28.        title: Text('Flutter REST API'),  
  29.      ),  
  30.      body: FutureBuilder(  
  31.        future: ApiService.getEmployees(),  
  32.        builder: (context, snapshot) {  
  33.          final employees = snapshot.data;  
  34.          if (snapshot.connectionState == ConnectionState.done) {  
  35.            return ListView.separated(  
  36.              separatorBuilder: (context, index) {  
  37.                return Divider(  
  38.                  height: 2,  
  39.                  color: Colors.black,  
  40.                );  
  41.              },  
  42.              itemBuilder: (context, index) {  
  43.                return ListTile(  
  44.                  title: Text(employees[index]['employee_name']),  
  45.                  subtitle: Text('Age: ${employees[index]['employee_age']}'),  
  46.                );  
  47.              },  
  48.              itemCount: employees.length,  
  49.            );  
  50.          }  
  51.          return Center(  
  52.            child: CircularProgressIndicator(),  
  53.          );  
  54.        },  
  55.      ),  
  56.      floatingActionButton: FloatingActionButton(  
  57.        onPressed: () {  
  58.          Navigator.push(  
  59.            context,  
  60.            MaterialPageRoute(  
  61.              builder: (context) => AddNewEmployeePage(),  
  62.            ),  
  63.          );  
  64.        },  
  65.        tooltip: 'Increment',  
  66.        child: Icon(Icons.add),  
  67.      ),  
  68.    );  
  69.  }  
  70. }  
Step 5
 
To add a new employee, we have created another page called AddNewEmployeePage, which will add a new employee to the list. Following is the implementation; for that I have created a widget in main.dart file.
  1. class AddNewEmployeePage extends StatefulWidget {  
  2.  AddNewEmployeePage({Key key}) : super(key: key);  
  3.    
  4.  _AddNewEmployeePageState createState() => _AddNewEmployeePageState();  
  5. }  
  6.    
  7. class _AddNewEmployeePageState extends State<AddNewEmployeePage> {  
  8.  final _employeeNameController = TextEditingController();  
  9.  final _employeeAge = TextEditingController();  
  10.  @override  
  11.  Widget build(BuildContext context) {  
  12.    return Scaffold(  
  13.      appBar: AppBar(  
  14.        title: Text('New Employee'),  
  15.      ),  
  16.      body: Center(  
  17.        child: Padding(  
  18.          padding: EdgeInsets.all(10),  
  19.          child: Column(  
  20.            children: <Widget>[  
  21.              TextField(  
  22.                controller: _employeeNameController,  
  23.                decoration: InputDecoration(hintText: 'Employee Name'),  
  24.              ),  
  25.              TextField(  
  26.                controller: _employeeAge,  
  27.                decoration: InputDecoration(hintText: 'Employee Age'),  
  28.                keyboardType: TextInputType.number,  
  29.              ),  
  30.              RaisedButton(  
  31.                child: Text(  
  32.                  'SAVE',  
  33.                  style: TextStyle(  
  34.                    color: Colors.white,  
  35.                  ),  
  36.                ),  
  37.                color: Colors.purple,  
  38.                onPressed: () {  
  39.                  final body = {  
  40.                    "name": _employeeNameController.text,  
  41.                    "age": _employeeAge.text,  
  42.                  };  
  43.                  ApiService.addEmployee(body).then((success) {  
  44.                    if (success) {  
  45.                      showDialog(  
  46.                        builder: (context) => AlertDialog(  
  47.                          title: Text('Employee has been added!!!'),  
  48.                          actions: <Widget>[  
  49.                            FlatButton(  
  50.                              onPressed: () {  
  51.                                Navigator.pop(context);  
  52.                                _employeeNameController.text = '';  
  53.                                _employeeAge.text = '';  
  54.                              },  
  55.                              child: Text('OK'),  
  56.                            )  
  57.                          ],  
  58.                        ),  
  59.                        context: context,  
  60.                      );  
  61.                      return;  
  62.                    }else{  
  63.                      showDialog(  
  64.                        builder: (context) => AlertDialog(  
  65.                          title: Text('Error Adding Employee!!!'),  
  66.                          actions: <Widget>[  
  67.                            FlatButton(  
  68.                              onPressed: () {  
  69.                                Navigator.pop(context);  
  70.                              },  
  71.                              child: Text('OK'),  
  72.                            )  
  73.                          ],  
  74.                        ),  
  75.                        context: context,  
  76.                      );  
  77.                      return;  
  78.                    }  
  79.                  });  
  80.                },  
  81.              )  
  82.            ],  
  83.          ),  
  84.        ),  
  85.      ),  
  86.    );  
  87.  }  
  88. }  
Step 6
 
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 the REST API in Flutter. We have used get and post methods of HTTP plugin.
Author
Parth Patel
272 6.9k 1.6m
Next » Form Validation In Flutter