Jhourlad Estrella
Jhourlad Estrella

Reputation: 3670

Flutter localstorage.getItem() returns null

I'm using a Flutter package called localstorage to save the token and the user id I got from an API backend. I'm successfully saving the data as I'm seeing from Chrome's local storage:

class AuthService {
  final LocalStorage storage = new LocalStorage('my_app_session');
  ....

  login(context, email, password) async {
      ...
      storage.setItem('id', res['data']['id'].toString());
      storage.setItem('token', res['token']['access_token']);
      ...
      Navigator.pushNamed(context, '/somepage');
  });
}

enter image description here

Then from a ChangeNotifier model:

class OrganizationModel extends ChangeNotifier {
  ...

  var orgService = new OrganizationService();
  ...

  Future fetch() async {
    List res = await orgService.fetch();
    ...
  }
}

Lastly, on OrganizationService:

class OrganizationService {
  final LocalStorage storage = new LocalStorage('my_app_session');

  _token() {
    var token = storage.getItem('token');
    print(token);
    return token;
  }
}

The problem is token always returns null. I tried another new entry via setItem() just to test it and it completely replaced the entire localstorage with the new entry as if it doesn;t see the existing ones.

Any ideas why is this happening based on my workflow?

Upvotes: 2

Views: 3756

Answers (3)

Migrate away from localstorage because it is not encrypted and the data persist on your local machine. Instead use FlutterSecureStorage for state restoration.

I use flutter_secure_storage: ^9.0.0 for local storage because it is encrypted.

 final storage = const FlutterSecureStorage();

 extractFromStorage().then((value) {});

Future<bool> extractFromStorage() async {
 try {
 String _local_employeeEmail = await storage.read(key: "email") ?? "";
 setState(() {
 _employeeEmail = _local_employeeEmail;
 });
 return true;
 } catch (e) {
 DialogCaller.showErrorDialog(context, e.toString());
 }
 return false;
 }

Future<void> setStorage(MasterMonitor model) async {
 try {
 await storage.write(
 key: "email",
 value: model.data.email,
 );
 } catch (e) {
 DialogCaller.showErrorDialog(context, e.toString());
 }
 }

Upvotes: 0

Jason Lim Ji Chen
Jason Lim Ji Chen

Reputation: 202

To allow data to be persisted,

Please remember to check for storage.ready even for data uploading, setItem().

Uploading data:

await storage.ready;
await storage.setItem('name', 'Abolfazl');

Retrieving data:

await storage.ready;
final name = await storage.getItem('name');

Upvotes: 3

Thomas Ahn
Thomas Ahn

Reputation: 86

var ready = await storage.ready; 
print('searching ${key} is $ready'); 
dynamic userJson = storage.getItem(key);

Just check storage.ready and search item, that's it.

Upvotes: 7

Related Questions