MongoDB with Flutter

MongoDB integration in Flutter with CRUD operations

MongoDB is one of the popular open-source NoSQL database. In this article, we will take a look at how we can use it in flutter apps.

In this example, we will use mongo_dart package which is a server-side driver library for MongoDB that is implemented in pure dart language. So let’s get started!

Installation

  1. Add the mongo_dart dependency to your pubspec.yaml file:
dependencies:
mongo_dart: ^0.4.4

2. Run the following command in the terminal to install it:

$ flutter pub get

3. Import the package:

import 'package:mongo_dart/mongo_dart.dart';

Implementation

The application which we will create will have a simple List of users. The user model will be as follows:

https://medium.com/media/4d366d2b746e36c0f869dbedd34e6ba1/href

Note that the id is of type ObjectId which is a mongo type.

Create a new file database.dart which will allow us to connect to the Mongo database and hold the CRUD operations.

Let’s create a new class MongoDatabase inside the file which we just created. First thing first, let’s connect to mongo database. Add the following method to connect to the database:

https://medium.com/media/682503e8d2cc351a5d3a4db9b2cbbe63/href

Here, we use the create() from the Db class provided by the library as pass the Mongo connection URL to it. The URL should be of the form:

"mongodb+srv://<USER>:<PASS>@<DB>/<COLLECTION>;

Next, we open the database with open() and get the collection in userCollection .

Create

Creating a new document is pretty straightforward. You just need to call the insertAll() of the collection which can insert multiple documents at once. Here we will only use it to insert a single document. This can be done as:

https://medium.com/media/292415acca3847b697bfef523d416858/href

Here, we just call the method and convert the User to map and pass it in a list.

Read

To read all the documents from Mongo, we need to use the find() on the collection. We also need to convert them into list so that it can be displayed on the UI. This can be done with the toList() that returns List of Map objects with String as key with dynamic type value.

https://medium.com/media/20b08299d7b22696e32c79c3f4d060cd/href

Here we also use simple try-catch statement to handle the empty results condition.

Update

To update a document, we find it by id using findOne(), assign new values and save it to the collection using save() .

https://medium.com/media/4607ce20cae19999707ab3908b1a2734/href

Delete

To delete a document, we call the remove() for the collection and pass the ObjectId using the where clause.

https://medium.com/media/4f40e5690ef171342303023aca77fe96/href

The article is kept simple so that you can focus on the concepts, you should NEVER write code like this in production apps.

With these methods in place, let’s quickly set up the pages required.

We will have the home page with list of users in a user card along with a floating action button which will lead us to page where we can add users. The user card will have edit and delete buttons. We will use FutureBuilder to get documents from the database.

https://medium.com/media/3bba9407e435b012e6be6d6735a7b894/href

The home screen looks like this:

This article only includes the necessary code for brevity, you can find the GitHub link to the full source code repository at the end of the article.

Let’s add a new page add_user_page.dart which will be used for both adding new users as well as updating existing users. Adding or updating the user will depend on the route arguments. The page will have three textField widgets one each for name, phone and age. The UI to add a user will look like this:

The methods to insert and update users will be:

https://medium.com/media/7fc1edc0389259b4212dfafeffa3974d/href

Note that we create a new id using the ObjectId() while inserting a new user but assign the same id while updating the user. We call corresponding insert and update methods from the class we created earlier.

The update UI looks like this:

The last step is to connect to the database when the app starts. This can be done like:

https://medium.com/media/cce3b4d7199aa2e9c163399dde960998/href

Here, we make the main() as async so that we can call the connect() to connect to the mongo database. That’s it we have a working flutter application with MongoDB as the database!

Conclusion

In this article, we explored how to use MongoDB in flutter and perform CRUD operations with a simple example.

The complete source code can be found on the link below:

harshshinde07/MongoDB-Flutter

Thanks for reading the article. If you enjoyed the article or learned something new, show your support by clapping as many times as possible. ?

It really motivates me to keep writing more! 🙂

Feel free to correct mistakes if there are any.

Let’s Connect:


MongoDB with Flutter was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Harshvardhan Shinde

MongoDB integration in Flutter with CRUD operations

MongoDB is one of the popular open-source NoSQL database. In this article, we will take a look at how we can use it in flutter apps.

In this example, we will use mongo_dart package which is a server-side driver library for MongoDB that is implemented in pure dart language. So let’s get started!

