Update What is Riverpods authored by Andrew Januszko's avatar Andrew Januszko
asdasd # What is it?
\ No newline at end of file
Riverpods is an implementation of the observer pattern that allows you to create providers and notifiers to watch the state of data in an app.
# Why do we need it?
Riverpods is used so we can manage the state of views that are presented to the user. So if a user inputs data and the screen needs to change dynamically, a provider can do it.
# How do we use it?
In our project, you need to create a ManagerState, Manager, and a widget to act as a consumer.
## ManagerState
The manager state handles the state of what can be changed by the user. This state is used by the manager.
```dart
class NetworkManagerState with _$NetworkManagerState {
///
/// Constructor.
///
const factory NetworkManagerState({
@Default('localhost:8080') baseURL,
}) = _NetworkManagerState;
const NetworkManagerState._();
}
```
## Manager
The manager acts as the controller of the state. The functions inside the manager can change and access the state.
```dart
class NetworkManager extends StateNotifier<NetworkManagerState> {
///
/// Constructor.
///
NetworkManager({
NetworkManagerState? state,
}) : super(
state ?? const NetworkManagerState(),
);
///
/// Set base url for Service client.
///
void setBaseURL() {
String baseURL;
debugPrint('--- BEGIN base URL Dump ---');
if (kDebugMode) {
debugPrint('Mode: debug');
if (Platform.isAndroid) {
baseURL = dotenv.get('API_DEBUG_ANDROID');
} else {
baseURL = dotenv.get('API_DEBUG_IOS');
}
} else if (kProfileMode) {
debugPrint('Mode: profile');
baseURL = dotenv.get('API_PROFILE');
} else {
debugPrint('Mode: release');
baseURL = dotenv.get('API_RELEASE');
}
debugPrint('baseURL: $baseURL');
debugPrint('--- END base URL Dump ---');
state = state.copyWith(
baseURL: baseURL,
);
}
///
/// Get the current location of the user.
///
Future<Location> getLocation() async {
final response = await getCurrentLocation();
debugPrint('--- BEGIN Location Dump ---');
final location = response.when(
data: (data) {
debugPrint('Response Type: Data');
return Location(
longitude: data.longitude,
latitude: data.latitude,
);
},
failure: (failure) {
debugPrint('Response Type: Failure');
return const Location(
longitude: -999,
latitude: -999,
);
},
);
debugPrint('Location: ${location.toString()}');
debugPrint('--- END Location Dump ---');
return location;
}
}
```
## Widget Consumer
The widget consumer watches a manager and updates the view accordingly.
```dart
container.read(NetworkProvider.networkController.notifier).setBaseURL();
container.refresh(NetworkProvider.serviceClient);
```
# How can I use this with build runner?
Since our state has boilerplate auto-generated by build runner, you need to run the `autogenerate.sh` file to rebuild the boiler plate if anything changes.
\ No newline at end of file