Flutter with Backend(APIs development using Nods.Js)

Hamza Asif
6 min readOct 3, 2024

--

To create APIs with Node.js and Express for use in a Flutter app, you can follow these steps:

We will use VS Code for this tutorial.

Set up Node.js and Express

First, you need to install Node.js and set up an Express project.

Install Node.js:

Note: Flutter Machine Learning & AI Courses

If you want to build Machine Learning and AI based smart Flutter apps then check our Mobile Machine Learning courses on udemy. Avail 92% off with coupon code “MOBILEMLAI” only for a limited time

  1. Flutter & ML : Train Tensorflow Lite models for Flutter Apps
  2. Face Recognition and Detection in Flutter — The 2024 Guide
  3. Flutter & OCR — Build Document Scanner Clone in Flutter
  4. FlutterFlow for Beginners: Build “No Code” Apps in 2024
  5. Flutter & Google Gemini — Build Chatbots and Assistants in Flutter
  6. Train Image Classification Models & Build Smart Flutter Apps
  7. Build Gallery App Clone in Flutter With Circle To Search Feature
  8. Machine Learning for Flutter- The Complete 2024 Guide
  9. Build Flutter Apps Effortlessly with ChatGPT — Zero Coding
  10. Flutter & AI: Build Image & Art Generation Flutter App

Make a folder for apis in your desktop:

Make it manually or by command below.

mkdir flutter-api

open this folder in VS Code.

cd flutter-api

Install all dependencies in project already opened in VS Code by typing in terminal of VS Code.

npm init -y

It will create package.json file in your project.

Now install express in your project. Express is used for backend.

npm i express

It will create more files in your project. Now install nodemon, it will be used for auto updation of server when any changes happen in code.

npm i nodemon

Now, create a new file named as app.js in your project.

echo > app.js

At this end our project structure will be like this.

Now Connect server with our project:

In first line, we get express instance by using require function.
In second line, we create an app. By using this app we can use all properties methods of express.
In fourth line, we declare our PORT, here process.env.PORT means whatever port is available now, or 5000 takes as a localhost port.
From 6 to 8 line of code, we are making a GET route, whenever someone hit this url, he will get a message “Hi, I am live”.
From line 10 to 17, we make a method start to connect or listen to server in try catch block for exception handling on connecting to server. If server connects successfully, inner lines of method will run.
App.js

const express = require('express');
const app = express();

const PORT = process.env.PORT || 5000;

app.get("/",(req, res) => {
res.send("Hi, I am live");
});

const start = async () => {
try{
app.listen(PORT, ()=>{
console.log('${PORT} Yes I am Connected');
})
} catch (error){
console.log(error);
}
}

start();

For running above code, you have to add script in package.json file.
Go to package.json file, remove whatever is written within script, and add these lines.
package.json

"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
},

Now, you run command for running dev script with nodemon, or you can run start script with node.

npm run dev

expected output:

If you cam up with exception or error “EADDRINUSE”, then change your port.

Now, you can check your api route on browser. By hitting on localhost:(YOUR_PORT)

Setup the controllers and Routes:

Controllers have all the methods and Routes tell which functions have to be called from controllers.

Let’s make two seperate folders for controllers and routes.

mkdir routes
mkdir controllers

Now, make files named as product.js in both folders. You can use different names also.

cd routes
echo > products.js
routes % cd ..
cd controllers
echo > products.js

Check if your server is still connected by run “npm run dev”.

Now, go to product.js file of routes.
Firstly, make instance of express and then instance of Router.
After that we have to declare routes, which function will be called on which route.
These functions will be defined in controllers.
In the last, we make these routes export for accessibility.
routes -> product.js

const express = require("express");
const router = express.Router();

router.route("/").get(getAllProducts);
router.route("/testing").get(getAllProductsTesting);

module.exports = router;

