Browse Source

Ranking with live updates

iwa-42 3 năm trước cách đây
mục cha
commit
2ccc2ee79c
4 tập tin đã thay đổi với 74 bổ sung32 xóa
  1. 23 8
      app/lib/database.dart
  2. 36 24
      app/lib/widgets/datatable.dart
  3. 14 0
      app/pubspec.lock
  4. 1 0
      app/pubspec.yaml

+ 23 - 8
app/lib/database.dart

@@ -1,23 +1,38 @@
 import 'package:cloud_firestore/cloud_firestore.dart';
+import 'models/user.dart';
 
 class DatabaseManager {
   CollectionReference usersList =
       FirebaseFirestore.instance.collection("Users");
 
-
-  Future getUsersList() async {
-    List users = [];
+  // Get stream with users ordered by total points from firestore
+  Stream<List> getUsersList() async* {
+    List<dynamic> users = [];
     try {
-      await usersList.orderBy("total_points", descending: true).get().then((querySnapshot){
-        querySnapshot.docs.forEach((element){
+      await usersList.orderBy("total_points", descending: true).snapshots().
+        listen((snap){
+        snap.docs.forEach((element){
         users.add(element.data());
         });
       });
-
-      return users;
+      yield users;
     } catch(e){
       print(e.toString());
-      return null;
+      yield [];
     }
   }
+  //It is not necessary.At least right now
+  // List<User> _userListFromSnapshot(QuerySnapshot snapshot){
+  //   return snapshot.docs.map((doc){
+  //     return User(
+  //       shared_id: doc.get('shared_id'),
+  //       name: doc.get('name'),
+  //       total_points: doc.get('total_ponts'),
+  //     );
+  //   }).toList();
+  // }
+  //
+  //  dynamic get users {
+  //   return usersList.orderBy("total_points", descending: true).snapshots();
+  // }
 }

+ 36 - 24
app/lib/widgets/datatable.dart

@@ -1,6 +1,7 @@
+import 'package:cloud_firestore/cloud_firestore.dart';
 import 'package:flutter/material.dart';
 import 'package:physigo/database.dart';
-
+import '../models/user.dart';
 
 class MyDataTable extends StatefulWidget {
   const MyDataTable({Key? key}) : super(key: key);
@@ -11,44 +12,54 @@ class MyDataTable extends StatefulWidget {
 
 class _MyDataTableState extends State<MyDataTable> {
 
-  List userList = [];
 
   @override
   Widget build(BuildContext context) {
-    return Scaffold(
-        body: Center(
-        child: buildDataTable(),
+
+    return  Scaffold(
+    body: Center(
+      child: StreamBuilder<dynamic>(
+        stream: DatabaseManager().getUsersList(),
+        builder: (context, snapshot) {
+          if(snapshot.connectionState == ConnectionState.waiting){
+            return const Text('Wait a moment');
+          }
+          else if(snapshot.hasData) {
+            return buildDataTable(snapshot.data);
+          }
+          return const Text("Something went wrong");
+          },
+    ),
     ),
     );
   }
   @override
   void initState() {
     super.initState();
-    fetchUsers();
   }
 
-  fetchUsers() async{
-      dynamic users = await DatabaseManager().getUsersList();
-
-      if(users == null){
-        print("Wrong");
-      }
-      else{
-        setState(() {
-          userList = users;
-        });
-      }
+  // fetchUsers() async{
+  //     dynamic users = await DatabaseManager().getUsersList();
+  //
+  //     if(users == null){
+  //       print("Wrong");
+  //     }
+  //     else{
+  //       setState(() {
+  //         userList = users;
+  //       });
+  //     }
   }
 
-  Widget buildDataTable() {
+  Widget buildDataTable(snapshotData) {
     final columns = ['ID', 'Name', 'points'];
 
     return DataTable(
       columns: getColumns(columns),
-      rows: getRows(),
+      rows: getRows(snapshotData),
     );
   }
-
+  // Columns of ranking
   List<DataColumn> getColumns(List<String> columns) {
     return columns.map((String column) {
       return DataColumn(
@@ -56,10 +67,12 @@ class _MyDataTableState extends State<MyDataTable> {
       );
     }).toList();
   }
-  List<DataRow> getRows() {
+
+  //Rows of ranking(id, name, total_points)
+  List<DataRow> getRows(dynamic snapshotData) {
     List<DataRow> rows = [];
 
-    userList.forEach((user) {
+    snapshotData.forEach((user) {
         rows.add(
             DataRow(
                 cells: [
@@ -67,7 +80,7 @@ class _MyDataTableState extends State<MyDataTable> {
                     Text("${user["shared_id"]}"),
                   ),
                   DataCell(
-                    Text(user["name"]),
+                    Text(user["name"],)
                   ),
                   DataCell(
                     Text("${user["total_points"]}"),
@@ -78,7 +91,6 @@ class _MyDataTableState extends State<MyDataTable> {
       });
     return rows;
   }
-}
 
 
 

+ 14 - 0
app/pubspec.lock

@@ -324,6 +324,13 @@ packages:
       url: "https://pub.dartlang.org"
     source: hosted
     version: "2.0.0"
+  nested:
+    dependency: transitive
+    description:
+      name: nested
+      url: "https://pub.dartlang.org"
+    source: hosted
+    version: "1.0.0"
   path:
     dependency: transitive
     description:
@@ -394,6 +401,13 @@ packages:
       url: "https://pub.dartlang.org"
     source: hosted
     version: "2.0.0"
+  provider:
+    dependency: "direct main"
+    description:
+      name: provider
+      url: "https://pub.dartlang.org"
+    source: hosted
+    version: "6.0.3"
   quiver:
     dependency: transitive
     description:

+ 1 - 0
app/pubspec.yaml

@@ -48,6 +48,7 @@ dependencies:
   firebase_auth: ^3.3.17
   flutter_activity_recognition: ^1.3.0
   geolocator: ^8.2.1
+  provider: ^6.0.1
 
 dev_dependencies:
   flutter_test: