build method
- BuildTrigger trigger
override
Recalculates the state of the repository.
This method is called when:
- The repository is first initialized.
- A repository watched via watch emits a new state.
- This repository is updated (if updateInterval is not Duration.zero).
Override this method to handle changes from said repositories.
Example:
class MyRepository extends Repository<MyState> {
final OtherRepository _otherRepository;
MyRepository(this._otherRepository) : super(MyState.new) {
watch(_otherRepository);
}
@override
FutureOr<void> build(BuildTrigger trigger) async {
if(trigger is InitialBuildTrigger) {
// Do something when the repository is first initialized
}
if(trigger is UpdateTrigger) {
// Do something when the repository is updated
}
if(trigger is OtherRepository) {
// Do something when the other repository emits a new state
}
}
}
Implementation
@override
FutureOr<void> build(BuildTrigger trigger) async {
if (trigger is! InitialBuildTrigger) return;
if (_state != null && isAuthenticated) {
log('Global state present and user is authenticated, skipping storage check');
return;
}
if (_state != null && !isAuthenticated) {
log('Global state present, however user the is unauthenticated. Discarding state.');
_state = null;
}
if (!await _localStorage.exists<Set<Token>>()) {
log('No token found in storage');
data({});
return;
}
final tokens = await _localStorage.read<Set<Token>>();
for (final token in tokens) {
final valid = await _auth.verifyToken(token);
if (!valid) {
log('Token $token is invalid. Setting clearing state.');
await logout();
return;
}
}
data(tokens);
if (isAuthenticated) PostHog().enable();
}