Default values of an optional parameter must be constant

后端 未结 2 1551
萌比男神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: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.

提交回复
热议问题