Reputation: 170
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
Upvotes: 5
Views: 5545
Reputation: 1
You have to wait for the storage to be ready, you can do that by using the ready
getter from your LocalStorage instance.
// Note tha this has to be inside an async function
LocalStorage storage = LocalStorage('mykey');
await storage.ready;
// Do your storage manipulation here
If you don't want to await for the storage to be ready everytime you can add it to your App State in main.dart while initializing.
Turn your void main()
into void main() async
and put a await storage.ready
there.
Upvotes: 0
Reputation: 41
If you created an abstraction for it you need initialize it in main function. such as
await AppGeneralCacheInitilization.instance.initializeCacheService();
by this way we are sure that the storage is available.
Upvotes: 0
Reputation: 3163
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
},
);
}
Upvotes: 6
Reputation: 2355
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);
});
};
Upvotes: 1