LocalStorage not persisting data after we close the flutter app
Solution 1
For some reason you have to await the local storage to be ready
(This should be done automatically though). So, before calling getItem()
you need await storage.ready;
, like so:
Future<DataType> _getData() async {
final LocalStorage storage = new LocalStorage('brick-game');
await storage.ready;
return await storage.getItem('data');
}
and then in your build
method you can use a FutureBuilder<T>()
to build your UI.
@override
Widget build(BuildContext context) {
return FutureBuilder<DataType>(
future: _getData,
builder: (BuildContext context) {
if (snapshot.hasData) // we read data from storage
else if (snapshot.hasError) // an error occured
else // we are still loading
},
);
}
Solution 2
local storage has a ready
method, that means it takes a while to can access storage
your save method is async
and you set items with await
keyword, but when you launch the app again you get items without await
keyword
try to make a method for getting items
getItems() async {
final LocalStorage storage = new LocalStorage('brick-game');
final data = await storage.getItem('data');
print(data);
}
@override
Widget build(BuildContext context){
getItems().then((_){
print(data);
});
};
Alok Banjare
Updated on November 28, 2022Comments
-
Alok Banjare over 1 year
I am new to Flutter and developing app which needs to store some amount of data in LocalStorage, I am successfully storing and retrieving data to and from LocalStorage but when I close the App and reopens it, it flushes the entire data, and when we try to access the same data it gives Null. I am attaching my sample code here how I am doing it. Its working fine only issue is it does not persist data after restarting an APP.
void saveData() async{ final LocalStorage storage = new LocalStorage('brick-game'); await storage.setItem('data', _data); } @override Widget build(BuildContext context){ final LocalStorage storage = new LocalStorage('brick-game'); final data = storage.getItem('data'); };
Please let me know what I am doing wrong or anything I am missing. Your help will be appreciated. Thanks