Ad

How To Read And Use Shared Preference Values In Initstate()? I Can Read And Use Values In Other Widgets But Not In My API Which I Call In Initstate

- 1 answer

I am creating a list of businesses through RestAPI in initstate. I need to use sharedpreference value as one of its parameter but when i try to load data, the sharepreference value is null initial but that value can be used in other widgets easily.

The problem is how to read sharepreference value and use at the same time in initstate.?

I have tried many options like taking my api out of initstate and defining with async function and call it in initstate.

**@override
  void initState() {
    super.initState();
    loadData();
    getBizList();
  }
  getBizList() async {
    await api
        .bizListAPI(widget.subCatid, savedCityID, supSubFinal, areaFinal)
        .then((response) {
      setState(() {
        bizListOBJ = response;
      });
    });
  }
loadData() async {
    SharedPreferences savedPref = await SharedPreferences.getInstance();
    setState(() {
      savedCity = (savedPref.getString('savedCity') ?? "Mumbai");
      savedCityID = (savedPref.getString('savedCityID') ?? "1");
    });
  }**

in above code i am able to get or read data and show city name from sharedpreference(savedCity) which is in appbar but i want to use savedcityID data to pass in my api in initstate.

I also tried to use following plugin

[https://medium.com/@greg.perry/a-flutter-class-for-app-preferences-a256166ecc63.][1]

With this I was able to do what i wanted but each time i close my app and open again ... i got following error

"_prefsInstance != null,
        "Maybe call Prefs.getKeysF() instead. SharedPreferences not ready yet!");"

after that when i go back and open page again, the app and biz list works perfect till again i close my app.

 [1]: https://medium.com/@greg.perry/a-flutter-class-for-app-preferences-a256166ecc63

sorry for my any noob explanation or question. Actually this is my 1st question in stack and I am beginner in flutter.

Ad

Answer

Can you try this?

void initState() {
  super.initState();
  loadData().then((_) {
    getBizList();
  });
}
Ad
source: stackoverflow.com
Ad