Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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. 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading