Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty typed list in dart

Tags:

dart

I am trying to convert this dart file here to use generics and I get the following error when trying to initialize an empty list in constructor.

Constant list literals can't include a type parameter as a type argument, such as 'T'. Try replacing the type parameter with a different

How can I create an empty list in this case. Below code can elaboreate my problem even more

old file

enum PostStatus { initial, success, failure }

class PostState extends Equatable {
  const PostState({
    this.status = PostStatus.initial,
    this.posts = const <Post>[],
    this.hasReachedMax = false,
  });

  final PostStatus status;
  final List<Post> posts;
  final bool hasReachedMax;

  PostState copyWith({
    PostStatus status,
    List<Post> posts,
    bool hasReachedMax,
  }) {
    return PostState(
      status: status ?? this.status,
      posts: posts ?? this.posts,
      hasReachedMax: hasReachedMax ?? this.hasReachedMax,
    );
  }

  @override
  List<Object> get props => [status, posts, hasReachedMax];
}

new file

class PagedState<T> extends Equatable {
  const PagedState({
    this.status = PagedStatus.initial,
    this.items = const <T>[], //ERROR HERE
    this.hasReachedMax = false,
  });

  final PagedStatus status;
  final List<T> items;
  final bool hasReachedMax;

  PagedState copyWith({
    PagedStatus status,
    List<T> items,
    bool hasReachedMax,
  }) {
    return PagedState(
      status: status ?? this.status,
      items: items ?? this.items,
      hasReachedMax: hasReachedMax ?? this.hasReachedMax,
    );
  }

  @override
  List<Object> get props => [status, items, hasReachedMax];
}

like image 391
Nux Avatar asked Jan 01 '26 07:01

Nux


1 Answers

As the error says, constant list literals can't use a type parameter, so you must use a non-const literal: <T>[].

However, since it's a default argument and default arguments must be constants, that won't work either. You either will need to:

  • Use a constant sentinel value as the default and replace it with the desired default later:
    const PagedState({
       List<T> items = null,
       this.hasReachedMax = false,
    }) : items = items ?? <T>[];
    
  • Use const [] without the explicit type parameter and let automatic type conversions do the work for you.
like image 159
jamesdlin Avatar answered Jan 06 '26 12:01

jamesdlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!