I would like to check the ‘shared_preferences’ package in dart and if the user succeeds in logging in after checking the remember check box, save the email that the user used to log in and fill in the email box automatically when entering the next login page.
var _email;
var _password;
var _rememberMe = false;
Future<void> _loadLoginInfo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_rememberMe = prefs.getBool('rememberMe') ?? false;
if (_rememberMe) {
print('loaded');
print(prefs.getString('email'));
_email = prefs.getString('email') ?? null;
}
});
}
Future<void> _saveLoginInfo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('rememberMe', _rememberMe);
if (_rememberMe) {
await prefs.setString('email', _email);
print('saved');
print(_email);
} else {
await prefs.remove('email');
}
}
@override
void initState() {
super.initState();
_loadLoginInfo();
}
Through the code below, I confirmed that ‘loaded’ is performed normally every time the page is called.
(Email saved via ‘print’ will be output normally.)
However, even if TextFormField is set as below, it always appears empty.
TextFormField(
decoration: InputDecoration(
hintText: 'Email',
border: OutlineInputBorder(),
),
initialValue: _email,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
return null;
},
onSaved: (value) {
_email = value;
},
),
When I click the login Elevated Button, I save the login info with the code below.
if (_rememberMe) {
print(_email);
_saveLoginInfo(); // Save login info
}
If the user succeeds in signing in normally while checking the remember check box, they want the email TextFormField to be filled automatically even when they log out or restart the app completely.
help me pls… ðŸ˜
2
Answers
Solved.
This is because the initState method is called before the build method, so the TextFormField is created before _email is set to the saved email.
So using a TextEditingController to set the initial value of the TextFormField in the _loadLoginInfo method.
Use
onChanged
inTextFormFeild
to retrieve user entered email as followings..