Home > database >  Getx Storage return null whenever app starts
Getx Storage return null whenever app starts

Time:01-26

I have initilized GetStorage() in main() and calling .read() in onReady dunction of GetX Controller but always get null!

Future<void> main() async {
  await GetStorage.init();
  runApp(const App());
}
class AuthenticationRepository extends GetxController {
  static AuthenticationRepository get instance => Get.find();

  /// Variables
  GetStorage userStorage = GetStorage('User');

  @override
  void onReady() {
    // Firebase User
    firebaseUser = Rx<User?>(_auth.currentUser);
    firebaseUser.bindStream(_auth.userChanges());

    //Session
    print('========= BEFORE -- ${userStorage.read('isFirstTime')} ===========');
    userStorage.writeIfNull('isFirstTime', 'true');
    print('========= AFTER -- ${userStorage.read('isFirstTime')} ============');    
  }

OUTPUT

================== BEFORE -- null ======================== ================== AFTER -- true =========================

I have tried named values also like GetStorage('User'); nothing worked.

CodePudding user response:

Need to add

WidgetsFlutterBinding.ensureInitialized();


Future<void> main() async {
      await GetStorage.init();
      runApp(const App());
    }

Change this to :

void main() async {
  await GetStorage.init();
  WidgetsFlutterBinding.ensureInitialized();

  runApp(const MyApp());
}

CodePudding user response:

You will need to give the container name in init if you are using a custom container name.

So, you have two solutions

1 -> Update your init to this

Future<void> main() async {
  await GetStorage.init('User');  // <- add your custom Container name 'User'
  runApp(const App());
}

OR

2 Don't use a custom container name and GetStorage uses it's default container name. In this case, update your code while declaring GetStorage object to read and write data

class AuthenticationRepository extends GetxController {
  static AuthenticationRepository get instance => Get.find();

  /// Variables
  GetStorage userStorage = GetStorage(); //<- remove custom container name 'User'

  @override
  void onReady() {
    // Firebase User
    firebaseUser = Rx<User?>(_auth.currentUser);
    firebaseUser.bindStream(_auth.userChanges());
//Session
print('========= BEFORE -- ${userStorage.read('isFirstTime')} ===========');
userStorage.writeIfNull('isFirstTime', 'true');
print('========= AFTER -- ${userStorage.read('isFirstTime')} ============');    

}

  • Related