0

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.

w461
  • 2,168
  • 4
  • 14
  • 40
  • If you want to have final fields and a const constructor, you will not be able to set the field to another value. Why do you want it to be final and then assign a new value? You can create another instance if you want to keep the immutable state. – VincentDR Nov 14 '22 at 09:15
  • Equatable requires final values to my understanding – w461 Nov 14 '22 at 09:25
  • Yes, then you need to create a new instance when changing value You create a new instance of your object, and you pass it to a new instance of the bloc'state. – VincentDR Nov 14 '22 at 09:28

1 Answers1

1

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. 
Reza M
  • 544
  • 3
  • 10
  • I had a thinking error. Actually the whole thing is about `copyWith`. And you are absolutely right, when I use `copyWith` I no longer care that `Right([])` is a constant. So I can also declare it as `this.jobListSections = const Right([])` – w461 Nov 14 '22 at 09:41