I am working on personal flutter project using Riverpod without hooks or code generation. I just implemented localization for the app. The implementation consists of single button that when pressed changes the current language to the other language due to using only two languages in the app.I used AutoDisposeAsyncNotifier to change the state of the app localization and to save locally via Shared Prefferences the current locale. I would like to make unit tests for the logic, but i am strugling with understanding from the riverpod documentation how to properly test the AsynNotifier/Provider that i am using.
Here is the content of the localization notifier i implemented:
class LocalizationNotifier extends AutoDisposeAsyncNotifier<Locale> {
Locale currentLocale = const Locale('en');
@override
FutureOr<Locale> build() {
return SharedPreferencesService().getLocale();
}
void changeLocale(Locale newLocale) {
switch(currentLocale.languageCode) {
case 'en':
newLocale = const Locale('bg');
break;
case 'bg':
newLocale = const Locale('en');
break;
default:
newLocale = const Locale('en');
break;
}
currentLocale = newLocale;
SharedPreferencesService().setLocale(newLocale);
ref.invalidateSelf();
}
}
final localizationProvider = AsyncNotifierProvider.autoDispose<LocalizationNotifier ,Locale>(
LocalizationNotifier.new,
);
Here is the code of the shared preferences service methods that i am using in the notifier i want to test:
Future<void> setLocale(Locale locale) async {
switch(locale.languageCode){
case 'en': await _prefs.setString(SharedPreferencesKeys.locale, 'en');
break;
case 'bg': await _prefs.setString(SharedPreferencesKeys.locale, 'bg');
break;
default: await _prefs.setString(SharedPreferencesKeys.locale, 'en');
break;
}
}
Locale getLocale() {
String languageCode = _prefs.getString(SharedPreferencesKeys.locale) ?? 'en';
return Locale(languageCode);
}
I’ve been banging my head over the documentation even tried using chatGPT but to no avail to understand how to do it and why to do it the way it should be. If anyone could provide me with example on on how to test the notifier so i could reverse engineer it for all the future providers/notifiers i implement that would be nice.