Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect flutter with MongoDB

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
like image 366
Rohit Nishad Avatar asked Jan 27 '20 03:01

Rohit Nishad


People also ask

Can we use MongoDB in Android?

After you have logged in to your account you will be able to see the following screen. Here we have to create a MongoDB database which will be connected to our android device later. So to create a database, Go to your projects folder and click on Create new project button.

Does realm support flutter?

Today, we are pleased to announce the next installment of the Realm Flutter SDK – now with support for Windows, macOS, iOS, and Android.

What is realm MongoDB?

Realm is an embedded, object-oriented database that lets you build real-time, offline-first applications. Its SDKs also provide access to Atlas App Services, a secure backend that can sync data between devices, authenticate and manage users, and run serverless JavaScript functions.


Video Answer


2 Answers

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

}
like image 149
Sandeep Krishna Avatar answered Oct 21 '22 03:10

Sandeep Krishna


Answer by Sandeep Krishna is correct but if you already have a Nodejs backend then expose REST API and connect with Flutter using http, dio or other similar packages. As connecting frontend directly to database is bad. Its just a advice.

like image 44
Ratnadeep Bhattacharyya Avatar answered Oct 21 '22 05:10

Ratnadeep Bhattacharyya