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

MarcelK

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);
    }
  }
ישו אוהב אותך

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I count the occurence of an integer in a list and output it correctly?

When using try/catch/finally, with error inputmismatch exception, How do I correctly implement a finally block, WITHOUT getting an error

How do I correctly store data between routes

How do I store a random integer in a local variable in Python?

Java: How do I store List<Integer> in Queue?

How do I store an integer using ColdFusion ORM?

webservice returns SID - how do I store result as an integer?

How do i correctly position these items horizontally in flutter to avoid overflow?

How do I correctly implement a FutureBuilder in Flutter in this case?

How do I wait for an asynchronous function to finish correctly (flutter, dart)

How do I lerp a double or integer value in Flutter?

How can I check a value for null in jquery without getting an error?

How can I express wait(NULL) without getting compilation warning?

How do I get and store document ID to Field in flutter

How do I format a long integer as a string without separator in Java?

How Do I Convert Integer To String Without Using int()

How Do I Convert String to Integer Without Using int()

How do I store a boolean test/expression without Evaluating it?

How can I use an integer I sent from another controller in JavaFX without getting a NumberFormatException?

How do I code these relationships in sql without getting am error

How do I remove a bridge header without getting errors?

How do I Display a .svg Icon Without it Getting Clipped?

How do i print a variable without getting brackets in python

How do I change sections in HTML without getting '#' in the Link?

How do I fix not null constraints error on flutter?

PHP - How do I correctly use a "if(isset() && != NULL) || (isset() && != NULL)" statement?

How do I correctly get the value of 'ⅻ' (and other similar non-alphabetical characters) and store it in a string?

How do I correctly store an (Objective-C) SKProduct* in a C++ std::map?

How do I correctly store encryption keys on macOS so only my executable can access them?