Search code examples
firebasefluttergoogle-cloud-firestoreflutter-getx

GetX Firebase stream does not update UI


I'm missing something fundamental with GetX and Firebase streams. The UI with the ListView doesn't get updated until a change occur in the UI (setState or somthing).

I got a TodoController with a RxList bound to a Firebase stream and a ListView to show all the todos. The ListView doesn't get updated.

GetBuilder<TodoController>(
  builder: (_) => TodoListView(
    todos: _.todos,
  ),
),

DB class

final FirebaseFirestore _firestore = FirebaseFirestore.instance;
String uid = FirebaseAuth.instance.currentUser!.uid;
return _firestore
    .collection('todos')
    .snapshots()
    .map((QuerySnapshot query) {
  List<Todo> _todos = [];
  for (var todoDoc in query.docs) {
    _todos.add(
      Todo.fromDocumentSnapshot(todoDoc)
    );
  }
  return _todos;
});

Controller class

class TodoController extends GetxController {
  final RxList<Todo> _todos = RxList<Todo>([]);
  final TodosDB _db = TodosDB();

  @override
  void onReady() {
    _todos.bindStream(_db.getTodoStream());
    super.onReady();
  }

  List<Todo> get todos {
    // to some fancy stuff... doesn't matter if I make
    // use of .where or anything
    return _todos;
  }
}

Solution

  • Solved by changing GetBuilder to GetX

    GetBuilder is non-reactive while GetX is reactive

    GetBuilder<TodoController>(
      builder: (_) => TodoListView(
        todos: _.todos,
      ),
    ),
    

    To this instead

    GetX<TodoController>(
      builder: (_) => TodoListView(
        todos: _.todos,
      ),
    ),