Search code examples
flutterdartsharedpreferences

How do I store an integer correctly in the SharedPrefences in Flutter without getting a null?


I want to save an Int which I can reuse in a new class. For this I used SharedPreferences. The problem is when I want to open the Int on my new page then I get only a null out. But I noticed that when I do a hot restart and then switch to the page no null comes out but what I saved before. Where is my error?

Here I save the value:

  Future<Album> fetchAlbum() async {

    int msgId;
//I fetch json from a page and store the value at msgId. I just don't have it in my code sample in here 
    SharedPreferences prefs = await SharedPreferences.getInstance();
    msgId = (prefs.getInt('msgId'));
    msgId = (prefs.getInt('msgId') ?? jsonData[0]["msgId"]);
          prefs.setInt('msgId', msgId);

  }

Here I retrieve the saved value (on a new page):

  String url ='MyUrl';
  int msgId;
  // int intMsgId;
  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      msgId = (prefs.getInt('msgId'));
      prefs.setInt('msgId', msgId);
      print(msgId);
    });
  }

  Future<String> makeRequest(String text) async {
    _loadCounter();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      msgId = (prefs.getInt('msgId'));
      prefs.setInt('msgId', msgId);
      print(msgId);
    });

    print("------MSG_ID------");
    print(msgId);
    print("------MSG_ID------");
    //print(msgId.length);
    if (msgId != null) {
      var response = await http.post(Uri.encodeFull(url),
          headers: {
            "x-requested-with": "xmlhttprequest",
            "Accept": "application/json",
            "content-type": "application/json",
          },
          body: jsonEncode({
            "messages": {
              "msgId": msgId,
              "refId": msgId
            }
          }));
      print(response.body);
    }
  }

Solution

  • The problem probably because you don't await the SharedPreferences.setInt method.

    your code:

    prefs.setInt('msgId', msgId);
    

    change to:

    await prefs.setInt('msgId', msgId);
    

    because SharedPreferences.setInt is async.