Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

flutter rest api

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:

rest api
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.
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<list<dynamic>> 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<bool> 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<employeepage> {
 @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.
class addnewemployeepage extends statefulwidget {
 addnewemployeepage({key key}) : super(key: key);
 
 _addnewemployeepagestate createstate() => _addnewemployeepagestate();
}
 
class _addnewemployeepagestate extends state<addnewemployeepage> {
 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: <widget>[
             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: <widget>[
                           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: <widget>[
                           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


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.