Installation

  1. Add the mongo_dart dependency to your pubspec.yaml file:
dependencies:
mongo_dart: ^0.4.4

2. Run the following command in the terminal to install it:

$ flutter pub get

3. Import the package:

import 'package:mongo_dart/mongo_dart.dart';

Implementation

The application which we will create will have a simple List of users. The user model will be as follows:

Note that the id is of type ObjectId which is a mongo type.

Create a new file database.dart which will allow us to connect to the Mongo database and hold the CRUD operations.

Let’s create a new class MongoDatabase inside the file which we just created. First thing first, let’s connect to mongo database. Add the following method to connect to the database:

Here, we use the create() from the Db class provided by the library as pass the Mongo connection URL to it. The URL should be of the form:

"mongodb+srv://<USER>:<PASS>@<DB>/<COLLECTION>;

Next, we open the database with open() and get the collection in userCollection .

Create

Creating a new document is pretty straightforward. You just need to call the insertAll() of the collection which can insert multiple documents at once. Here we will only use it to insert a single document. This can be done as:

Here, we just call the method and convert the User to map and pass it in a list.

Read

To read all the documents from Mongo, we need to use the find() on the collection. We also need to convert them into list so that it can be displayed on the UI. This can be done with the toList() that returns List of Map objects with String as key with dynamic type value.

Here we also use simple try-catch statement to handle the empty results condition.

Update

To update a document, we find it by id using findOne(), assign new values and save it to the collection using save() .

Delete

To delete a document, we call the remove() for the collection and pass the ObjectId using the where clause.

The article is kept simple so that you can focus on the concepts, you should NEVER write code like this in production apps.

With these methods in place, let’s quickly set up the pages required.

We will have the home page with list of users in a user card along with a floating action button which will lead us to page where we can add users. The user card will have edit and delete buttons. We will use FutureBuilder to get documents from the database.

The home screen looks like this:

This article only includes the necessary code for brevity, you can find the GitHub link to the full source code repository at the end of the article.

Let’s add a new page add_user_page.dart which will be used for both adding new users as well as updating existing users. Adding or updating the user will depend on the route arguments. The page will have three textField widgets one each for name, phone and age. The UI to add a user will look like this:

The methods to insert and update users will be:

Note that we create a new id using the ObjectId() while inserting a new user but assign the same id while updating the user. We call corresponding insert and update methods from the class we created earlier.

The update UI looks like this:

The last step is to connect to the database when the app starts. This can be done like:

Here, we make the main() as async so that we can call the connect() to connect to the mongo database. That’s it we have a working flutter application with MongoDB as the database!

Conclusion

In this article, we explored how to use MongoDB in flutter and perform CRUD operations with a simple example.

The complete source code can be found on the link below:

harshshinde07/MongoDB-Flutter

Thanks for reading the article. If you enjoyed the article or learned something new, show your support by clapping as many times as possible. ?

It really motivates me to keep writing more! :)

Feel free to correct mistakes if there are any.

Let’s Connect:


MongoDB with Flutter was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Harshvardhan Shinde


Print Share Comment Cite Upload Translate Updates
APA

Harshvardhan Shinde | Sciencx (2021-07-25T14:23:05+00:00) MongoDB with Flutter. Retrieved from https://www.scien.cx/2021/07/25/mongodb-with-flutter/

MLA
" » MongoDB with Flutter." Harshvardhan Shinde | Sciencx - Sunday July 25, 2021, https://www.scien.cx/2021/07/25/mongodb-with-flutter/
HARVARD
Harshvardhan Shinde | Sciencx Sunday July 25, 2021 » MongoDB with Flutter., viewed ,<https://www.scien.cx/2021/07/25/mongodb-with-flutter/>
VANCOUVER
Harshvardhan Shinde | Sciencx - » MongoDB with Flutter. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/25/mongodb-with-flutter/
CHICAGO
" » MongoDB with Flutter." Harshvardhan Shinde | Sciencx - Accessed . https://www.scien.cx/2021/07/25/mongodb-with-flutter/
IEEE
" » MongoDB with Flutter." Harshvardhan Shinde | Sciencx [Online]. Available: https://www.scien.cx/2021/07/25/mongodb-with-flutter/. [Accessed: ]
rf:citation
» MongoDB with Flutter | Harshvardhan Shinde | Sciencx | https://www.scien.cx/2021/07/25/mongodb-with-flutter/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.