CRUD operations: Overview and how to perform it using Flutter in Firestore

When we are building APIs, we want our models to provide the basic types of functionality, so you would want to make sure that your module can perform the best. As a result, you may have a broad experience when it comes to software development. So, if you have a chance to work with a variety of different databases, you might encounter working with CRUD operations – one of the main ways of building the basic store.

A model should have the ability to perform at most basic functions in order to be complete. Also, since SQL is pretty prominent in the development community, it’s crucial for developers to understand how CRUD operations work. So, we would like to provide you with this article, with a view to bringing you up to speed on this term of CRUD definition programming, and how to perform it using Flutter in Firestore.

Overview of CRUD operations

CRUD definition programming

What are CRUD operations?
CRUD definition

Within computer programming, the acronym CRUD stands for create, read, update and delete. These are the four basic functions of persistent storage in CRUD definition programming. Also, each letter in the acronym can refer to all functions executed in relational database applications and mapped to a standard HTTP method, SQL statement or DDS operation. This is common in constructing web applications because it can remind developers of how to construct full, usable models.

Structure breakdown

As mentioned above, there are 4 basic types of functionality in CRUD definition programming. So, to make this library system usable, we would want to make sure there were clear mechanisms. Here’s the breakdown:

  • Create procedures: Performs the INSERT statement to create a new record.
  • Read procedures: Reads the table records based on the primary keynoted within the input parameter.
  • Update procedures: Executes an UPDATE statement on the table based on the specified primary key for a record within the WHERE clause of the statement.
  • Delete procedures: Deletes a specified row in the WHERE clause.

Benefits of CRUD operations

Instead of using ad-hoc SQL statements, many programmers prefer to use CRUD because of its performance. When a stored procedure is first executed, the execution plan is stored in SQL Server’s procedure cache and reused for all applications of the stored procedure. If an execution plan is not available, then the SQL Server will create a new execution plan for the query. 

CRUD Operations in Modern JavaScript - DEV
The benefits of this procedure

Moreover, using CRUD operations helps to prevent SQL injection attacks. By utilizing stored procedures instead of string concatenation to build dynamic queries from user input data for all SQL Statements means that everything placed into a parameter gets quoted.

How to perform CRUD operations using Flutter in Firestore?

Let’s assume that your project’s setup is complete, and we only focus on the coding phase. If you start without the setup, then there’s a variety of options that you guys can go to Github. The coding phase starts now.

How to perform CRUD operations using Flutter in Firestore?
How to perform CRUD operations?

Step #0: Code Setup

Let’s quickly go over the structure. The lib folder is divided into two folders. core and UI. Core contains all the files associated with the logic. UI contains all the files associated with the UI. Core is divided into three folders.

  • Models: Contains all the plain data models
  • Services: Contains the dedicated files that will handle actual business logic
  • ViewModels: Contains the Provider models for each of the Widget views

Also, UI is divided into three folders:

  • Shared: Contains files used in multiple other UI files
  • Views: Contains the files for the app views
  • Widgets: Contains widget files that are too big to keep in the view files.

Step #1: Create model class

Our application using CRUD operations will need a Product model so under models we will create productModel.dartfile. This file contains 2 methods :

  • Product.fromMap(Map snapshot, String id): When data is fetched from Firebase, it is in JSON format. this method allows us to map data from JSON format to our Product format.
  • toJson() : The toJson() does the opposite which is to map the data back into JSON format before we upload it into Firebase.

Step #2: Create API class

Under our Services directory will perform all the Network work. So, we will Create an API class that will request/read/delete/update data from Firebase. That class will contain different methods like fetching data as a stream, getting the document by id, removing/deleting a document, etc. The coding should go something a little bit like this:

class Api{
  final Firestore _db = Firestore.instance;
  final String path;
  CollectionReference ref;

