Flutter has become a popular choice for mobile app development, and MongoDB is a widely used NoSQL database for data storage. Connecting Flutter with MongoDB can provide a powerful solution for building scalable and robust mobile applications. In recent times, several advancements have made it easier to connect Flutter with MongoDB. In this article, we will explore the basics of connecting Flutter and MongoDB, providing insights into the benefits and possibilities that this combination offers.
Here I will explain from start to end how to connect MongoDB to Flutter with code examples, let’s start playing!
First, let’s decide in which manner you connect your MongoDB to Flutter, Let’s discuss.
If you already have a Node JS backend or any kind of API so it totally worst idea to write that same login again in Flutter (Literally it’s worst!), so in this situation, you just have to use API clients (such as http) to make a call to your API endpoint.
But if it’s a special case where connecting MongoDB is the only option moving forward with this blog.
Ok, now let’s start this tutorial + blog
Warning: It’s always recommended to create a web server or backend and access the database from there and use backend APIs. It’s for educational purposes and experiments only.
How to connect Connect Flutter to MongoDB?
There are several third-party packages available on pub.dev,
- mongo_dart: A pure Dart driver for MongoDB, which can be used with Flutter applications.
- mongo_flutter: A lightweight package that provides a simple and intuitive API for connecting to MongoDB databases from Flutter apps.
- flutter_mongo: Another package that provides a simple API for connecting to MongoDB databases, with support for CRUD operations.
In order to connect MongoDB, you must have a dart package (dart is a programming language and flutter is written on dart) we are going to use a package called ‘mongo_dart’.
A brief intro to ‘mongo_dart’
‘mongo_dart’ is an unofficial, community-supported server-side driver library for MongoDB implemented in pure Dart. Server-side means all packages using dart:io, dart:html is nota accepted.
import 'package:mongo_dart/mongo_dart.dart' show Db, DbCollection;
Now create an instance to store DB connection.
static DBConnection _instance;
Set the MongoDB connection details (to generate URI)
final String _host = "DATABASE SERVER";
final String _port = "DATABASE PORT";
final String _dbName = "DATABASE NAME";
Db _db;
Now here implement three simple functions (getInstance, getConnection, closeConnection)
To get the DB instance.
static getInstance(){
if(_instance == null) {
_instance = DBConnection();
}
return _instance;
}
To get the mongo connection.
Future<Db> getConnection() async{
if (_db == null){
try {
_db = Db(_getConnectionString());
await _db.open();
} catch(e){
print(e);
}
}
return _db;
}
_getConnectionString(){
return "mongodb://$_host:$_port/$_dbName";
}
To close the connection.
closeConnection() {
_db.close();
}
FINAL CODE
import 'package:mongo_dart/mongo_dart.dart' show Db, DbCollection;
class DBConnection {
static DBConnection _instance;
final String _host = "DATABASE SERVER";
final String _port = "DATABASE PORT";
final String _dbName = "DATABASE NAME";
Db _db;
static getInstance(){
if(_instance == null) {
_instance = DBConnection();
}
return _instance;
}
Future<Db> getConnection() async{
if (_db == null){
try {
_db = Db(_getConnectionString());
await _db.open();
} catch(e){
print(e);
}
}
return _db;
}
_getConnectionString(){
return "mongodb://$_host:$_port/$_dbName";
}
closeConnection() {
_db.close();
}
}
How to connect Connect Flutter to MongoDB Atlas?
The concept is the same, you just need to pass the credentials and modify the URI (add “+srv” suffix)
FINAL CODE
import 'package:mongo_dart/mongo_dart.dart' show Db, DbCollection;
class DBConnection {
static DBConnection _instance;
final String _getConnectionString = "MONGODB_ATLAS_URI";
Db _db;
static getInstance(){
if(_instance == null) {
_instance = DBConnection();
}
return _instance;
}
Future<Db> getConnection() async{
if (_db == null){
try {
_db = Db.create(_getConnectionString);
await _db.open();
} catch(e){
print(e);
}
}
return _db;
}
closeConnection() {
_db.close();
}
}
Usages
var collection = db.collection('authors');
await collection.insertMany([
{
'name': 'William Shakespeare',
'email': 'william@shakespeare.com',
'age': 587
},
{'name': 'Jorge Luis Borges', 'email': 'jorge@borges.com', 'age': 123}
]);
Connecting Flutter and MongoDB Realm
To connect MongoDB Realm with Flutter, you can use the official Realm Flutter SDK, which provides a simple and intuitive API for integrating your app with the Realm platform. With this integration, you can build robust and feature-rich mobile applications with ease.
Things to keep in mind
- If you have API then it’s the worst idea to write the whole login again in a flutter!
- mongo_dart is an unofficial package (there is no official package)
In summary, connecting Flutter with MongoDB can be achieved using third-party packages such as mongo_dart, mongo_flutter, or flutter_mongo. Among them, mongo_dart is a pure Dart driver for MongoDB that can be used with Flutter applications. The connection details are set by providing the MongoDB host, port, and database name. To connect Flutter with MongoDB Atlas, the URI needs to be modified by adding the “+srv” suffix. Finally, to connect Flutter with MongoDB Realm, you can use the official Realm Flutter SDK. It’s important to note that if you already have an API, it’s not recommended to write the same code again in Flutter.
5 thoughts on “Connect Flutter to MongoDB or MongoDB Atlas”
Why would you want to destroy your own system, granting unrestricted access to everything, to everybody? I don’t see a reason to do such thing. Even if you don’t have your own custom made Web Server with an API (with Ruby, Laravel, Node.js + Epress.js, etc, etc), you can always use Firebase, which offers that precisely, out of the box and FOR FREE (of course, with Cloud Firestore or Realtime Database). So there is no reason to do it this way. It makes no sense.
I totally agree with you. Even thanks for your suggestion I am going to edit the blog and add some warning to it reagrding this.
But other then that the post remenis the same because its for educational perpouse or kind of fun to do its not recommended doesn’t mean its not doable.
It is absolutely irrational to connect your front end client or mobile app directly to your DB, without using a Server which exposes the necessary API end points. Your API is the only one that should be connected directly to your DB. Otherwise every single user that unpacks your app’s code, will have full access to all the API keys, AWS S# secret keys, and every single Env variable with all the login data to your DB, etc, etc, etc. Will have absolute access to everything. This is suicidal.
same here..
searching how to connect flutter web app with mongodb atlas.
can you please guide me for connecting flutter web app with MongoDB atlas?