read data from firebase database compared to firestore

Viewed 70

Since the tutorial I am following is using firestore and I tried to use firebase database. Could you plz let me know where is wrong, why I cant read my data?

Here is the tutorial code for firestore:

  static Stream<List<Todo>> readTodos() => FirebaseFirestore.instance
      .collection('todo')
      .orderBy(TodoField.createdTime, descending: true)
      .snapshots()
      .transform(Utils.transformer(Todo.fromJson));

for transformer methode is like this:

  static StreamTransformer transformer<T>(
          T Function(Map<String, dynamic> json) fromJson) =>
      StreamTransformer<QuerySnapshot, List<T>>.fromHandlers(
        handleData: (QuerySnapshot data, EventSink<List<T>> sink) {
          final snaps = data.docs.map((doc) => doc.data()).toList();
          final objects = snaps.map((json) => fromJson(json)).toList();

          sink.add(objects);
        },
      );

Here is my code for firebase database:

  static Stream<List<Todo>> readTodos() => FirebaseDatabase.instance
      .ref("todo")
      .orderByChild(TodoField.createdTime)
      .onValue
      .map((todo) => todo.snapshot.children
          .map((e) => Todo.fromJson(e.value as Map<String, dynamic>))
          .toList()
        ..sort((a, b) => b.createdTime.compareTo(a.createdTime)));

Here is streambuilder:

    StreamBuilder<List<Todo>>(
      stream: FirebaseApi.readTodos(),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          default:
            if (snapshot.hasError) {
              return buildText('Something Went Wrong Try later');
            } else {
              final todos = snapshot.data;
              TodosController todosController = Get.find();
              todosController.setTodos(todos);
              return TodoListWidget();
            }
        }
      },
    ),

here is my data structure:

enter image description here

So since the text is "Something Went Wrong Try later", I assume there is error that from somewhere right. Plesae let me know or share me the right code, thanks a lot!

Question 2: also plz tell me if Im doing correctly to sort the todo event by createdTime, since for firebase only ascending is allowed, thanks!(I would like to pay for the answer since I really asked a lot and the solutions always saved my time if stack overflow has this feature)

1 Answers

If there is an error in your AsyncSnapshot, you should show the contents of that error to learn what causes the problem:

switch (snapshot.connectionState) {
  case ConnectionState.waiting:
    return Center(child: CircularProgressIndicator());
  default:
    if (snapshot.hasError) {
      print('Error: ${snapshot.error}; // 
      return buildText('Something Went Wrong Try later');
    } else {
Related