Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetStorage always returns null in flutter

Code

    print("Before : ${GetStorage().read("XXX")}");
    GetStorage().write("XXX", 1);
    print("After : ${GetStorage().read("XXX")}");

This is my Code. Every time I run the App, the Output is

Before : null
After : 1

Why is the storage data getting cleared everytime I restart the App? I thought this was an alternative to SharedPreference which works just fine. Have I missed something?

like image 778
Prateek BB Avatar asked Aug 30 '26 16:08

Prateek BB


2 Answers

Before anything, initialize the package, normally I do this on main.dart

main() async {

  await GetStorage.init();


}

Create an instance from GetStorage, I like to put a name on the box, if not it will put "GetStorage" by default. It needs to have a name so it can retrieve your data.

GetStorage getStorage = GetStorage('myData');

After that you can write and retrieve data from it, I recommend you to "await" all reads and writes.

await getStorage.write('test', 1);
var a = await getStorage.read('test');
print(a); /// 1

I recommend you to put a name on the box according to what you are storing.

like image 114
djalmafreestyler Avatar answered Sep 01 '26 06:09

djalmafreestyler


You should await for GetStorage.init().

void main() async {
  await GetStorage.init();
  print("Before : ${GetStorage().read("XXX")}");
  GetStorage().write("XXX", 1);
  print("After : ${GetStorage().read("XXX")}");
}
like image 33
yaser sojoodi Avatar answered Sep 01 '26 06:09

yaser sojoodi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!