How to Integrate Node.js with Flutter

Vinayak
YavarTechWorks
Published in
4 min readMay 23, 2023

Flutter is a popular open-source framework for developing cross-platform mobile applications, while Node.js is a powerful and scalable JavaScript runtime environment that can be used for building server-side applications. In this article, we’ll explore how to integrate Flutter with Node.js to create powerful, full-stack mobile applications.

Before we get started, it’s important to understand that Node.js is a server-side technology, which means that it’s not designed to be used directly in mobile applications. However, by leveraging the power of Node.js through APIs and web services, we can create robust backends that can be used by mobile applications built using Flutter.

Step 1: Setting Up the Node.js Server

The first step in integrating Flutter with Node.js is to set up a backend server that can be accessed by the mobile application. To do this, we’ll use Node.js and a popular web framework called Express.js.

To get started, create a new Node.js project and install the Express.js package by running the following command:

npm install express

Next, create a new file called server.js and add the following code:

const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`)
})

This code sets up a basic Express.js server that listens on port 3000 and responds to requests with a simple “Hello World!” message.

To test the server, run the following command in your terminal:

node server.js

If everything is working correctly, you should see the message “Server running at http://localhost:3000" in your console.

Step 2: Creating an API for the Flutter App

Now that we have a basic Node.js server set up, we can create an API that the Flutter app can use to communicate with the server. For this example, we’ll create a simple API that returns a list of books.

Add the following code to your server.js file:

const books = [
{id: 1, title: 'Alice in Wonderland', author: 'Lewis Carrol'},
{id: 2, title: 'Around the World in eighty days', author: 'Jules Verne'},
{id: 3, title: 'Utopia', author: 'Sir Thomas Moor'},
]

app.get('/api/books', (req, res) => {
res.json(books)
})

This code creates an array of book objects and sets up an API endpoint at /api/books that returns the array as JSON.

To test the API, run the server using the ‘node server.js’ command and visit http://localhost:3000/api/books in your web browser. You should see the list of books in JSON format.

Step 3: Integrating the API with Flutter

With the Node.js server and API set up, we can now integrate it with a Flutter mobile application. To do this, we’ll use the http package to make HTTP requests to the API.

First, we will create a model for the book data.

class Book {
final int id;
final String title;
final String author;

Book({required this.id, required this.title, required this.author});

factory Book.fromJson(Map<String, dynamic> json) {
return Book(
id: json['id'],
title: json['title'],
author: json['author'],
);
}
}

In this example, we define a Book class that represents a book with an id, title, and author.

Then add the following code to the lib/main.dart file:

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

void main() => runApp(BookApp());

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

class BooksScreen extends StatefulWidget {
@override
_BooksScreenState createState() => _BooksScreenState();
}
class _BooksScreenState extends State<BooksScreen> {
List<Book> _books = [];
@override
void initState() {
super.initState();
_fetchBooks();
}
Future<void> _fetchBooks() async {
final response = await http.get(Uri.parse('http://localhost:3000/api/books'));
if (response.statusCode == 200) {
final List<dynamic> json = jsonDecode(response.body);
setState(() {
_books = json.map((item) => Book.fromJson(item)).toList();
});
} else {
throw Exception('Failed to load books');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Books'),
),
body: ListView.builder(
itemCount: _books.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(_books[index].title),
subtitle: Text(_books[index].author),
);
},
),
);
}
}

In the above code, we define a BooksScreen widget that fetches the list of books from the API endpoint /api/books and displays them in a ListView.builder. The Book.fromJson method is used to convert each JSON object from the API response to a Book object.

To display the list of books, we use the ListView.builder widget that takes an ‘itemCount’ and an ‘itemBuilder’ callback. The itemCount is set to the length of the _books list, and the itemBuilder callback is called for each item in the list. In the itemBuilder callback, we return a ListTile widget that displays the book’s title and author.

To run this Flutter UI, we need to start the Node.js server that serves the API, and then run the Flutter app on an emulator or physical device. We can do that by running the following commands in the terminal:

$ node server.js
$ flutter run

This will start the Node.js server on port 3000 and launch the Flutter app on an emulator or physical device. The Flutter app should fetch the list of books from the API and display them in a list view.

Conclusion

In conclusion, integrating Node.js with Flutter can enable developers to build full-stack applications that utilize the strengths of both technologies. By using Node.js for the backend and Flutter for the frontend, developers can create powerful and scalable applications that deliver a seamless user experience across multiple platforms.

Thanks for reading this article ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Until then Bye-Bye.

--

--