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;

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?


Technically, this would work:

final List<Video> videos = [
  Video() = = '',
  Video() = = '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, required}); 

  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

Answered By – dumazy

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *