How to implement Rest API in Flutter?
Along with building a UI in Flutter, we can also integrate it with the backend. So, in this article, we will see how to implement Rest API in Flutter.
How to implement Rest API in Flutter?
Most applications use API to display the user’s data. We will use the HTTP package, which provides advanced methods to perform operations. REST API uses simple HTTP calls to communicate with JSON data because:
- It uses await & async features.
- It provides various methods.
- Also it provides class and HTTP to perform web requests.
Let us see how a JSON file is used to Fetch, Delete & Update data in a flutter app. We will make separate dart files of Main.dart for easier debugging & cleaner code in the following steps.
1) Setting up the Project:
Install the HTTP dependency and add it in pubspec.yaml file in order to use API in the application.
dependencies: http:
2) Creating a Request:
This basic request uses the get method to fetch the data from the specified URL in JSON format. Each request returns a Future<Response>. A Future<> is used to represent a potential value or error that will be available at some time in the future. For example, you made a request to a server now the response will take less than a few seconds. This time is represented from Future<>. Here, we use the async & await feature which ensures that the response is asynchronous. It means that until & unless we get the response, it will not move further.
Future<List<Fruit>> fetchFruit() async { final response = await http.get(url); } String url = "Your_URL";
3) Creating the Classes:
Create a Fruit class & save it as fruit.dart as shown below:
class Fruit { final int id; final String title; final String imgUrl; final int quantity; Fruit( this.id, this.title, this.imgUrl, this.quantity, ); factory Fruit.fromMap(Map<String, dynamic> json) { return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']); } factory Fruit.fromJson(Map<String, dynamic> json) { return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']); } }
4) Create Class objects:
Create the FruitItem in fruitItem.dart
import 'package:flutter/material.dart'; import 'fruit.dart'; class FruitItem extends StatelessWidget { FruitItem({this.item}); final Fruit item; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( elevation: 5, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.network( this.item.imgUrl, width: 200, ), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.item.title, style: TextStyle(fontWeight: FontWeight.bold)), Text("id:${this.item.id}"), Text("quantity:${this.item.quantity}"), ], ))) ]), )); } }
5) Create a List of fruits:
Create a FruitList class in fruitList.dart as shown below:
import 'package:flutter/material.dart'; import 'fruit.dart'; import 'fruitItem.dart'; class FruitList extends StatelessWidget { final List<Fruit> items; FruitList({Key key, this.items}); @override Widget build(BuildContext context) { return ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return FruitItem(item: items[index]); }, ); } }
6) Displaying the Responses:
Display the response on the screen from main.dart file as shown below:
import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:flutter/material.dart'; import 'fruit.dart'; import 'fruitItem.dart'; import 'fruitList.dart'; class MyHomePage extends StatelessWidget { final String title; final Future<List<Fruit>> products; MyHomePage({Key key, this.title, this.products}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color(0xFF4CAF50), title: Text("GeeksForGeeks"), ), body: Center( child: FutureBuilder<List<Fruit>>( future: products, builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? FruitList(items: snapshot.data) : Center(child: CircularProgressIndicator()); }, ), )); } }
Conclusion:
Thanks for being with us on a Flutter Journey!
So, in this article, we have seen how to implement Rest API in Flutter. Also, feel free to comment and provide any other suggestions regarding Flutter.
Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.
Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.
Contemporary ventures
Recent blog
ready to get started?
Fill out the form below and we will be in touch soon!
"*" indicates required fields