代码之家  ›  专栏  ›  技术社区  ›  Sayed M. Idrees

如何在没有构造函数的情况下初始化自定义对象列表[Dart/flatter]

  •  0
  • Sayed M. Idrees  · 技术社区  · 4 年前

    我一直面临这个问题,我有一个模拟类,带有静态值用于测试。 但我无法为自定义对象类创建一个列表,该类没有如下构造函数。

    class Video { 
      
      Video();  //this is default constructor
    
      late int id;
      late String name;
    }
    

    问题: 现在我想初始化一个静态列表。

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

    我不想改变类构造函数。

    有没有办法在没有构造函数的情况下初始化自定义类的列表?

    1 回复  |  直到 4 年前
        1
  •  1
  •   dumazy    4 年前

    从技术上讲,这是可行的:

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

    你基本上是分配 late 创建 Video 例如,但在它出现在列表中之前。

    然而,您可能不需要对这些属性进行后期初始化,而需要为其使用构造函数

    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'),
    ];
    

    当然,这取决于您的用例