I'm quite familiar with Provider package and combine it with the ChangeNotifier
.
Let's say I have 3 getters and method with a different function :
- Toggle Loading
- Toggle Image Loading
- Toggle ObsecurePassword
Using ChangeNotifer
import 'package:flutter/foundation.dart';
class GlobalChangeNotifier extends ChangeNotifier {
bool _isLoading = false;
bool _isImageLoading = false;
bool _isObsecurePassword = false;
bool get isLoading => _isLoading;
bool get isImageLoading => _isImageLoading;
bool get isObsecurePassword => _isObsecurePassword;
void setLoading(bool value) {
_isLoading = value;
notifyListeners();
}
void setImageLoading(bool value) {
_isImageLoading = value;
notifyListeners();
}
void setObsecurePassword(bool value) {
_isObsecurePassword = !value;
notifyListeners();
}
}
final globalChangeNotifier = GlobalChangeNotifier();
If I'm using ChangeNotifier
, I only need to create 1 file and just call a method like globalChangeNotifier.METHOD()
or value like globalChangeNotifier.value
.
But now, I've learned about Riverpod package, and in the documentation, it's using StateNotifier
.
I want to migrate my previous code from ChangeNotifier
to StateNotifier
.
But in my understanding, StateNotifier only can hold 1 type data, so if I want to migrate above code I should create 3 files, let's say:
provider_isloading.dart
,provider_isimageloading.dart
andprovider_obsecurepassword.dart
.
Using StateNotifier
// provider_isloading.dart
class IsImageLoading extends StateNotifier<bool> {
IsImageLoading() : super(false);
void toggleImageLoading(bool value) {
state = value;
}
}
final isImageLoadingProvider = StateNotifierProvider((ref) => IsImageLoading());
// provider_isimageloading.dart
class IsLoading extends StateNotifier<bool> {
IsLoading() : super(false);
void toggleLoading(bool value) => state = value;
}
final isLoadingProvider = StateNotifierProvider((ref) => IsLoading());
// provider_obsecurepassword.dart
class IsObsecurePassword extends StateNotifier<bool> {
IsObsecurePassword() : super(false);
void toggleObsecurePassword(bool value) {
state = !value;
}
}
final isObsecurePasswordProvider = StateNotifierProvider((ref) => IsObsecurePassword());
And I also need to create 1 file to export all of those files:
GlobalStateNotifer.dart
export './provider_loading.dart';
export './provider_imageloading.dart';
export './provider_obsecurepassword.dart';
My question is, is it the best practice to make it as I've explained earlier?