【问题标题】:Assign default value in flutter constructor在颤振构造函数中分配默认值
【发布时间】:2021-06-08 19:48:04
【问题描述】:

我有一个名为 vendor 的类

class Vendor {
    int id;
    String name;
    
   Vendor({this.id , this.name});
}

现在我有另一个班级的人,在这个班级我有一个供应商列表,我想在个人构造函数中设置默认值:

class Person {
      List<Vendor> vendor;
   
      Person({this.vendor});
 }

我已经尝试过这个解决方案,但它不起作用

class Person {
       List<Vendor> vendor;
      Person({this.vendor}) : vendor = vendor ?? const [];
 }

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以使用= 为可选的构造函数参数设置默认值:

    class Foo {
      final List<String> strings;
      Foo({this.strings = const ['example']});
    }
    
    class Bar {
      final List<String> strings;
      Bar([this.strings = const ['example']]);
    }
    
    print(Foo().strings);  // prints '[example]'
    print(Bar().strings);  // prints '[example]'
    

    注意,作为可选参数传入的值必须是const

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 2021-05-06
      • 2017-11-16
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多