Caculate the total task created on firebase base on id flutter

Issue

I would like to calculate the total created task on firebase using flutter. Is there a way to do it using flutter do I have to use java and swift to do this function. This is how I stored my task and they are generated by firebase (ID).

Done it in realtime database

enter image description here

final tasksData = Provider.of<Tasks>(context);
    final tasks = tasksData.tasks;
    print(tasks.length); // total tasks

Future<void> fetchAndSetProducts() async {
const url = 'https://firebaselink.firebaseio.com/tasks.json';
try {
  final response = await http.get(url);
  final extractedData = json.decode(response.body) as Map<String, dynamic>;
  final List<TodoList> loadedTasks = [];
  extractedData.forEach((taskId, taskData) {
    loadedTasks.add(TodoList(
      id: taskId, 
      name: taskData['name'],
      description: taskData['description'],
      date: DateTime.parse(taskData['date']),
      filename: taskData['filename'],
      location: taskData['location'],
      isCompleted: taskData['isCompleted'],
      notes: taskData['notes'],
    ));
  });
  _tasks = loadedTasks;
  notifyListeners();
} catch (error) {
  print(error);
  throw (error);
}
}

     List<TodoList> _tasks = [];

  List<TodoList> get tasks {
    return [..._tasks];
  }

Further questions display future in Text widget

  Future<void> refreshTasks(BuildContext context) async {
await Provider.of<Tasks>(context,listen: false).totalCompletedTask();
  }

Text( refreshTasks.toString()) 

Error:
Got this:
Closure: (BuildContext) => Future

Solution

You can go through each document and check isCompleted is true or not if it is true then increase value of totalTrue variable, which will hold total true count.

Following method will do work for you.

 getCount() async {
    int totalcount = 0;
    await FirebaseDatabase.instance
        .reference()
        .child("tasks")
        .once()
        .then((DataSnapshot snapshot) {
      Map<dynamic, dynamic> data = snapshot.value;
      data.forEach((key, value) {
        if (value['isCompleted']) {
          totalcount++;
        }
      });
    });

    print(totalcount);
  }

Update:

Future<int> fetchAndSetProducts() async {
  const url = 'https://firebaselink.firebaseio.com/tasks.json';
  try {
    int totalcount = 0;

    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    extractedData.forEach((taskId, taskData) {
      if (taskData['isCompleted']) {
        totalcount++;
      }
    });
    print(totalcount);
    return totalcount;
  } catch (error) {
    print(error);
    throw (error);
  }
}

Answered By – Viren V Varasadiya

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

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