Making Simple App MongoDb and Flutter

Nurettin Eraslan
4 min readJul 4, 2023

--

We can create a sample movie showcase application using Flutter and MongoDB. This application will display movie information to users, and users will be able to add, edit, or delete movies from the movie list. You can follow the steps below to create this application:

Step 1: MongoDB Installation Download MongoDB from the official MongoDB website and install it on your computer. Follow the specific instructions for your operating system during the installation process.

Step 2: Starting the Database Server To start the MongoDB database server, follow these steps:

  1. Open a terminal.
  2. Navigate to the directory where MongoDB is installed.
  3. Run the following command to start the MongoDB database:
mongod

This command starts the MongoDB server and begins listening on the default port 27017.

Step 3: Creating the Database

  1. Open another terminal.
  2. Start the MongoDB client by running the following command:
mongo

This command starts the MongoDB client and connects it to the MongoDB server.

  1. In the MongoDB client, run the following command to create a new database:
use film_intro_app

This command creates a database named “film_tanitim_uygulamasi” or switches to an existing database. You can replace the name “film_tanitim_uygulamasi” with your desired database name.

Once the database is created, MongoDB is ready to store data under the specified database name. You can update the connection URL in your database.dart file in your Flutter application to connect to this database.

You can now create and integrate a MongoDB database with your Flutter application by following these steps.

Flutter Setup

Step 1: Project Setup To create your Flutter project, run the following command:

flutter create film_intro_app

Step 2: Adding Dependencies In the pubspec.yaml file, add the required packages for your Flutter application. We will be using the "mongo_dart" package to access MongoDB. Add the following code to the dependencies section:

dependencies:
flutter:
sdk: flutter
mongo_dart: ^0.3.0

Run the following command in the terminal to install the packages:

flutter pub get

Step 3: Establishing the Database Connection Create a new file named database.dart in the lib directory and add the following code:

import 'package:mongo_dart/mongo_dart.dart';

class Database {
static final Database _instance = Database._internal();
Db _db;

factory Database() {
return _instance;
}

Database._internal() {
_db = Db('mongodb://localhost:27017/film_intro_app');
}

Future<void> openConnection() async {
await _db.open();
}

Future<void> closeConnection() async {
await _db.close();
}

DbCollection get films => _db.collection('films');
}

This class is responsible for connecting to the MongoDB database and accessing the films collection. You can use the openConnection and closeConnection methods to open and close the connection.

Step 4: Film Model Create a new file named film.dart in the lib directory and add the following code:

class Film {
final String id;
final String title;
final String director;
final int year;

Film({this.id, this.title, this.director, this.year});

Map<String, dynamic> toMap() {
return {
'title': title,
'director': director,
'year': year,
};
}

factory Film.fromMap(Map<String, dynamic> map, String id) {
return Film(
id: id,
title: map['title'],
director: map['director'],
year: map['year'],
);
}
}

This class represents the Film model, which includes an id, title, director, and year for each film. The toMap method converts the film into a map, and the fromMap method converts a map into a Film object.

Step 5: Main Screen Create a new file named main.dart in the lib directory and add the following code:

import 'package:flutter/material.dart';
import 'database.dart';
import 'film.dart';

void main() async {
await Database().openConnection();
runApp(FilmIntroApp());
}

class FilmIntroApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Film Intro App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FilmListScreen(),
);
}
}

class FilmListScreen extends StatefulWidget {
@override
_FilmListScreenState createState() => _FilmListScreenState();
}

class _FilmListScreenState extends State<FilmListScreen> {
List<Film> films = [];

@override
void initState() {
super.initState();
_getFilms();
}

Future<void> _getFilms() async {
final List<Map<String, dynamic>> data =
await Database().films.find().toList();
setState(() {
films = data
.map((filmData) => Film.fromMap(filmData, filmData['_id'].toString()))
.toList();
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Film List'),
),
body: ListView.builder(
itemCount: films.length,
itemBuilder: (context, index) {
final film = films[index];
return ListTile(
title: Text(film.title),
subtitle: Text(film.director),
trailing: Text(film.year.toString()),
);
},
),
);
}
}

In this code, we create the main screen and the film list. The FilmListScreen class retrieves the films from the database and displays them as a list.

Step 6: Running the Application Start the MongoDB database server locally and run your Flutter application on an emulator or physical device. The films will be listed. You can then add a user interface to perform add, edit, or delete operations.

This is a basic example that helps you create a sample film introduction application using Flutter and MongoDB. You can use this starting point to customize the application and add more features.

--

--