简体   繁体   中英

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);
});
}

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");
});
//To save data in shared preference
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('firstName', 'ABC'); //'firstName' is key and 'ABC' is the value 
prefs.setString('lastName', 'D');

//To get data saved in shared preference
String firstname = prefs.getString('firstName') ?? ""; //Pass the key to retrieve saved data
String lastname = prefs.getString('lastName') ?? ""; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM