adding a new value to a class of list dart

Viewed 657

How can i add a new index to a class of list? i have created a class that force the user to enter just 5 items. But i can not add items to this class from outside. if i created the variable ListOf5<Asset> list5; how can i add item like solist5.add(something)?

the code is:

class ListOf5<T> extends ValueObject<AddProductValueFailures,List<T>>{
  ListOf5._(this.value);
  static const maxLength=5;
  @override
  Either<AddProductValueFailures, List<T>>  value;
  // List Length Validator
  factory ListOf5({required List<T> listOfPickedImages}){
    return ListOf5._(imagePickerValidator<T>(maxLength:maxLength ,ImagesList: listOfPickedImages));
  }
  // List Length
  // 0 is empty or more than 5
 int get length=> value.getOrElse(() => []).length;
 
 // Is List Full
 bool isFull()=>length==maxLength;
}
1 Answers

I think it will be simpler to make it as a class that wraps the List class.

class ListOf5<T> {
  final List<T> _data = [];

  bool add(T data) {
    if (_data.length == 5) {
      return false;
    }
    _data.add(data);
    return true;
  }

  // Add other methods
  int get length => _data.length;
  bool get isFull => _data.length == 5;
}

This way the implementation of the class can be simpler and other implementation details can be done from outside of this class.

Related