Now, we defined these functions in controllers -> product.js.
In both functions, we returned a json data having msg in it after checking wether status is 200 or not.
At the end, we export these functions.
controllers -> product.js

const getAllProducts = async (req, res) => {
res.status(200).json({ msg: "I am getAllProducts"});
};

const getAllProductsTesting = async (req, res) => {
res.status(200).json({ msg: "I am getAllProductsTesting"});
};

module.exports = { getAllProducts, getAllProductsTesting};

Now, try to import routes (tell the path of these functions, where these are defined)
routes -> product.js

const express = require("express");
const router = express.Router();

const {
getAllProducts,
getAllProductsTesting,
} = require("../controllers/products");

router.route("/").get(getAllProducts);
router.route("/testing").get(getAllProductsTesting);

module.exports = router;

Now use middleware to set router to tell app.js file about using the routes now.

For this, add these two lines in your app.js file.

const product_routes = require("./routes/products");

app.use("/api/products", product_routes);

Now, you can get json data by hitting url “/api/products” after localhost:port. Same with the testing api also “/api/products/testing”.

output:

To use an API in Flutter in a simple way, you can follow these steps:

1. Add the http package to your pubspec.yaml

First, add the http package, which helps you make HTTP requests.

dependencies:
http: ^0.13.5 # Add the latest version

Run flutter pub get to install the package.

2. Make an API call

In your Dart file, import the http package and use it to make API requests.

Example: Fetching Data from an API

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert'; // To handle JSON

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
// Function to fetch data from the API
Future<String> fetchData() async {
final response = await http.get(Uri.parse('http://localhost:5001/api/products'));

if (response.statusCode == 200) {
// If the server returns a response, decode it
final jsonResponse = json.decode(response.body);
return jsonResponse['msg']; // Extract the 'msg' from the response
} else {
// If there was an error, throw an exception
throw Exception('Failed to load data');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('API Example')),
body: Center(
child: FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // Loading indicator
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
// Display the 'msg' field from the API response
return Text('Message: ${snapshot.data}');
}
},
),
),
);
}
}

Explanation

  1. http.get(): Makes a GET request to http://localhost:5001/api/products.
  2. json.decode(): Converts the API response into a Dart map.
  3. jsonResponse['msg']: Extracts the msg value from the JSON response.
  4. FutureBuilder: Handles asynchronous data fetching, displaying a loading indicator while waiting for the response, and showing the msg field once the response is received.

Important Note:

  • For Emulators or Devices: If you’re running this on a physical device or emulator, you need to use your machine’s IP address instead of localhost, because localhost refers to the device itself.
  • Replace localhost with your local machine’s IP. Example: http://192.168.1.100:5001/api/products.

Note: Flutter Machine Learning & AI Courses

If you want to build Machine Learning and AI based smart Flutter apps then check our Mobile Machine Learning courses on udemy. Avail 92% off with coupon code “MOBILEMLAI” only for a limited time

  1. Flutter & ML : Train Tensorflow Lite models for Flutter Apps
  2. Face Recognition and Detection in Flutter — The 2024 Guide
  3. Flutter & OCR — Build Document Scanner Clone in Flutter
  4. FlutterFlow for Beginners: Build “No Code” Apps in 2024
  5. Flutter & Google Gemini — Build Chatbots and Assistants in Flutter
  6. Train Image Classification Models & Build Smart Flutter Apps
  7. Build Gallery App Clone in Flutter With Circle To Search Feature
  8. Machine Learning for Flutter- The Complete 2024 Guide
  9. Build Flutter Apps Effortlessly with ChatGPT — Zero Coding
  10. Flutter & AI: Build Image & Art Generation Flutter App

--

--

Hamza Asif
Hamza Asif

Written by Hamza Asif

Udemy Instructor, Flutter Dev helping people Integrate ML & AI in Mobile Apps . Visit my courses https://www.udemy.com/user/e1c14fb5-1c9b-45ef-a479-bbc543e33254

No responses yet