flutterdartblocdart-null-safetydartz

How to initialize Either Right to an empty value in flutter - Reloaded


How do I correctly initialize my Either object in the following code?

class JobListState extends Equatable {
  const JobListState({
    this.status = JobListStatus.initial,
    this.jobListSections = Right([]),
    this.filter,
  });

  final JobListStatus status;
  final Either<Failure, List<JobListViewmodel?>> jobListSections;
  final JobListFilter? filter;

A very similar question was answered 1,5 years ago, but this results in the error The default value of an optional parameter must be constant.

And I guess, if I declare this.jobListSections = const Right([]), I can no longer assign left.

I am assigning the initial value to create the initial state for Bloc.


Solution

  • Because your variables are final you can not change it directly. You can declare copyWith method to change your values.

    class JobListState extends Equatable {
      const JobListState({
        this.status = JobListStatus.initial,
        this.jobListSections = Right([]),
        this.filter,
      });
    
      final JobListStatus status;
      final Either<Failure, List<JobListViewmodel?>> jobListSections;
      final JobListFilter? filter;
    
      JobListState copyWith({
        JobListStatus? status,
        Either<Failure, List<JobListViewmodel?>>? jobListSections,
        JobListFilter? filter
      }) {
         return JobListState(
           status: status ?? this.status,
           jobListSections: jobListSections ?? this.jobListSections,
           filter: filter ?? this.filter
         );
      }
    }
    
    // anywhere you use JobListState
    var state = JobListState(); // state.jobListSections is Right([])
    state = state.copyWith(jobListSections: Left(Failure())); // state.jobListSections is Left
    // here you have new state that you can emit it.