2

I recently made the switch to null-safety in my flutter project, which brings a new kind of problem when using the Either type (from the dartz package)

For example, before I would have some properties in my class like this:

Either<Failure, List<Product>> _products;

I would then have a function to get the products, and consume it in my view.

However, now with null safety, I need to initialize this property, because it should never be null, instead I would like to have an empty list.

If I do this

Either<Failure, List<Product?>> _products = [];

I get this error

A value of type 'List<dynamic>' can't be assigned to a variable of type 'Either<Failure, List<Product?>>'.

So my question would be, how can I initialize this property to the right value of Either, with an empty list?

Manu
  • 372
  • 2
  • 12

2 Answers2

4

Have this go:

Either<Failure, List<Product?>> _products = right([]);
Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
  • This seems to be working perfectly, thank you! Just a little correction however for those reading, in dartz, it's Right(yourvalue) (with a capital R) – Manu May 25 '21 at 07:05
  • 1
    Great. However your comment is, well not incorrect, but let's say that both works. This is the reason: Either right(R r) => new Right(r); – Robert Sandberg May 25 '21 at 07:06
  • I just came along the same issue. But even when applying the accepted solution I receive `The default value of an optional parameter must be constant.`. And imho I should not write `_products = const right([]);`, because I assume I can no longer assign `Left`, then. – w461 Nov 14 '22 at 07:46
  • 1
    It is not the same premises. It sounds like you are trying to initialize with this "right-empty-value" as the default value for a property in a method call or constructor. The same would occur if you try to initialize with any new object that isn't a constant. Just as your error message says. – Robert Sandberg Nov 14 '22 at 07:52
  • Thanks for your quick response! Yes indeed, the complete line would be `this.jobListSections = Right([]),`. Do you have any idea how to solve this or should I raise a separate question for this? – w461 Nov 14 '22 at 08:03
  • It is most appropriate to create a new question for it, as it will be easier for others to find the same type of question. But there are already equivalent questions that has been asked on the same topic (perhaps not with the object "Either" as parameter, but that is beside the point. Same kind of method that needs to be applied. See e.g. https://stackoverflow.com/search?q=The+default+value+of+an+optional+parameter+must+be+constant – Robert Sandberg Nov 14 '22 at 12:17
-1

you can use the new 'late' keyword that fixes this issue

late Either<Failure, List<Product?>> _products;

read more about it here

flutter_bee
  • 150
  • 9