In this tutorial, we will continue our journey through Full Stack Development by learning about Node, Express, MongoDB, and Flutter development.
Node is a popular server-side JavaScript runtime that allows you to build scalable and efficient web applications. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. MongoDB is a NoSQL database that allows you to store and retrieve data in a flexible and efficient manner. Flutter is an open-source UI software development kit created by Google that allows developers to build natively compiled applications for mobile, web, and desktop from a single codebase.
In this tutorial, we will focus on integrating Node, Express, MongoDB, and Flutter to build a full-stack application. We will start by setting up a Node and Express server that connects to a MongoDB database. We will then create an API that allows us to perform CRUD operations on our database. Finally, we will build a Flutter frontend that consumes our API to display and manipulate data.
To get started, let’s first set up our Node and Express server. Create a new directory for your project and run the following commands in your terminal:
mkdir fullstack-demo
cd fullstack-demo
npm init -y
npm install express mongoose
Next, create a new file called server.js
and add the following code:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb://localhost/fullstack-demo', { useNewUrlParser: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch(err => {
console.error('Error connecting to MongoDB:', err);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
This code sets up a basic Express server and connects to a local MongoDB database named fullstack-demo
. Make sure you have MongoDB installed on your system and running before starting the server.
Now let’s create a basic API for performing CRUD operations on our database. Add the following code to server.js
:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const Item = mongoose.model('Item', {
name: String,
description: String
});
app.get('/items', async (req, res) => {
const items = await Item.find();
res.json(items);
});
app.post('/items', async (req, res) => {
const newItem = new Item(req.body);
await newItem.save();
res.json(newItem);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
This code defines two routes for fetching and creating items in our MongoDB database. We have also defined a simple data model for our items using Mongoose.
To test our API, you can use tools like Postman or cURL to send HTTP requests to http://localhost:3000/items
. Make sure to install the body-parser
middleware to parse incoming request bodies in JSON format.
Next, let’s set up a Flutter project to consume our API and display the data. Install Flutter on your system and create a new Flutter project using the following commands:
flutter create fullstack_flutter
cd fullstack_flutter
Open the pubspec.yaml
file in your project directory and add the http
package as a dependency:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
Run flutter pub get
to install the dependencies and then create a new file called main.dart
in the lib
directory. Add the following code to main.dart
:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Future<List> fetchItems() async {
final response = await http.get(Uri.parse('http://localhost:3000/items'));
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load items');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Full Stack Demo'),
),
body: FutureBuilder<List>(
future: fetchItems(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data[index]['name']),
subtitle: Text(snapshot.data[index]['description']),
);
},
);
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
return Center(child: CircularProgressIndicator());
},
),
),
);
}
}
This code defines a Flutter app that fetches items from our API and displays them in a list view. Make sure to replace the sample URL with your server’s address.
To run the Flutter app, use a simulator or connect a physical device to your computer and run flutter run
in the project directory. You should see a list of items fetched from your API displayed on the screen.
Congratulations! You have successfully integrated Node, Express, MongoDB, and Flutter to build a full-stack application. Stay tuned for more tutorials on Full Stack Development with other technologies and frameworks.
Where is full stack course?
There is no full stack course