How to Create a Favourite Product Function in Flutter
Tags: flutter, appwrite, mobileapp, dart
Published: 2022-08-22 10:11:35

---
title: How to Create a Favourite Product Function in Flutter
published: true
description: Learn how to create a favourite product feature in Flutter using Appwrite’s database for storage.
tags: #Flutter #Appwrite #mobileapp #dart
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dnn8bgly1upsnld5ohge.png
# Use a ratio of 100:42 for best results.
---
Most digital platform services offer “**Add to Favo****u****rite**” functionality to their products. It allows users to save, streamline, and prioritise their experience using said platform.

In this post, we will learn how to create a favourite product feature in Flutter using Appwrite’s database for storage.

## Prerequisites

To fully grasp the concepts presented in this tutorial, we require the following:

- Basic understanding of Dart and Flutter
- Flutter [SDK](https://flutter.dev/docs/get-started/install) installed
- [Xcode](https://developer.apple.com/xcode/) with a developer account (for Mac users)
- Either [IOS Simulator](https://developer.apple.com/documentation/xcode/running-your-app-in-the-simulator-or-on-a-device), [Android Studio](https://developer.android.com/studio), or [Chrome web browser](https://support.google.com/chrome/answer/95346?hl=en-GB&co=GENIE.Platform%3DDesktop) to run our application
- Docker [installation](https://www.docker.com/get-started/)
- An Appwrite instance; check out this [article](https://dev.to/hackmamba/create-a-local-appwrite-instance-in-3-steps-19n9?utm_source=hackmamba&utm_medium=hackmamba) on how to set up an instance locally or one-click install on [DigitalOcean](https://marketplace.digitalocean.com/apps/appwrite)

## Getting Started

In this post, we will focus on implementations only. The project UI has already been set up.

To get started, we need to clone the project by navigating to the desired directory and running the command below:

```bash
    git clone https://github.com/Mr-Malomz/product_fav.git && cd product_fav
```

The complete source code is also available on the [**dev**](https://github.com/Mr-Malomz/product_fav/tree/dev) branch of the same repository.

## Running the Project

First, we need to install the project dependencies by running the command below:
```bash
    flutter pub get
```
Then run the project using the command below:
```bash
    flutter run
```
The command above will run the application on the selected device.

![Home Screen](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657816492174_Screenshot+2022-07-13+at+09.35.31.png)
![Favourite Screen](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657816492191_Screenshot+2022-07-13+at+09.35.52.png)

## Creating a New Appwrite Project

To create a new project, start the Appwrite instance and navigate to the specified hostname and port `http://localhost:80`. Next, we need to log into our account or create an account if we don’t have one. 


![Appwrite Running](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650158621491_screencapture-localhost-auth-signup-2022-04-17-02_22_56.png)


On the console, click on the **Create Project** button, input `product_feature` as the name, and click **Create**.

![Create Project](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650159125946_Screenshot+2022-04-17+at+02.28.39.png)
![Enter Project Name](https://paper-attachments.dropbox.com/s_BDB4B2E9DEBC947CF21789BC4224D1B5D1E6999B18844A1ABC22F2142E2E2A61_1653953612228_Screenshot+2022-05-30+at+15.00.51.png)


Next, we need to create a database to save our product features. Navigate to the **Database** tab, click **Add Database**, input `products` as the database name, and click **Create**.

![Click on Add Database](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657817537975_Screenshot+2022-07-14+at+17.50.40.png)
![Enter Database Name & Enter](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657817547622_Screenshot+2022-07-14+at+17.52.06.png)


With that done, we need to create a collection for grouping our products. Click on **Add Collection**, input `product_list` as the collection name, and click on **Create**.

![Click on Add Collection](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650179872134_Screenshot+2022-04-17+at+08.09.34.png)
![Enter Collection Name & Create](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657817955690_Screenshot+2022-07-13+at+10.21.14.png)


Appwrite has an advanced yet flexible way to manage access to users, teams, or roles to access specific resources. We will modify the permission `role:all` to enable access from any application. Then click on **Update** to save changes.

![Modify Permission](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657844341998_Screenshot+2022-07-13+at+10.21.59.png)

## Add Attributes

Attributes are fields that our database will possess. Navigate to the Attributes tab, click on **Add Attributes**, add a `New String Attribute` and size of `1000` for both **title** and **description** fields with the `required` option marked, and `New Boolean Attribute` for **isFav** also marked as **required**, and click on **Create**.

![Select Attribute](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650181607632_Screenshot+2022-04-17+at+08.41.22.png)
![Create Field](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650181638011_Screenshot+2022-04-17+at+08.45.03.png)

## Add Sample Data

To get a feel for our database, we can add sample data by navigating to the **Documents** tab, clicking on **Add Document**, inputting the required fields, and clicking on **Create**.

![Add Document](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657829103749_Screenshot+2022-07-13+at+13.01.49.png)
![Input Fields and Create](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657829153280_Screenshot+2022-07-13+at+11.49.06.png)


**Sample Product Data**

| **title**          | **description**                                                                                                                    | **isFav** |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | --------- |
| iPhone 9           | An apple mobile which is nothing like apple                                                                                        | false     |
| iPhone X           | SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...                              | false     |
| Samsung Universe 9 | Samsung's new variant which goes beyond Galaxy to the Universe                                                                     | false     |
| OPPOF19            | OPPO F19 is officially announced on April 2021.                                                                                    | false     |
| Huawei P30         | Huawei’s re-badged P30 Pro New Edition was officially unveiled yesterday in Germany and now the device has made its way to the UK. | false     |
| MacBook Pro        | MacBook Pro 2021 with mini-LED display may launch between September, November                                                      | false     |

## Add Index

Indexes in a database improve the speed of data retrieval. Navigate to the **Indexes** tab, click on **Add Index**, input `isFav` as the index key, select `isFav` from the Attributes dropdown, and click on **Create**.

![](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657829891109_Screenshot+2022-07-13+at+13.03.45.png)




## Connecting Appwrite to Flutter

To add support for our Flutter app, navigate to the **Home** menu, click on the **Add Platform** button, and select **New Flutter App**.

![Add Platform](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650183238195_Screenshot+2022-04-17+at+09.11.20.png)
![Select New Flutter App](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650183238206_Screenshot+2022-04-17+at+09.12.40.png)


Depending on the device we are running our Flutter application, we can modify it as shown below.

**i****OS**
To obtain our Bundle ID, we can navigate using the path below:
**ios > Runner.xcodeproj > project.pbxproj**

Open the `project.pbxproj` file, and search for `PRODUCT_BUNDLE_IDENTIFIER`.

![iOS](https://paper-attachments.dropbox.com/s_8EFF1B60DFE36B93FEF6E1F360D9B02058A7F0176A6FBB3402F95D5C617D66C1_1652741900395_Screenshot+2022-05-16+at+23.57.24.png)


Next, open the project directory on [Xcode](https://developer.apple.com/xcode/), open the `Runner.xcworkspace` folder in the app's iOS folder, select the Runner project in the Xcode project navigator, select the Runner target in the main menu sidebar, and then select **i****OS 11** in the deployment info’s target.

![Change Deployment Target](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650208061820_Screenshot+2022-04-17+at+16.05.22.png)


**Android**
To get our package name, we can navigate using the path below:
**android > app > src > debug > AndroidManifest.xml**

Open the `AndroidManifest.xml` file, and copy the `package` value.

![Android](https://paper-attachments.dropbox.com/s_8EFF1B60DFE36B93FEF6E1F360D9B02058A7F0176A6FBB3402F95D5C617D66C1_1652741912183_Screenshot+2022-05-16+at+23.58.09.png)


Next, we need to modify the `AndroidManifext.xml` as shown below:
```xml
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.product_fav">
        <uses-permission android:name="android.permission.INTERNET"/>
        <application ...>
        <activity android:name="com.linusu.flutter_web_auth.CallbackActivity" android:exported="true">
          <intent-filter android:label="flutter_web_auth">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="appwrite-callback-[PROJECT_ID]" />
          </intent-filter>
        </activity>
      </application>
    </manifest>
```

Then, we need to navigate to the `lib` directory and create a `utils.dart` file and add the snippet below:
```dart
    class AppConstant {
      final String databaseId = "REPLACE WITH YOUR DATABASE ID";
      final String projectId = "REPLACE WITH YOUR PROJECT ID";
      final String endpoint = "REPLACE WITH YOUR ENPOINT";
      final String collectionId = "REPLACE WITH YOUR COLLECTION ID";
    }
```
Navigate to the **Database** menu, click on the `Products` database, click on the **Settings** tab, and copy the `Database ID`.

![Copy Database ID](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657831750553_Screenshot+2022-07-14+at+21.48.31.png)


Switch to the **Collections** tab, click on the `product_list` collection, click on the **Settings** tab, and copy the `Collection ID`.

![Click on the product_list](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657832233698_Screenshot+2022-07-14+at+21.53.30.png)
![Copy the Collection ID](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657832233709_Screenshot+2022-07-14+at+21.56.23.png)


Navigate to the **Settings** menu to copy the `Project ID` and `API Endpoint`.

![Copy Project ID and API Endpoint](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657831905105_Screenshot+2022-07-14+at+21.50.50.png)



For the `endpoint` property, we need to modify it to work with our system's local network address. We can adjust accordingly:

**i****OS**
Navigate to the **Network** section, copy the IP address, and modify it as shown below:
```dart
    class AppConstant {
      final String databaseId = "REPLACE WITH YOUR DATABASE ID";
      final String projectId = "REPLACE WITH YOUR PROJECT ID";
      final String endpoint = "http://192.168.1.195/v1";
      final String collectionId = "REPLACE WITH YOUR COLLECTION ID";
    }
```

![](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650365320233_Screenshot+2022-04-18+at+19.38.08.png)


**Android**
We can connect our Android emulator to the system’s IP using the `10.0.2.2` IP address.
```dart
    class AppConstant {
      final String databaseId = "REPLACE WITH YOUR DATABASE ID";
      final String projectId = "REPLACE WITH YOUR PROJECT ID";
      final String endpoint = "http://10.0.2.2/v1";
      final String collectionId = "REPLACE WITH YOUR COLLECTION ID";
    }
```

## Building the Favourite Product Feature

To get started, we need to create a model to convert the response sent from Appwrite to a Dart object. The model will also cater to JSON serialization. To do this, add the snippet below in the same `utils.dart` file:
```dart
    class AppConstant {
      //code goes here
    }
    
    class Product {
      String? $id;
      String title;
      String description;
      bool isFav;
    
      Product({
        this.$id,
        required this.title,
        required this.description,
        required this.isFav,
      });
    
      factory Product.fromJson(Map<dynamic, dynamic> json) {
        return Product(
          $id: json['\$id'],
          title: json['title'],
          description: json['description'],
          isFav: json['isFav'],
        );
      }
    
      Map<dynamic, dynamic> toJson() {
        return {'title': title, 'description': description, 'isFav': isFav};
      }
    }
```
The snippet above does the following:

- Creates a `Product` class with required properties
- Adds a constructor with unrequired and required parameters
- Creates a `fromJson` and `toJson` method for JSON serialization

Next, we need to create a service file to separate the application core logic from the UI. To do this, create a `product_service.dart` file inside the `lib` directory and update it by doing the following:
```dart
    import 'package:appwrite/appwrite.dart';
    import 'package:product_fav/utils.dart';
    
    class ProductService {
      Client client = Client();
      Databases? db;
    
      ProductService() {
        _init();
      }
    
      //initialize the application
      _init() async {
        client
            .setEndpoint(AppConstant().endpoint)
            .setProject(AppConstant().projectId);
        db = Databases(client, databaseId: AppConstant().databaseId);
    
        //get current session
        Account account = Account(client);
    
        try {
          await account.get();
        } on AppwriteException catch (e) {
          if (e.code == 401) {
            account
                .createAnonymousSession()
                .then((value) => value)
                .catchError((e) => e);
          }
        }
      }
    
      Future<List<Product>> getAllProducts() async {
        try {
          var data =
              await db?.listDocuments(collectionId: AppConstant().collectionId);
          var productList = data?.documents
              .map((product) => Product.fromJson(product.data))
              .toList();
          return productList!;
        } catch (e) {
          throw Exception('Error getting list of products');
        }
      }
    
      Future<List<Product>> getAllFavourites() async {
        try {
          var data = await db?.listDocuments(
              collectionId: AppConstant().collectionId,
              queries: [Query.equal('isFav', true)]);
          var favList =
              data?.documents.map((fav) => Product.fromJson(fav.data)).toList();
          return favList!;
        } catch (e) {
          throw Exception('Error getting list of favourites');
        }
      }
    
      Future addAsFav(
          String title, String description, String id, bool isFav) async {
        try {
          Product updateProduct =
              Product(title: title, description: description, isFav: isFav);
          var data = await db?.updateDocument(
            collectionId: AppConstant().collectionId,
            documentId: id,
            data: updateProduct.toJson(),
          );
          return data;
        } catch (e) {
          throw Exception('Error updating product');
        }
      }
    }
```

The snippet above does the following:

- Imports the required dependencies
- Creates a `ProductService` class with `client` and `db` properties to connect to the Appwrite instance and the database, respectively
- Creates an `_init` method that configures the Appwrite using the property and also conditionally creates an anonymous user to access Appwrite
- Creates a `getAllProducts` method that uses the configured database’s `listDocuments` function to get a list of products and converts the returned JSON to a list using the `Product.fromJson` method
- Creates a `getAllFavourites` method that uses the configured database’s `listDocuments` function to get a list of products marked as favourite and converts the returned JSON to a list using the `Product.fromJson` method. This method also uses the `isFav` index we created earlier to retrieve products matching the query optimally.
- Creates an `addAsFav` method that takes in the `title`, `description`, and `isFav` parameter and uses the `updateDocument` function to update a product; this creates an instance of the product using the `title`, `description`, and `isFav` parameter, passes in the `id` as the `documentId`, and passes in the updated note by converting the Dart object to JSON using the `updateProduct.toJson()` method


## Consuming the Service

With that done, we can start using the service to perform the required operation.

**Get** **the L****ist of Product****s** **and Add to Favo****u****rite****s**
To get the list of products, we need to navigate to the `screens` folder, open the `home.dart` and modify as shown below:
```dart
    import 'package:flutter/material.dart';
    import 'package:product_fav/product_service.dart'; //add this
    import 'package:product_fav/utils.dart'; //add this
    
    class Home extends StatefulWidget {
      const Home({Key? key}) : super(key: key);
      @override
      State<Home> createState() => _HomeState();
    }
    class _HomeState extends State<Home> {
      List<Product>? products;
      bool _isLoading = false;
      bool _isError = false;
    
      @override
      void initState() {
        _getProductList();
        super.initState();
      }
    
      _getProductList() {
        setState(() {
          _isLoading = true;
        });
        ProductService().getAllProducts().then((value) {
          setState(() {
            products = value;
            _isLoading = false;
          });
        }).catchError((e) {
          setState(() {
            _isLoading = false;
            _isError = true;
          });
        });
      }
    
      _addAsFavourite(
          String title, String description, String id, bool isFav, int index) {
        ProductService().addAsFav(title, description, id, isFav).then((value) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('favourites updated successfully!')),
          );
          setState(() {
            products![index].isFav = isFav;
          });
        }).catchError((e) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Error adding favourite!')),
          );
        });
      }
    
      @override
      Widget build(BuildContext context) {
        //widget code goes here
      }
    }
  ```  

The snippet above does the following:

- Imports the required dependencies 
- Creates a `products`, `_isLoading`, and `_isError` properties to manage the application state
- Creates a `_getProductList` method to get the list of products using the `getAllProducts` service and sets states accordingly
- Uses the `initState`  method to call the `_getProductList` method when the object is inserted into the tree
- Creates a `_addAsFavourite` method that takes in the `title`, `description`, `id`, and `index` as a parameter and uses the `addAsFav` service to mark the selected product as a favourite, updates the UI using the `setState` method, and uses the `snackbar` to show the action performed

Next, we can modify the UI widgets to show the products coming from Appwrite.
```dart
    //imports goes here
    
    class Home extends StatefulWidget {
      const Home({Key? key}) : super(key: key);
      @override
      State<Home> createState() => _HomeState();
    }
    class _HomeState extends State<Home> {
      //properties goes here
    
      @override
      void initState() {
        _getProductList();
        super.initState();
      }
    
      _getProductList() {
        //code goes here
      }
    
      _addAsFavourite(
         //code goes here
      }
    
      @override
      Widget build(BuildContext context) {
        return _isLoading
            ? const Center(
                child: CircularProgressIndicator(
                color: Colors.blue,
              ))
            : _isError
                ? const Center(
                    child: Text(
                      'Error loading products',
                      style: TextStyle(
                        color: Colors.red,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  )
                : ListView.builder(
                    itemCount: products?.length,
                    itemBuilder: (context, index) {
                      return InkWell(
                        onTap: () {
                          var isFav =
                              products![index].isFav == false ? true : false;
                          _addAsFavourite(
                            products![index].title,
                            products![index].description,
                            products![index].$id!,
                            isFav,
                            index,
                          );
                        },
                        child: Container(
                          decoration: const BoxDecoration(
                            border: Border(
                              bottom: BorderSide(width: .5, color: Colors.grey),
                            ),
                          ),
                          padding: EdgeInsets.fromLTRB(10, 20, 10, 20),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Expanded(
                                flex: 7,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      products![index].title,
                                      style: TextStyle(
                                          color: Colors.blue,
                                          fontWeight: FontWeight.w800),
                                    ),
                                    SizedBox(height: 10.0),
                                    Text(products![index].description)
                                  ],
                                ),
                              ),
                              Icon(
                                products![index].isFav
                                    ? Icons.favorite
                                    : Icons.favorite_border,
                                color: products![index].isFav
                                    ? Colors.red
                                    : Colors.grey,
                              )
                            ],
                          ),
                        ),
                      );
                    },
                  );
      }
    }
```

**Get the List of Favourite Products**
To get the list of products added as a favourite, we need to open the `favourite.dart` file in the same `screens` folder and modify as shown below:
```dart
    import 'package:flutter/material.dart';
    import 'package:product_fav/product_service.dart'; //add this
    import 'package:product_fav/utils.dart'; //add this
    
    class Favourites extends StatefulWidget {
      const Favourites({Key? key}) : super(key: key);
      @override
      State<Favourites> createState() => _FavouritesState();
    }
    class _FavouritesState extends State<Favourites> {
      List<Product>? favourites;
      bool _isLoading = false;
      bool _isError = false;
    
      @override
      void initState() {
        _getFavList();
        super.initState();
      }
    
      _getFavList() {
        setState(() {
          _isLoading = true;
        });
        ProductService().getAllFavourites().then((value) {
          setState(() {
            favourites = value;
            _isLoading = false;
          });
        }).catchError((e) {
          setState(() {
            _isLoading = false;
            _isError = true;
          });
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return _isLoading
            ? const Center(
                child: CircularProgressIndicator(
                color: Colors.blue,
              ))
            : _isError
                ? const Center(
                    child: Text(
                      'Error loading products',
                      style: TextStyle(
                        color: Colors.red,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  )
                : favourites!.isEmpty
                    ? const Center(
                        child: Text(
                          'No items added to favourites yet',
                          style: TextStyle(
                            color: Colors.grey,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      )
                    : ListView.builder(
                        itemCount: favourites?.length,
                        itemBuilder: (context, index) {
                          return Container(
                            decoration: const BoxDecoration(
                              border: Border(
                                bottom: BorderSide(width: .5, color: Colors.grey),
                              ),
                            ),
                            padding: EdgeInsets.fromLTRB(10, 20, 10, 20),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                Expanded(
                                  flex: 7,
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        favourites![index].title,
                                        style: TextStyle(
                                            color: Colors.blue,
                                            fontWeight: FontWeight.w800),
                                      ),
                                      SizedBox(height: 10.0),
                                      Text(favourites![index].description)
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      );
      }
    }
```

The snippet above does the following:

- Imports the required dependencies 
- Creates the `favourites`, `_isLoading`, and `_isError` properties to manage the application state
- Creates a `_getFavList` method to get the list of products marked as favourite using the `getAllFavourites` service and sets states accordingly
- Uses the `initState`  method to call the `_getProductList` method when the object is inserted into the tree
- Modifies the UI widgets to show the products marked as favourite coming from Appwrite


With that done, we restart the application using the code editor or run the command below:
```bash
    flutter run
```

![](https://media.giphy.com/media/ItWBIOloZWfI6O4o0Q/giphy.gif)


We can also validate the entries by navigating to the **Database** section of Appwrite’s management console.

![Data on Appwrite](https://paper-attachments.dropbox.com/s_1AF7D1BE0ADF7EDE6E675290822A2A4A6CAEEB0CB3D05C84CB9D946F913A7CD3_1657836507167_Screenshot+2022-07-13+at+22.14.25.png)

# Conclusion

This post discussed how to create a favourite product feature in Flutter using Appwrite’s database for storage. The Appwrite platform ships with services that speed up development processes. Try it out today and focus on what matters while Appwrite takes care of the tricky part.

These resources might be helpful:

- [Appwrite official documentation](https://appwrite.io/docs?utm_source=hackmamba&utm_medium=hackmamba-blog)
- [Appwrite Flutter SDK](https://appwrite.io/docs/getting-started-for-flutter?utm_source=hackmamba&utm_medium=hackmamba-blog)
- [Appwrite support for Indexes](https://appwrite.io/docs/databases#indexes?utm_source=hackmamba&utm_medium=hackmamba-blog)
- [Flutter null safety](https://dart.dev/null-safety)