Flutter Gex, UI is not updating reactively

23 views Asked by At

here is my main.dart file:


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await GetStorage.init();
  Get.put(MyUserController());
  Get.put(LoginController(AuthRepository(AuthController())));
  Get.put(SignupController(AuthRepository(AuthController())));
  Get.put(CropsController());
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final myUserController = Get.find<MyUserController>();
      final needLogin = myUserController.needLogin.value;
      return GetMaterialApp(
        debugShowCheckedModeBanner: false,
        getPages: AppPages.routes,
        title: 'CropHub',
        theme: MAppTheme.lightTheme,
        darkTheme: MAppTheme.darkTheme,
        themeMode: ThemeMode.system,
        home: needLogin ? const LoginScreen() : const Home(),
      );
    });
  }
}

and from somewhere else, i call this function:

logOut() {
    print("log out called");
    _getStorage.erase();
    needLogin.value = true;
    print("needLogin value from user controller: ${needLogin.value}");
  }

what i expect is when the logout function is called, the UI in main.dart file is updated reactively, substituting the home screen with the login screen, but this is not happening unless i restart the app again from the IDE.

1

There are 1 answers

1
Yakubu On

Ensure needLogin is declared as an RxBool to be observable by GetX

class MyUserController extends GetxController {
    RxBool needLogin = false.obs; 
}

Adjust logOut Method:

void logOut() {
 print("log out called");
 _getStorage.erase();
 final myUserController = Get.find<MyUserController>();
 myUserController.needLogin.value = true; // Directly update the observable
 print("needLogin value from user controller: 
 ${myUserController.needLogin.value}");
}