flutter-tutorial

Flutter Rest Api (GET,POST,PUT,DELETE)

We can use Flutter to create a UI as well as link it with the backend. The majority of applications make use of APIs to display user data. We’ll utilise the HTTP package, which has a lot of complex techniques for doing things. Because: REST API communicates with JSON data using basic http requests

  • It makes use of the await and async functionalities.
  • It offers a variety of options.
  • It comes with class and http for doing web requests.

Let’s look at how a JSON file is utilised in a Flutter app to Fetch, Delete, and Update data. In the next phases, we’ll split Main.dart into distinct dart files for better debugging and cleaner code.

Step 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:

Step 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 async & await feature which ensures that the response is asynchronous which means 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";

Step 3: Creating the Classes

Create a Fruit class & saving 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']);
  }
}

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

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

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

1.Post Data

Future<Fruit> sendFruit(
  
String title, int id, String imgUrl, 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(),
      'imgUrl': imgUrl,
      'quantity': quantity.toString()
    }),
  );
  if (response.statusCode == 201) {
    return Fruit.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}

2. Put 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.');
  }
}

3. Delete 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.');
  }
}

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.