  Api( this.path ) {
    ref = _db.collection(path);

  }
  Future<QuerySnapshot> getDataCollection() {
    return ref.getDocuments() ;
  }
  Stream<QuerySnapshot> streamDataCollection() {
    return ref.snapshots() ;
  }
  Future<DocumentSnapshot> getDocumentById(String id) {
    return ref.document(id).get();
  }
  Future<void> removeDocument(String id){
    return ref.document(id).delete();
  }
  Future<DocumentReference> addDocument(Map data) {
    return ref.add(data);
  }
  Future<void> updateDocument(Map data , String id) {
    return ref.document(id).updateData(data) ;
  }


}

As mentioned above, we will not be providing a bunch of models and services at the beginning of our app using CRUD operations at the global context scale. Instead, we’ll inject it using the locator setup in locator.dart.

Step #3: Create CRUD operations model

The CRUD operations Model will use the API class to Handle the different operations. Under viewmodels, create the CRUDModel.dart file and add the different functions needed. This model (as well as every other service and model) will be injected using the locator. After that, we register it in the locator file. The code should be briefly like this:

void setupLocator() {
  locator.registerLazySingleton(() => Api('products'));
  locator.registerLazySingleton(() => CRUDModel()) ;
}

Step #4: Routing and main configuration

To keep things nice and clean when having CRUD operations, we’ll put all the routing in a separate file called router.dart under the UI folder his function receives RouteSettings which contains the name of the route being requested. We’ll also return an error view for any undefined route. Then, under the main file, we will provide the onGenerateRoute property with the static generateRoute function from the Router. It should be like this:

void main() {
  setupLocator();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(builder: (_) => locator<CRUDModel>()),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        initialRoute: '/',
        title: 'Product App',
        theme: ThemeData(),
        onGenerateRoute: Router.generateRoute,
      ),
    );
  }
}

Step #5: Dig deep into the visual of the CRUD operations app

In HomeView.dartwe will fetch different products from the collection products and display them in cards. Then, we will create ProductCard() to display the details of the product. The code should go something like this:

import 'package:flutter/material.dart';
import 'package:productapp/core/models/productModel.dart';
import 'package:productapp/ui/views/productDetails.dart';


class ProductCard extends StatelessWidget {
  final Product productDetails;

  ProductCard({@required this.productDetails});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        Navigator.push(context, MaterialPageRoute(builder: (_) => ProductDetails(product: productDetails)));
      },
      child: Padding(
        padding: EdgeInsets.all(8),
        child: Card(
          elevation: 5,
          child: Container(
            height: MediaQuery
                .of(context)
                .size
                .height * 0.45,
            width: MediaQuery
                .of(context)
                .size
                .width * 0.9,
            child: Column(
              children: <Widget>[
                Hero(
                  tag: productDetails.id,
                  child: Image.asset(
                    'assets/${productDetails.img}.jpg',
                    height: MediaQuery
                        .of(context)
                        .size
                        .height *
                        0.35,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.all(16),
                  child: Row(
                    mainAxisAlignment:
                    MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        productDetails.name,
                        style: TextStyle(
                            fontWeight: FontWeight.w900,
                            fontSize: 22,
                            fontStyle: FontStyle.italic),
                      ),
                      Text(
                        '${productDetails.price} \$',
                        style: TextStyle(
                            fontWeight: FontWeight.w900,
                            fontSize: 22,
                            fontStyle: FontStyle.italic,
                            color: Colors.orangeAccent),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Then, to create a new Product item, we will take the name input and price by the user. To do this, we instantiate a new Product object. Finally, we upload to Firebase using our addProduct() function called using the CRUD operations provider. And that’s when we complete the procedure.

Final words

That should be it! Here are the overview of CRUD operations and the steps on how to perform it using Flutter in Firestore. All in all, though there are many other things to add on, this process is where you want to start in the most basic term. As you get more practice with designing storage systems, incorporating CRUD operations into your models will become easier and easier using Flutter in Firestore.

We – ArrowHiTech is proud to be one of the most well-established outsourcing companies all around the world. That is to say, with over 12 years of experience, you can take a look our Customized Flutter App Development Services for your eCommerce business.

Vietnam Software Outsourcing Company | ArrowHiTech Jsc

Also, check out our Mobile Application and Web Application Development Services 

Tags

Share