Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Maintain Activity Log in Firebase Using FlutterFlow

Monitoring changes in your application’s data is essential for auditing, troubleshooting, and ensuring transparency for users. We’ll concentrate on a real-world example involving the Tasks and Activity_log collections. We’ll walk you through the process of reading the previous task document, updating it, comparing the two, identifying any discrepancies, and writing these modifications to the Activity_log collection.

This blog will explore Maintain an Activity Log in Firebase using FlutterFlow. We will see how to work on a detailed guide for your Flutterflow applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents:

Introduction

Requirements

Setting Up Firebase and FlutterFlow

Creating Collections and Data Models In FlutterFlow

Implementing the Action Flow

Creating the Custom Function

Implementing Function Code

Conclusion



Introduction:

It is essential to keep a record of changes made by users to tasks within your application. We’ll achieve this by:

  • Examining the previous Firebase task document.
  • Updating the Firebase task document.
  • Examining the Firebase task document that has been updated
  • Calculating the differences between the both documents.
  • Adding the modifications to Firebase’s Activity_log collection.

A transparent and observable record of all task modifications is made possible by this procedure.

Requirements:

  • Create a FlutterFlow account by visiting FlutterFlow.
  • Firebase Project: Link your FlutterFlow application to a Firebase project.
  • Basic Knowledge: Knowledge of Dart programming, Firebase Firestore, and FlutterFlow.

Setting Up Firebase and FlutterFlow:

Connecting FlutterFlow to Firebase:-

  • Open your project in FlutterFlow.
  • Go to Settings > Firebase.
  • After selecting Connect to Firebase, adhere to the instructions.
  • In your Firebase console, enable the Firestore Database.

Creating Collections and Data Models In FlutterFlow:

=> Tasks Collection: The task documents are kept in this collection.

Fields:-

  1. title (String)
  2. description (String)
  3. status (String)
  4. assigned_to (String)
  5. due_date (Timestamp)

=> Activity_log Collection: Task modification logs are kept in this collection.

Fields:-

  1. task_id (DocumentReference) – The task document’s reference..
  2. changes (Map<String, dynamic>) – The differences are contained in modifications.
  3. timestamp (Timestamp)
  4. modified_by (String) – name or User ID.

=> Creating Data Models:

  • Using the left panel, select Firestore.
  • Create Tasks and Activity_log after selecting + Add Collection.
  • As stated before, define the fields for every collection.

Implementing the Action Flow:

The action flow will be applied to the Submit button that is used to modify a task.
=> Overview of Actions

  • Custom Function: Log changes and compare documents.
  • Get Document: Fetch previous task data.
  • Update Document: Make changes to the Firestore task.
  • Get Document: Fetch current task data.

1: Read Old Task Document

Action: Retrieve the Firestore document

  • In your user interface, select the Submit button.
  • Click + Add Action after selecting Actions.
  • Firestore > Get Document is the option.
  • Set the current task document as the Document Reference.
    — Make use of Set from Variable > Task Reference > Widget State.
  • Save the document to a variable in the local state:
    — Make a variable of type Map with the name oldTaskData.

2: Update Task Document

Action: Update the document in Firestore.

  • Once the old document has been retrieved, add another action.
  • Select Update Document under Firestore.
  • Set the current task’s Document Reference.
  • Use the updated data from input widgets to map the fields.
  1. title: Derived from TitleController.text in Widget State
  2. description: Retrieved from DescriptionController.text in Widget State
  3. status: Retrieved from StatusDropdown.value in Widget State
  4. due_date: Set from Widget State > DueDatePicker.value.

3: Read Updated Task Document

Action: Get the Firestore document.

  • After the document has been updated, add another action.
  • Select Firestore > Retrieve Document.
  • Assign the current task as the Document Reference.
  • To a local state variable, save the document:
    — Make a variable of type Map with the name newTaskData.

4: Compare Documents and Log Changes

We’ll compare oldTaskData and newTaskData using a custom function.

Action: Custom Function

  • Once the new document has been retrieved, add another action.
  • Select Custom Function > logTaskChanges (this will be created later).
  • Configure the parameters:
  1. oldDataoldTaskData
  2. newDatanewTaskData
  3. taskIdcurrentTaskReference.id

Creating the Custom Function:

Defining the Custom Function

  1. Select Custom Functions from the panel on the left.
  2. Press the + Add Custom Function button.
  3. Give it the name logTaskChanges.
  4. Specify the parameters:
  • oldData (Map<String, dynamic>)
  • newData (Map<String, dynamic>)
  • taskId (String)

Implementing Function Code:

The Dart code for the custom function is as follows:

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> logTaskChanges(
  Map<String, dynamic> oldData,
  Map<String, dynamic> newData,
  String taskId,
) async {
  final differences = <String, Map<String, dynamic>>{};
  oldData.forEach((key, oldValue) {
    final newValue = newData[key];
    if (oldValue != newValue) {
      differences[key] = {
        'old_value': oldValue,
        'updated_value': newValue,
      };
    }
  });
  if (differences.isNotEmpty) {
    await FirebaseFirestore.instance.collection('Activity_log').add({
      'task_id': FirebaseFirestore.instance.doc('Tasks/$taskId'),
      'changes': differences,
      'timestamp': FieldValue.serverTimestamp(),
      'modified_by': /* Provide User ID or Name */,
    });
  }
}

Adding User Identification

Modify the function to include the user’s ID or name who made the changes.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

Future<void> logTaskChanges(
  Map<String, dynamic> oldData,
  Map<String, dynamic> newData,
  String taskId,
) async {
  final differences = <String, Map<String, dynamic>>{};
  oldData.forEach((key, oldValue) {
    final newValue = newData[key];
    if (oldValue != newValue) {
      differences[key] = {
        'old_value': oldValue,
        'updated_value': newValue,
      };
    }
  });

  if (differences.isNotEmpty) {
    final user = FirebaseAuth.instance.currentUser;
    await FirebaseFirestore.instance.collection('Activity_log').add({
      'task_id': FirebaseFirestore.instance.doc('Tasks/$taskId'),
      'changes': differences,
      'timestamp': FieldValue.serverTimestamp(),
      'modified_by': user != null ? user.uid : 'Unknown',
    });
  }
}

Note:

  • FirebaseAuth: Used to get the current user’s ID.
  • modified_by: Stores the user ID who made the changes.

Handling Null Values:

To avoid errors, make sure your function can handle null values.

if (oldValue != newValue && (oldValue != null || newValue != null)) {
differences[key] = {
'old_value': oldValue,
'updated_value': newValue,
};
}

Example of changes Field:

{
  "title": {
    "old_value": "Old Task Title",
    "updated_value": "New Task Title"
  },
  "status": {
    "old_value": "In Progress",
    "updated_value": "Completed"
  }
}

Conclusion:

In the article, I have explained the Maintain Activity Log in Firebase Using FlutterFlow Development basic structure; you can modify this code according to your choice. This was a small introduction to the Maintain Activity Log in Firebase Using FlutterFlow On User Interaction from my side, and it’s working using Flutterflow.

I hope this blog will provide you with sufficient information on Trying Maintain Activity Log in Firebase Using FlutterFlow in your projects. You’ve successfully used Firebase to integrate an activity logging system into your FlutterFlow application by following this tutorial. By keeping track of all work adjustments, this system improves accountability and transparency.. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire Flutterflow developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any Flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.