0

I've been facing this issue, I have a mock class with static values for testing. but I am unable to create a list for custom Object class which has no constructor as following.

class Video { 
  
  Video();  //this is default constructor

  late int id;
  late String name;
}

Problem: Now I want to initialize a static list.

final List<Video> videos = [
  new Video({id = 1, name = ""}) //but this gives an error. 
];

I don't want to change class constructor.

Is there any way to initialize list of custom class without constructor?

1
  • 1
    var videos = [Video()..id = 1..name = ''];. However, you really should fix the class constructor, especially with late variables. Commented Feb 12, 2022 at 8:15

1 Answer 1

1

Technically, this would work:

final List<Video> videos = [
  Video()..id = 1..name = '',
  Video()..id = 2..name = 'another',
];

You basically assign the late properties after creating the Video instance, but before it's in the list.

However, it's likely that you don't need those properties to be late-initizalized and rather use a constructor for it

class Video { 
  
  Video({required this.id, required this.name}); 

  int id;
  String name;
}

final List<Video> videos = [
  Video(id: 1, name: ''),
  Video(id: 2, name: 'another'),
];

But that depends on your use case, of course

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @dumazy, the double dots annotation worked for me in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.