Connect Flutter to MongoDB or MongoDB Atlas

I hope you enjoy reading this!
Don’t forget to share this blog with your friends.

Table of Contents
Connect Flutter to MongoDB or MongoDB Atlas

Flutter is getting popular these days, flutter community has some unanswered questions (I think) one of my unanswered questions was “How to connect MongoDB to flutter” and I got the answer (thanks to StackOverflow).

Here I will explain from start to end how to connect MongoDB to flutter with code examples, let 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 move forward with this blog.

Ok, now let start  this tutorial + blog

How to connect Connect Flutter to MongoDB?

In order to connect MongoDB, you must have a dart package (dart is a programming language and flutter is written on dart) 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 function (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': '[email protected]',
      'age': 587
    },
    {'name': 'Jorge Luis Borges', 'email': '[email protected]', 'age': 123}
]);

Things 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)

Leave a Comment

Your email address will not be published. Required fields are marked *

Get an AMAZING ARTICLE for FREE that cost me 100$
Get an AMAZING ARTICLE for FREE that cost me 100$
Get inside Data of your Industry for FREE
You are only 2 steps away from complete research-based data.
This site uses cookies to improve your user experience.