firebase 如何从Firestore数据库中读取数据并在ListView.builder中显示

toiithl6  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(80)

我是一个新的flutter谁目前正在探索Firebase CRUD和GetX管理。我尝试从Firebase读取数据以显示,但它无法显示任何数据。有什么我错过的吗?如何读取和显示它?我已经附上了存储的Firebase数据的代码和图像。
网站首页

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final TaskController controller = Get.put(TaskController());
  DateTime selectedDate = DateTime.now();
 // final db = FirebaseFirestore.instance.collection('task');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(),
      body: Column(
        children: [
          addTaskBar(),
          addDateBar(),
          const SizedBox(height: 5.0),
          showTask(),
        ],
      ),
    );
  }

 showTask() {
    return Expanded(child: Obx(() {
      return ListView.builder(
        itemCount: controller.tasks.length,
        itemBuilder: (_, index) {
          print(controller.tasks.length);
          Task task = controller.tasks[index];
          print(task.toMap());
          if (task.repeat == 'Daily') {
            DateTime date = DateFormat.jm().parse(task.startTime.toString());
            var myTime = DateFormat('HH:mm').format(date);
            print(myTime);

            return AnimationConfiguration.staggeredList(
              position: index,
              child: SlideAnimation(
                child: FadeInAnimation(
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          _showBottomSheet(context, task);
                        },
                        child: TaskTile(task),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }
          if (task.date == DateFormat.yMd().format(selectedDate)) {
            return AnimationConfiguration.staggeredList(
                position: index,
                child: SlideAnimation(
                    child: FadeInAnimation(
                        child: Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        _showBottomSheet(context, task);
                      },
                      child: TaskTile(task),
                    ),
                  ],
                ))));
          } else {
            return Container();
          }
        },
      );
    }));
  }
}

任务模型类

class Task {
  String? id;
  String? title;
  String? note;
  bool? isCompleted;
  String? date;
  String? startTime;
  String? endTime;
  int? color;
  int? remind;
  String? repeat;

  Task({
    required this.id,
    required this.title,
    required this.note,
    required this.isCompleted,
    required this.date,
    required this.startTime,
    required this.endTime,
    required this.color,
    required this.remind,
    required this.repeat,
  });

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'id': id,
      'title': title,
      'note': note,
      'isCompleted': isCompleted,
      'date': date,
      'startTime': startTime,
      'endTime': endTime,
      'color': color,
      'remind': remind,
      'repeat': repeat,
    };
  }

  Task.fromMap(DocumentSnapshot<Map<String, dynamic>> documentSnapshot) {
    id = documentSnapshot.id;
    title = documentSnapshot['title'];
    note = documentSnapshot['note'];
    isCompleted = documentSnapshot['isCompleted'];
    date = documentSnapshot['date'];
    startTime = documentSnapshot['startTime'];
    endTime = documentSnapshot['endTime'];
    color = documentSnapshot['color'];
    remind = documentSnapshot['remind'];
    repeat = documentSnapshot['repeat'];
  }
}

任务控制器类

class TaskController extends GetxController {
  Rx<List<Task>> taskList = Rx<List<Task>>([]);
  List<Task> get tasks => taskList.value;

  @override
  void onReady() {
    taskList.bindStream(FirestoreDB.taskStream());
  }
}

Firebase类

class FirestoreDB {
  final FirestoreDB instance = FirestoreDB();
  // add tasks into firebase firestore
  static addTask({required Task taskmodel}) async {
    await FirebaseFirestore.instance
        .collection('task')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .collection('tasks')
        .add(
          taskmodel.toMap(),
        );
    print(taskmodel);
    print(taskmodel.toMap());
  }

  // stream that continuously checks all the tasks available inside the user’s task collection.
  // This function returns a list of the Task object.
  static Stream<List<Task>> taskStream() {
    return FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .collection('tasks')
        .snapshots()
        .map((QuerySnapshot query) {
      List<Task> tasks = [];
      for (var task in query.docs) {
        final taskModel =
            Task.fromMap(task as DocumentSnapshot<Map<String, dynamic>>);
        tasks.add(taskModel);
      }
      return tasks;
    });
  }

  Future<List<Task>> getTasks() async {
    QuerySnapshot<Map<String, dynamic>> snapshot = await FirebaseFirestore
        .instance
        .collection("users")
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .collection('tasks')
        .get();
    return snapshot.docs
        .map((docSnapshot) => Task.fromMap(docSnapshot))
        .toList();
  }

  updateTask(Task taskmodel, documentId) async {
    await FirebaseFirestore.instance
        .collection('task')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .collection('tasks')
        .doc(documentId)
        .update(
          taskmodel.toMap(),
        );
  }

  deleteTask(String documentId) async {
    await FirebaseFirestore.instance
        .collection('task')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .collection('tasks')
        .doc(documentId)
        .delete();
  }

  deleteAllTask() async {
    await FirebaseFirestore.instance.collection('task').get().then((snapshot) {
      for (DocumentSnapshot ds in snapshot.docs) {
        ds.reference.delete();
      }
    });
    // .doc(FirebaseAuth.instance.currentUser!.uid)
    // .delete();
  }
}

Firestore示例图像:

3qpi33ja

3qpi33ja1#

有很多地方可能会出错,尝试将您的流放在try catch块中,并记录可能出现的任何错误,您也可以记录快照数据以查看可能出错的地方

相关问题