Connecting MongoDB to a Flutter App Using mongo_dart

KAILASH RAJPUT
3 min readSep 24, 2023

--

MongoDB is a popular NoSQL database known for its flexibility and scalability. Integrating MongoDB with a Flutter app can be a powerful combination. In this blog, we’ll explore how to connect MongoDB to a Flutter app using the mongo_dart package.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. Flutter Installed: Ensure that you have Flutter and Dart set up on your development machine. You can download Flutter from here.
  2. Server: MongoDB should be installed and running. You can download and install MongoDB from here.
  3. MongoDB Database: Create a MongoDB database where your app data will be stored.

Setting Up the Flutter Project

Let’s create a new Flutter project or use an existing one.

  1. Add Dependencies:

In your pubspec.yaml file, add the mongo_dart package:

dependencies:
flutter:
sdk: flutter
mongo_dart: ^latest_version

Replace latest_version with the actual version of mongo_dart.

  1. Run flutter pub get to fetch and install the dependencies.

Step 1: Import the Package

In your Flutter project, import the mongo_dart package in the Dart file where you intend to work with MongoDB.

import 'package:mongo_dart/mongo_dart.dart';

Step 2: Establish a Connection

To connect to your MongoDB server, you need to create a Db instance. Provide the connection details such as the server address and port.

final Db db = Db('mongodb://your_server_address:your_port');

Replace your_server_address and your_port with the appropriate values for your MongoDB server configuration.

Step 3: Open the Connection

Open the MongoDB connection asynchronously. It’s important to handle any potential exceptions during the connection process.

  static Future<void> connect() async {
try {
db = await Db.create(mongoUri);
await db!.open();
inspect(db);
} catch (e) {
log(e.toString());
}
}

Step 4: Interact with MongoDB

Once connected, you can perform various database operations such as querying, inserting, updating, and deleting data. Here’s a basic example of inserting a document into a collection:

final collection = db.collection('your_collection_name');

final documentToInsert = {
'name': 'John Doe',
'email': 'john@example.com',
};

await collection.insert(documentToInsert);

You can also retrieve data using queries:

final query = where.eq('name', 'John Doe');
final result = await collection.findOne(query);

if (result != null) {
print('Found document: $result');
} else {
print('Document not found');
}

Step 5: Close the Connection

It’s essential to close the MongoDB connection when you’re done using it to free up resources.

static Future<void> close() async {
try {
await db!.close();
} catch (e) {
log(e.toString());
}
}

Step 6: Error Handling

Always implement error handling to gracefully handle any exceptions that may occur during the database operations. This ensures that your app remains robust and user-friendly.

Step 7: Complete code

import 'dart:developer';
import 'package:flutter/widgets.dart';
import 'package:mongo_dart/mongo_dart.dart';
import 'package:travel_app/constants/dburl.dart';

class MongoDatabase {
static Db? db;
static final DbCollection user = db!.collection(userCollection);
static final DbCollection allplaces = db!.collection(places);
static final DbCollection allHotels = db!.collection(hotelCollection);

static Future<void> connect() async {
try {
db = await Db.create(mongoUri);
await db!.open();
inspect(db);
} catch (e) {
log(e.toString());
}
}

static Future<void> close() async {
try {
await db!.close();
} catch (e) {
log(e.toString());
}
}
}

Conclusion

By following these steps, you can seamlessly connect MongoDB to your Flutter app using the mongo_dart package. You can then build powerful, data-driven applications that leverage the flexibility and scalability of MongoDB as your backend database.

Remember that this is just a basic example, and you can expand on it to build more complex functionality for your Flutter app, such as user authentication, data synchronization, and real-time updates. MongoDB’s versatility combined with Flutter’s rich UI capabilities opens up a world of possibilities for your mobile app development projects.

--

--