Default values of an optional parameter must be constant

后端 未结 2 1552
萌比男神i
萌比男神i 2021-01-12 05:56

Ive been trying to get this right for some time and can\'t figure out what is wrong.

enum MyEnum { a, b }

class ClassA {
  final MyEnum myEnum;
  ClassA({th         


        
相关标签:
2条回答
  • 2021-01-12 06:47

    For ClassA to be able to create constant values, the constructor must be marked as const.

    enum MyEnum { a, b }
    
    class ClassA {
      final MyEnum myEnum;
      const ClassA({this.myEnum = MyEnum.a});  // <- constructor is const.
    }
    
    class ClassB {
      final ClassA classA;
      ClassB({this.classA = const ClassA()}); // <- creation is const
    }
    

    You need to write const for the object creation, even if only constant values are allowed as default values. The language do not automatically insert a const in that position because the language team wants to reserve the option of allowing non-constant default values at some point.

    0 讨论(0)
  • 2021-01-12 06:51

    Try

    enum MyEnum { a, b }
    
    class ClassA {
      final MyEnum myEnum;
      ClassA({this.myEnum});
    }
    
    class ClassB {
      final ClassA classA;
      ClassB({this.classA}); // ClassA expression is underlined with red
    }
    

    no need for '=' operator. It will automatically assign the value when you will pass it to the constructor.

    Use the '=' operator only when you need to pass a default value to your variables hence, making them optional parameters.

    Edit

    enum MyEnum { a, b }
    
    class ClassA {
      final MyEnum myEnum;
      const ClassA({this.myEnum = MyEnum.a});
    }
    
    class ClassB {
      final ClassA classA;
      ClassB({this.classA = const classA()}); // ClassA expression is underlined with red
    }
    

    This is the only way i could find to achieve what you want, the constructor should be default

    This is called a canonicalized constructor.

    0 讨论(0)
提交回复
热议问题