CRUD Operations with Flutter and Node.js (GET REST API)

Saransh Singhal
6 min readSep 3, 2023

--

In this tutorial you will learn about :

  1. How to get data from Node.js as backend to Flutter front-end.
  2. How to use a FutureBuilder widget in Flutter.
  3. Using PostMan to get data.
  4. Setting up emulator/personal device to connect to local server.

Hey There 🙋🏼‍♂️, So this is a series of tutorial in which you will learn about CRUD operations in Flutter and Node.js.

If you know the Basics then you can continue the tutorial as I have mentioned everything from the beginning.

OR

You can read the previous story to get and idea about what we have done till last :

So let’s start of by creating a new URL in Node.js:

  1. This is the URL which will be called when a person clicks on GET button from the Flutter front-end.
  2. Creating a new URL :
const express = require("express");

const app = express();

app.use(express.json());

app.use(express.urlencoded({extended : true}));

app.listen(2000, ()=>{
console.log("listening to port 2000");
});

const productData = [];

//post api
app.post("/api/add_product", (req,res)=>{
console.log("Result", req.body);

const pdata = {
"id": productData.length + 1,
"name": req.body.name,
"price": req.body.price,
"desc" : req.body.desc

}

productData.push(pdata);
console.log("Final", productData);

res.status(200).send({
"status-code": 200,
"message": "Product added Successfully",
"Product": pdata
});
});


//get api
app.get("/api/get_product", (req,res)=>{
if(productData.length>0){
res.status(200).send({
"status_code": 200,
"product": productData
}


)
}
else{
res.status(200).send({
"status_code": 200,
"product":[]
})
}
})

Explanation:

  1. Using express package we use its get method and create a new URL /api/get_product.
  2. Then if we have data present in the productData List then we will display the status code to be 200 that means the connection is established and will display the list
  3. If our productData list is empty then we will display too we will display the status code to be 200 as the connection is established but list is empty.

Our back-end is ready to give data !

Now moving to front-end :

  1. We need to check if the data is being fetched using PostMan. (STEP-1)
  2. We need to create a function to get the data. (STEP-2)
  3. Creating UI to display that data. (STEP-3)

STEP-1 :

  1. Open PostMan or if you dont have it, you can download it through PostMan.
  2. In the search-bar type localhost:2000/api/get_product, and send a get request.

(Dont worry if your PostMan interface doesn’t look like mine, you just need to use the search bar to get the request.)

3. Fingers crossed 🤞🏼, We get the Body as

{
"status_code": 200,
"product": []
}

that means our api is working and is currently empty.

4. Now we check by entering data into our api from the app and then again using the get request

(NOTE : To get the code for sending request I have added the code above as add_product() and will provide the Github link below for the backend and frontend)

(NOTE : If you face issues with emulator then make sure you have watched the previous story, in this easy methods are displayed to connect emulator to local server.)

5. Now after clicking the POST button our data is been added to the list

6. Again sending GET request on PostMan :

Voila !! That means our backend is working properly !

STEP 2:

  1. Creating a function to get this data to our frontend :
import 'dart:convert';

import 'package:crud_frontend/model/product_model.dart';
import 'package:crud_frontend/post.dart';
import 'package:http/http.dart' as http;

class Http {
static String url = "http://192.168.180.1/api/";

static postProduct(Map pdata) async {
try {
final res = await http.post(Uri.parse("${url}add_product"), body: pdata);

if (res.statusCode == 200) {
var data = jsonDecode(res.body.toString());
print(data);
} else {
print("Failed to load data");
}
} catch (e) {
print(e.toString());
}
}

static getProduct() async {
List<Product> product = [];
try {
final res = await http.get(Uri.parse("${url}get_product"));

if (res.statusCode == 200) {
var data = jsonDecode(res.body);

data['product'].forEach((value) => {
product.add(
Product(
value['name'],
value['price'],
value['desc'],
),
)
});
return product;
}
else{
return [];
}
} catch (e) {
print(e.toString());
}
}
}

Explanation :

  1. Creating a getProduct function which is async because its time is not fixed for working.
  2. Getting all the data in a const res using http package and passing the URL as a Uri.
  3. If our connection is good, we take the response body(res) into a variable named data
  4. This data’s “product” item is been stored in the list we created before using for-loop.

Here is the Product list we created in the previous tutorial :

class Product{
final String name;
final String price;
final String desc;

Product(this.name, this.price, this.desc);

}

STEP-3 :

  1. Adding the data to UI.
  2. Our UI works as follows:

a. Data posted from the POST button

b. Using GET button we see a list of all the items that have been stored in the list.

(Code for these UI will be provided below in the Github Repo)

Creating a get.dart file and adding a stateless widget and implementing it as follows :

import 'package:crud_frontend/model/product_model.dart';
import 'package:crud_frontend/service/http.dart';
import 'package:flutter/material.dart';

class GET extends StatelessWidget {
const GET({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("GET data")),
body: FutureBuilder(
future: Http.getProduct(),
builder: (BuildContext context,AsyncSnapshot snapshot) {
if(!snapshot.hasData){
return Center(
child: CircularProgressIndicator(),
);
}
else{
List<Product> data = snapshot.data;

return ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context,int index) {
return ListTile(
leading: Icon(Icons.shopping_bag),
title: Text(data[index].name),
subtitle: Text(data[index].desc),
trailing: Text("₹ ${data[index].price}"),
);
},
);
}

},
),
);
}
}

Explanation:

  1. In the body of Scaffold we return a FutureBuildr(), here future is a parameter which takes the return of Http.getProduct()
  2. In the builder we create a if-else where, if the snapshot is empty (or the list is empty) a CircularProgressIndicator will be shown.
  3. If the snapshot contains data then a list of data will be shown.
  4. For that we assign snapshot’s data to a List of type Product (which we created earlier)
  5. Then creating a ListView which takes item count as the data’s lenght and itemBuilder as a ListTile

TESTING :

Now we need to test that everything is working fine 🤞🏼:

  1. Clicking on POST Button :

2. Voila !! We get our result in GET screen !!!

(The ‘bottle’ visible here is the one we tested before)

We have successfully learned the POST and GET request from flutter to node.js

Setup :

POST REST API :

GITHUB :

LinkedIn : https://www.linkedin.com/in/saransh-singhal-359082238/

Feel free to ask any queries or give any suggestions.

--

--

Saransh Singhal

Full Stack App developer trying to make learning easy and fun