K.D.Dilshan
K.D.Dilshan

Reputation: 455

Flutter Mobile Getx Get Storage's getToken() not working properly

Introduction, I have mobile app and I implement login part into my app and I save my token in local using get_storage because I can use my token after re open my app without login again. my approach was I will check the token is null then should navigate to login screen or if it's not null user should navigate to home. The issue was when I open the app it's not navigate to the Home screen. I check it using print when the first time call hasToken() method its always return false also IU check the getToken() it was null.

look at below my local data access algorithm part,

import 'package:get_storage/get_storage.dart';
import 'package:example/constants/constant.dart';

class LocalStorage {
  static GetStorage userBox = GetStorage(Constant.userBox);

  static String? getToken() {
    return userBox.read(Constant.userToken);
  }

   static bool hasToken()  {
    print('token: ${userBox.read(Constant.userToken)}');
    final token  = userBox.read(Constant.userToken);
    return token != null;
  }



  void saveUserToken({required String token}) {
    userBox.write(Constant.userToken, token);
  }

  void clearToken() {
    userBox.remove(Constant.userToken);
  }
}

Look at below code it was my splash screen controller , it will handle the splash screen functions. in thi checkTokenAndNavigate() call but it can see only null so that's why always navigate to the login screen.

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:example/routes/app_rotes_list.dart';
import '../../services/local/local_data.dart';

class SplashScreenController extends GetxController {
  final logoScale = 0.5.obs;
  final opacity = 0.0.obs;

  @override
  void onInit() {
    super.onInit();
    animateLogo();
  }

  Future<void> animateLogo() async {
    // Animate logo scale and opacity
    await Future.delayed(const Duration(milliseconds: 2000));
    logoScale.value = 1.0;
    opacity.value = 1.0;

    // Delay before navigation
    await Future.delayed(const Duration(seconds: 2));
    await checkTokenAndNavigate();
  }

  Future<void> checkTokenAndNavigate() async {
  //  await GetStorage.init(); // Ensure storage is initialized
    await Future.delayed(const Duration(milliseconds: 500));
    final hasToken =  LocalStorage.hasToken();
    final token =  LocalStorage.getToken();
    print('checkTokenAndNavigate has token: $hasToken');

    print('checkTokenAndNavigate has token 2: $token');
    if ( hasToken ) {
      Get.offAllNamed(AppRoutes.HOME_SCREEN);
    } else {
       Get.offAllNamed(AppRoutes.LOGIN_SCREEN);
    }
  }
}

After then when I come to the login screen I check actually if its null? using button click and I print the token at that time it was not null return true.

Look at below I check it form login,

onPressed: () {
              print('Has valid token when press button : ${LocalStorage.hasToken()}');
              obscureText.value = !obscureText.value;
            }, 

Then I check it before load splash it's mean I check it before navigate to splash screen like below,

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // await GetStorage.init(); //I use this and with out this nothing happen
  Get.put(AppThemeManager());
  Get.lazyPut<NetworkController>(() => NetworkController(), fenix: true);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({super.key});
  final AuthController authController = Get.put(AuthController());
//:::::::::::::::::::::::::::::::::<< This widget is the root of your application >>::::::::::::::::::::::::::::::::://
  @override
  Widget build(BuildContext context) {
    print('Has valid token when open : ${LocalStorage.hasToken()}');
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(fontFamily: 'Poppins'),
      defaultTransition: Transition.fadeIn,
      getPages: AppRoutes.routes,
      initialRoute: AppRoutes.SPLASH_SCREEN,
      // initialRoute: AppRoutes.SPLASH_SCREEN,
    );
  }
}

then it was null but the splash screen controller's hasToken() return not null, cannot solve this issue yet if you can suggest any idea if will made me happy Thank you , I've try lots of time serching google stackoverflow , gpt but cannot solve it.

I was use get_storage: ^2.1.1 and get: ^4.6.6

Upvotes: 0

Views: 31

Answers (0)

Related Questions