I’m still kind of a newbie in flutter. I want to use riverpod state management to update UI showing username and email of user immediately after user updates his or her information. The information displayed is retrieved from shared preferences which is automatically updated once the user updates his or her information
code for retrieving data from shared preference
Future<void> _loadDataFromSharedPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
token = prefs.getString('token');
String? userJson = prefs.getString('user');
if (userJson != null) {
user = json.decode(userJson);
}
firstNameController.text = user!['firstName'];
lastNameController.text = user!['lastName'];
userId = user!['_id'];
});
}
updating user data in shared preference
if (response.statusCode == 200) {
final Map<String, dynamic> responseBody = jsonDecode(response.body);
print('User updated successfully: ${responseBody['user']}');
// Update SharedPreferences with the new user data
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('user', jsonEncode(responseBody['user']));
} catch (e) {
print('Failed to save user data in SharedPreferences: $e');
showCustomFlushbar(context, "Failed to save user data locally!");
throw Exception('Failed to save user data in SharedPreferences');
}
// Pop the current context
if (context.mounted) {
Navigator.pop(context);
}
} else {
showCustomFlushbar(context, "Imeshindikana kubadili jina!");
_btnController.error();
throw Exception('Failed to update user: ${response.statusCode}');
}
displaying user information on the ui
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (user != null) ...[
Text(
'${user!['firstName'] ?? ''} ${user!['lastName'] ?? ''}',
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
),
),
Text(
user!['email'] ??
"+${user!['phone']?.toString()}" ??
'',
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
]
],
),
I have read and watched tutorials on riverpod but haven’t understood how to implement this. Please help
ecnyakiha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.