I’m using just the state management feature of GetX, so app is not wrapped in getmaterialapp. I’ll explain what I had, the problem, what i tried.
I had an Authcontroller getting hydrated per screen where it’s needed like so final AuthPropertyController authController = Get.put(AuthController());
. With this, I was able to navigate from onboarding screen > login> Home page. This flow correctly reflects user authentication status on home screen. However, i realized that when an alternatively flow is used, the home screen doesn’t detect update of user property at all: (onboarding > home>property> login…then clicking “back” until we return to home screen). In fact, after login completes on this flow and Navigator.pop runs, the property page does detect user presence. This is the problem
What I’ve tried:
I started using a singleton ie the main.dart looks like this:
void main() {
initializeAppDependencies();
runApp(const MyApp());
}
void initializeAppDependencies() {
Get.put(AuthController(), permanent: true);
}
Then all the screens now use final AuthController authController = Get.find<AuthController>();
. However, the home screen has a drawerNav with items that should update depending on logged in user status. But it isn’t reactive at all. I’m sure the login process completes. I’ve tried using didChangeDependencies
. I tried storing token in sharedPreferences and rehydrating user on each call. The problem is that the stateful widget itself doesn’t bother rebuilding at all. I’m guessing it’s cuz no setState
is called, but isn’t that the whole schtick of GetX’s controller properties, that you don’t have to listen to them explicitly and that they are intelligent enough to rebuild and replace setState
?
I also plugged the state readers in a method that runs within the widget’s build
method but it does no good. Lastly, I tried this,
GetBuilder(
init: Get.find<AuthController>(),
builder: (controller) {
// return widget contents
})
For the life of me, it never rebuilds during the initial run. I even attempted accessing the static to
method from within this builder
method above. But The controller simply seems dead to whatever is going on within that controller WHENEVER it loads before activities on the controller ie it’s oblivious to the one updated by the login after visiting multiple screens. I don’t want to go the route of comparing object hashes to verify this but all indicators point to this theory
Below is the relevant method
import 'dart:convert';
import 'package:get/get.dart';
import 'package:get/state_manager.dart';
import 'package:http/http.dart' as http;
class AuthController extends GetxController {
var user = Rx<User?>(null);
var submissionError = Rx<String?>(null);
var requestErrorString = "".obs;
static AuthController get to => Get.find();
sendLoginRequest(String email, String password) async {
var responsePayload;
submissionError.value = null; // reset it ahead of next request so it doesn't continue blocking if that succeeds
http.Response response = await http.post(
Uri.parse("${AppSettings.BASE_URL}/${ApiRoutes.LOGIN}"),
body: {"email": email, "password": password}, headers: AppSettings.REQUEST_HEADERS
);
int statusCode = response.statusCode;
responsePayload = response.body;
Map decodedResponse = jsonDecode(responsePayload);
if (statusCode == 200) {
await AppSettings().saveUserToken(decodedResponse["token"]);
user.value = User.fromJson(decodedResponse["user"]);
}
else if (statusCode == 422)
submissionError.value = decodedResponse["message"];
else {
requestErrorString.value = response.reasonPhrase!;
}
}
And this is the current home screen
class AllScreensContainer extends StatefulWidget {
const AllScreensContainer({super.key});
@override
State<AllScreensContainer> createState() =>
_AllScreensContainerState();
}
class _AllScreensContainerState extends State<AllScreensContainer> {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
List<Map> bottomPageDetails = [
{"label":"Home", "icon": Icon(Icons.home_outlined), "route": RouteConstants.HOME_SCREEN},
{"label":"Profile", "icon": Icon(Icons.person), "route": RouteConstants.PROFILE},
{"label":"Favorites", "icon": Icon(Icons.heart_broken), "route": RouteConstants.FAVORITES},
];
int bottomScreenIndex = 0;
final AuthController authController = Get.find();
List<Map> getLeftDrawerItems() {
return [
{"label":"Properties", "icon": Icon(Icons.home_work_outlined, color: Colors.white,), "route": RouteConstants.ALL_PROPERTIES},
{"label":"Acquired Properties", "icon": Icon(Icons.person_add, color: Colors.white,), "route": RouteConstants.MY_PROPERTIES},
if (!AppSettings.IS_ONLINE || (authController.user.value != null && !authController.user.value!.has_deposited))
{"label":"Expression of Interest", "icon": Icon(Icons.money, color: Colors.white,), "route": RouteConstants.DEPOSIT_INTEREST},
{"label":"About", "icon": Icon(Icons.info_outline, color: Colors.white,), "route": RouteConstants.ABOUT},
{"label":"Services", "icon": Icon(Icons.home_repair_service_outlined, color: Colors.white,), "route": RouteConstants.SERVICES},
{"label":"Contact Us", "icon": Icon(Icons.contact_page_outlined, color: Colors.white,), "route": RouteConstants.CONTACT},
{"label":"Logout", "icon": Icon(Icons.logout_outlined, color: Colors.white,), "route": RouteConstants.LOGOUT}
];
}
@override
Widget build(BuildContext context) {
return buildDrawerScaffold(context);
}
Widget buildDrawerScaffold(BuildContext context) {
String screenTitle = "Explore";
if (AppSettings.IS_ONLINE && authController.user.value != null)
screenTitle = "Welcome ${authController.user.value!.name}";
//print( authController.hydrateUser());
return Container(
decoration: BoxDecoration(
image: DecorationImage(
alignment: Alignment.topLeft,
image: AssetImage("assets/images/Home-bg.jpg"),
fit: BoxFit.scaleDown,
),
),
child: Scaffold(
key: scaffoldKey,
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Text(screenTitle),
centerTitle: true,
forceMaterialTransparency: true,
//automaticallyImplyLeading: false, // modify this to hold custom icon
),
body: Home(),
bottomNavigationBar: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
child: Container(
child: NavigationBar(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
//indicatorColor: Colors.orange,
onDestinationSelected: (int index) {
/*setState(() {
bottomScreenIndex = index;
});*/
Navigator.pushNamed(context, bottomPageDetails[index]["route"]);
},
//selectedIndex: bottomScreenIndex,
destinations: bottomPageDetails.map((Map destination) {
return NavigationDestination(
// selectedIcon: ,
icon: destination["icon"],
label: destination["label"]
);
}).toList(),
)
)),
drawer: Drawer(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/drawer-navigation-bg.png"),
fit: BoxFit.cover
)
),
padding: EdgeInsets.fromLTRB(10, 80, 7, 1),
child: ListView(
//padding: EdgeInsets.zero,
children: getLeftDrawerItems().map((Map destination) {
int index = getLeftDrawerItems().indexOf(destination);
TextStyle? leftNavTextStyle = Theme.of(context).textTheme.headlineMedium?.copyWith(
fontSize: 15,
color: Colors.white
);
return ListTile(
leading: destination["icon"], // you can handle selected/highlighted state using any of these
title: Text(destination["label"], style: leftNavTextStyle,),
onTap: () {
Navigator.pushNamed(context, destination["route"]);
scaffoldKey.currentState!.closeDrawer();
});
}).toList(),
),
),
)
)
);
}
}
So, the question is how do I make this controller universal AND cause it to trigger rebuilds on widgets it’s on? Or, how do I correctly put it on those widgets?