0

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

Duxton Lim
  • 21
  • 6

1 Answers1

1

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);
  }
}
Viren V Varasadiya
  • 25,492
  • 9
  • 45
  • 61
  • Hi I'm using realtime database not firestore or does it work for realtime database as well? – Duxton Lim May 10 '20 at 08:41
  • sorry that is my mistake, i did not focus on database type. but you can use fetching process of that, and counting logic of my answer. it will work with that too. try to implement your self if you can't figure-out let me know. i will update my answer with firebase realtime database. – Viren V Varasadiya May 10 '20 at 08:44
  • hi could u update your answer please? Thanks couldn't figure it out – Duxton Lim May 10 '20 at 09:02
  • I got a very long error after trying to compile it. [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, Default FirebaseApp is not initialized in this process com.example.personal_assistance. Make sure to call FirebaseApp.initializeApp(Context) first., null) – Duxton Lim May 10 '20 at 09:55
  • did you set up your app for firebase ? did firebase was working in your app ? are you able to fetch data from firebase at any other place in your app? – Viren V Varasadiya May 10 '20 at 09:59
  • Yes I was able to display all my data in other places. However I did not use firebase_database packages before that. I did not set up my app by registering it – Duxton Lim May 10 '20 at 10:01
  • Hi can I ask u another question? How do u use the value from Future fetchAndSetProducts in a text widget? which would return totalCount in this case – Duxton Lim May 10 '20 at 11:15
  • Check update. @DuxtonLim. Also add await whatever you call that method – Viren V Varasadiya May 10 '20 at 11:32
  • I got error message instead of the value I wanted Closure: (BuildContext) => Future I have also updated above at my questions. – Duxton Lim May 10 '20 at 12:09
  • this issue is related to provider. – Viren V Varasadiya May 10 '20 at 12:11
  • Is there a way to solve it? Or is there another way round to calculate total completed task when it's TRUE – Duxton Lim May 10 '20 at 12:16
  • it is not possible for me to guess what is wrong from this much code only. ask another question with full detail. – Viren V Varasadiya May 10 '20 at 12:18
  • Ouh I see is it possible for u to show me how would u display future in a text widget? Thanks – Duxton Lim May 10 '20 at 12:22
  • 1
    you have to use futurebuilder for that. – Viren V Varasadiya May 10 '20 at 12:25