Search code examples
flutterdartflutter-getx

Flutter Getx builder not updating UI


I'm trying to use a GetX Builder in combination with a bool in the controller to display a loading spinner while fetching data and then the data afterwards.

Printing the update to the bool shows it finishes loading and changes the variable but the UI is never updated to reflect this.

Controller

class AuthController extends GetxController {

  //final RxBool isLoading = true.obs;
  //var isLoading = true.obs;

  final Rx<bool> isLoading = Rx<bool>(true);

  setLoading(bool status) {
    isLoading.value = status;
    print(isLoading.value);
    update();
  }


  fetchUserData() async {
    setLoading(true);
    _firebaseUser.bindStream(_auth.authStateChanges());
    if (_auth.currentUser != null) {
      bool profileRetrieved =
          await FirestoreDB().getUserProfile(_auth.currentUser!.uid).then((_) {
        return true;
      });

      setLoading(!profileRetrieved);

    }
  }
}

Profile Page

class ProfileCard extends StatelessWidget {
  const ProfileCard({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AuthController>(
      init: AuthController(),
      initState: (_) => AuthController().fetchUserData(),
      builder: (controller) {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }
        return Container(...);
      },
    );
  }
}

That widget is called within another as part of the wider UI. Let me know if you'd need to see that and/or anything else.

As you can see I've tried different ways of setting up the bool and none of them seem to trigger a change of UI in the builder.

Probably doing something stupid but I've tried a few different approaches and looked around for people having similar problems but not been able to crack it.

Thanks in advance.


Solution

  • You are using isLoading as a Rx<bool>. In that case you need to change GetBuilder into GetX. And no need to call update().

    • GetBuilder is for non-reactive, non-Rx, simple state management

    • GetX is for reactive, Rx state management