Search code examples
androidiosflutterdartsharedpreferences

How to properly save data in text field flutter using SharedPreferences?


I'm trying to get the data from the text field via 'Save Data' button then show that data in Text Widget when I click the 'Show Data' button. I'm using SharedPreferences dependency. I'm already done with the code but there's one problem, whenever I click the 'Show Data' button, it only shows the data from the second Text Field like this: LastName null

The result should be: FirstName LastName

Here's the Save Data

saveData(String firstName, String lastName) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(firstName, lastName);
}

Here's the Show Data

showData(String firstName, String lastName) async {
final prefs = await SharedPreferences.getInstance();
setState(() {
  fName = prefs.getString(firstName);
  lName = prefs.getString(lastName);
});
}

Solution

  • The Shared Preferences lib stores data as <key,value>. In your code you store the value lastName under the key firstName. So when you try to find the data with the key firstName, it returns the lastName, but when you try to get the data linked to the key lastName, it doesn't exist.

    This code should lead you to the solution

    prefs.setString("firstName", firstName);
    prefs.setString("lastName", lastName);
    
    ...
    
    setState(() {
      fName = prefs.getString("firstName");
      lName = prefs.getString("lastName");
    });