How to connect flutter with MongoDB

随声附和 提交于 2020-07-23 10:38:12

问题


I have a website build with node js and MongoDB and I want to create a mobile app with flutter and I don't know how to connect flutter with MongoDB.

give me some code example.


回答1:


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

}



回答2:


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.




回答3:


As far I'm working with flutter,It's better to create a system that been built from Back-end and Front-end, Here I created an example, with flutter web and node Js in CentOS server:

https://github.com/nimr77/Nginx-with-flutter-mongoDb-and-Npm the Nodejs will be the interface between the server and the app, and the Nginx is the HTTP server, our Lovely flutter will be the website That will manage the database.

I hope it will help you !



来源:https://stackoverflow.com/questions/59924840/how-to-connect-flutter-with-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!