How to solve SharedPreferences not working in flutter

Viewed 7637

I am using SharedPreferences to save the response from API. I want to use when my apps is offline or switch to another tab, the data will not reload again. But it not working. It only working when I online. But if I online I switch the page the data will reload again. If I offline the data will not come out.

3 Answers

Ruturn the data in finally :

Future<PagesData> sendPagesDataRequest(int page) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  try {
    // your codes ...
  } finally {
    String myDataValue = prefs.getString('myData');
    return pagesDataFromJson(myDataValue);
  }
}

From the code, I see that when you are online you get the data and it gets parsed, but when you are offline and you are doing all the stuff in the try-catch block, so when you go offline there is socket Exception that occurs in a catch block that you have not handled.

SharedPreferences prefs = await SharedPreferences.getInstance();
        String myDataValue = prefs.getString('myData');
        final project = pagesDataFromJson(myDataValue);

if you call this in the catch you might be able to get the data when you are offline.

But this is just a fix check this link which will tell you if internet is there or no : https://pub.dev/packages/data_connection_checker

or youcan refer this video :

https://www.youtube.com/watch?v=u_Xyqo6lhFE

So it would not load the data from the prefrences because when you get the exception it directly goes to the catch without leaving the below code.

Fetch data from the API

Future<String> fetchPagesData(int page) {
  String url = Uri.encodeFull("https://API_URL?page=$page");
  return http.get(url).body;
}

Set SharedPreferences data

Future<String> setPagesData(int page, String value) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('myData$page', value);
}

Get SharedPreferences data

Future<PagesData> getPagesData(int page) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('myData$page');
}

Catch while offline

Future<PagesData> sendPagesDataRequest(int page) async {
  try {
    fetchPagesData(page).then((value) => setPagesData(page, value));
//   } on SocketException {
// no network connection   
  } catch (e) {}

  return getPagesData(page);
}
Related