Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to initialize list of custom object with no constructor [Dart/Flutter]

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading