How to connect flutter with MongoDB

Rohit Nishad picture Rohit Nishad · Jan 27, 2020 · Viewed 18.6k times · Source

I have a website build with Nuxt JS and MongoDB.

I want to create a mobile app with flutter and I don't know how to connect flutter with MongoDB.

Give me some code examples.

Here is the solution! (Click here)

Actually, I publish a blog about it feel free to check the solution!

  1. Works with MongoDB and also MongoDB Atlas
  2. Beginners guide

Answer

Sandeep Krishna picture Sandeep Krishna · Jan 27, 2020

Import flutter library mongo_dart and connect to the database. mongo_dart Server-side driver library for MongoDB implemented in pure Dart.

I hope the below code snippet helps !!

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();
  }

}