How to initialize Either Right to an empty value in flutter

1.5k views Asked by At

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?

2

There are 2 answers

6
Robert Sandberg On BEST ANSWER

Have this go:

Either<Failure, List<Product?>> _products = right([]);
0
flutter_bee On

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

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

read more about it here