Localstorage Returns Null

localStorage returns NULL

Working Live example.

You've to parse the returned string to JSON to get the station like :

var defaultReportData = JSON.parse(localStorage.getItem('defaultReportData'));
console.log( defaultReportData.station );

Getting items from localstorage returns null

localStorage.setItem(key, value) expecting a value to be string. When you pass the object such as [{id: 1}], it will typecast it to string. Hence the object becomes the string like this "[object Object]".

localStorage.setItem('test', [{id: 1}]);
const item = localStorage.getItem('test');
console.log(item) // "[object Object]" a string
console.log(item[0]) // "["
console.log(item[1)) // "o"

Solution

The solution is to stringify it before saving to localStrage and parse it after getting the item.

localStorage.setItem('workItems', JSON.stringify(response.data.items));
// when you get the items
if (JSON.parse(localStorage.getItem('workItems')).length > 0)

Flutter localstorage.getItem() returns null

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.



Related Topics



Leave a reply



Submit