Search code examples
flutterdartdart-null-safety

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.

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