Friday, June 21, 2024
Google search engine
HomeDevelopersRest API in Flutter

Rest API in Flutter

Introduction

Hello and welcome to my new blog on Rest API in Flutter. In this blog, we shall discuss fetching data, deleting data, updating data using a JSON file. Nowadays the use of API in an app is very common, almost every app we use in daily life use API to display the uses data. We will use http package, which provides advanced methods to perform various operations. REST API uses a simple http calls to communicate with JSON data. Each request returns a Future<Response>.


Table of content

Need of http package & methods

Setting up the project

Creating a simple get Request

Handling the error code

Decoding the JSON data

Creating UI classes

Displaying the response on the screen

Updating the data

Deleting the data

Sending the data


Need of http Package?

  • :: It uses await and async feature.
  • :: It provides various method.
  • :: It provides class and http to perform web request.

:: Core Methods in http package?

Listing Http package methods woth giving a try and of much usage

  1. post Method

:: This method uses a URL and POST method to post the data and return a Future<Response>. It is used to send the data on the web.

2. get Method

:: get method uses a URL and fetches the data in JSON format.

3. delete Method

:: This method is used to delete the data using the DELETE method.

4. head Method

:: Uses the URL to request the data using the HEAD method and return the response as Future<Response>.

5. read Method

:: It is similar as get method, used to read the data.

6. put Method

:: It uses the specified URL and update the data specified by the user using the PUT method.

7. patch Method

It is very similar to the put method, used to update the data.

:: Setting up the Project

Install the http dependency

Add the following dependency in pubspec.yaml file

dependencies:
http:

Import the package as http

import 'package:http/http.dart' as http;

Also Import import 'dart:convert'; to convert the JSON data.

: Creating a Request

Future<List<Fruit>> fetchFruit() async {
final response = await http.get(url);
}
String url = "Your_URL";

This is the basic request using get method to fetch the data from the specified URL in the JSON format.

: Handling the error code

final response = await http.get(
'url');
if (response.statusCode == 200) {
//displaY UI
} else {
//SHOW ERROR MESSAGE
}
}

If the response status code is 200 then we can display the requested data otherwise we can show the error message to the users.

: Decoding the JSON data

List<Fruit> decodeFruit(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Fruit>((json) => Fruit.fromMap(json)).toList();
}

: Creating a Fruit class

class Fruit {
final int id;
final String title;
final String imageUrl;
final int quantity;

Fruit(
this.id,
this.title,
this.imageUrl,
this.quantity,
);
factory Fruit.fromMap(Map<String, dynamic> json) {
return Fruit(json['id'], json['title'], json['imageUrl'], json['quantity']);
}
factory Fruit.fromJson(Map<String, dynamic> json) {
return Fruit(json['id'], json['title'], json['imageUrl'], json['quantity']);
}
}

:: Creating a FruitList class

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]);
},
);
}
}

: Creating the FruitItem

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.imageUrl,
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}"),
],
)))
]),
));
}
}

: Displaying the response on the screen

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(title: Text("Product Navigation"),
),
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());
},
),
));
}
}
Decoding JSON data to display the UI

: Updating the data

Future<Fruit> updateFruit(String title) async {
final http.Response response = await http.put(
'url/$id',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);

if (response.statusCode == 200) {
return Fruit.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to update album.');
}
}

: Deleting the data

Future<Fruit> deleteAlbum(int id) async {
final http.Response response = await http.delete(
'url/$id',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);

if (response.statusCode == 200) {
return Fruit.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to delete album.');
}
}

: Sending the data

Future<Fruit> sendFruit(
String title, int id, String imageUrl, int quantity) async {
final http.Response response = await http.post(
'url',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
'id': id.toString(),
'imageUrl': imageUrl,
'quantity': quantity.toString()
}),
);
if (response.statusCode == 201) {
return Fruit.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load album');
}
}

Github Link

flutter-devs/rest_API_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com

🌸🌼🌸 Thank you for reading. 🌸🌼🌸🌼


Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Previous article
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments