saveProfile function
- BuildContext context
This function is called when the save button is pressed in the new profile screen.
The only argument is the context so that the function can access the providers.
The function first checks if all the fields are filled in: if they are not, the unfilled fields appear in red. If they are filled, it checks if PersonalDataProvider.editingMode is true. If it is, the function calls PersonalDataProvider.updateProfile. If it is not, the function checks if there is another profile with the same nickname: if there is one, a message is displayed and the user must enter a different nickname. If the nickname is not repeated, PersonalDataProvider.addNewProfile is called.
Regardless of updating or adding a new profile, PersonalDataProvider.saveProfiles is called to save the profiles on SharedPreferences
Implementation
void saveProfile(BuildContext context) async {
final parametersProvider = Provider.of<ParametersProvider>(context, listen: false);
final personalDataProvider = Provider.of<PersonalDataProvider>(context, listen: false);
final tempUser = personalDataProvider.tempUser;
if (tempUser.dateOfBirth != null &&
tempUser.sex != null &&
tempUser.levelOfStudies != null &&
tempUser.nickname != "" &&
tempUser.isSymbols1 != null
) {
parametersProvider.setSaveButtonPressed(false);
if (personalDataProvider.editingMode) {
personalDataProvider.updateProfile(
personalDataProvider.activeUser ?? 0, tempUser);
}
else {
/// Loop to check if the nickname is already taken
bool nicknameRepeated = false;
for (int i = 0; i <
personalDataProvider.profilesList
.length; i++) {
if (tempUser.nickname ==
personalDataProvider.profilesList[i]
.nickname) {
nicknameRepeated = true;
}
}
if (nicknameRepeated) {
showDialog(
context: context,
builder: (context) =>
AlertDialog(
content: Text(
AppLocalizations.of(context)!
.nickname_used,
style: const TextStyle(
fontSize: 20,
color: AppColors.blueText
),
),
actions: [
TextButton(
onPressed: () =>
Navigator.of(context).pop(),
child: const Text('OK',
style: TextStyle(fontSize: 20)),
),
],
),
);
} else {
personalDataProvider.addNewProfile(tempUser);
personalDataProvider.resetTempUser();
}
}
await personalDataProvider.saveProfiles();
Navigator.pushNamed(context, '/');
} else {
parametersProvider.setSaveButtonPressed(true);
}
}