How to make a function return observable in Flutter using GetX?
I am trying to convert a code uses stateful widget and provider package to a code with using staless widget and GetX package, but I don't know what can I do for the following getter function?
bool get isAuth {
return token != null;
}
This function checks out if the token
exist or not, and the token itself comes from the following function:
String? get token {
if (_expiryDate != null &&
_expiryDate!.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return null;
}
I don't know how to modify this part of code to make the isAuth
variable observable, then I can use it inside the main.dart
to direct the application either into the Auth screen or Home screen?
Edit: I tried the code suggested in the answer by @S. M. JAHANGIR but I don't know what should I do for the Obx
part in main.dart
file? The following is the main.dart
file:
void main() {
Get.put(MenuController());
Get.put(NavigationController());
Get.put(AuthController());
Get.put(AuthCard);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute: Obx(()=>AuthController.instance.isAuth
? homeScreenRoute
: authenticationScreenRoute),
unknownRoute: GetPage(
name: '/not-found',
page: () => PageNotFound(),
transition: Transition.fadeIn),
getPages: [
GetPage(
name: rootRoute,
page: () {
return SiteLayout();
}),
GetPage(
name: authenticationScreenRoute,
page: () => const AuthenticationScreen()),
GetPage(name: homeScreenRoute, page: () => HomeScreen()),
],
debugShowCheckedModeBanner: false,
title: 'BasicCode',
theme: ThemeData(
scaffoldBackgroundColor: light,
textTheme: GoogleFonts.mulishTextTheme(Theme.of(context).textTheme)
.apply(bodyColor: Colors.black),
pageTransitionsTheme: const PageTransitionsTheme(builders: {
TargetPlatform.iOS: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
}),
primarySwatch: Colors.blue,
),
// home: AuthenticationPage(),
);
}
}
And I get the following error message for this line of the code initialRoute: Obx(()=>AuthController.instance.isAuth? homeScreenRoute: authenticationScreenRoute)
:
The argument type 'Obx' can't be assigned to the parameter type 'String?'.
I also tried initialRoute: Obx(()=> AuthController.instance.isAuth ? homeScreenRoute : authenticationScreenRoute) as String?
But it gives me a new error:
The return type 'String' isn't a 'Widget', as required by the closure's context.
If you want to make the isAuth
getter observable, you can simply do:
RxBool get isAuth {
return RxBool(token != null);
}
But a more convenient way to do this is:
final _isAuth = false.obs;
bool get isAuth {
_isAuth.value= token != null;
return _isAuth.value;
}
And use it like:
Obx(()=> isAuth? codeIfAuthenticated: codeIfNotAuthenticated)