build method

  1. @override
FutureOr<void> build(
  1. BuildTrigger trigger
)
override

Recalculates the state of the repository.

This method is called when:

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 {
  final tokens = waitForData(_auth);

  _isHandlingAuthChange = true;

  if (tokens.isEmpty) {
    log('User is unauthenticated');

    error(
      AuthException(
        '',
        Webservice.lb_planner_api,
        message: (reason, webservice) {
          return 'User is not authenticated';
        },
      ),
    );

    _isHandlingAuthChange = false;

    return;
  }

  try {
    log('Fetching user data');

    final user = await _userDatasource.getUser(tokens[Webservice.lb_planner_api]);

    log('User data fetched successfully');

    data(user);

    await PostHog().identify(
      distinctId: sha256.convert(user.id.toString().codeUnits).toString(),
      properties: {
        'capabilities': user.capabilities.map((c) => c.name).toList(),
      },
    );

    _isHandlingAuthChange = false;

    return;
  } catch (e, s) {
    log('Failed to fetch user data', e, s);
  }

  _isHandlingAuthChange = false;
}