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.
Actually, I publish a blog about it feel free to check the solution!
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.
Today, we are pleased to announce the next installment of the Realm Flutter SDK – now with support for Windows, macOS, iOS, and Android.
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.
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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With