简体   繁体   中英

How to create a final member variable in the constructor initialization list using named parameters in Dart?

I have this class that I want to initialize using named parameters, and using those parameters I create the final variable in the initialization list.
But whatever I try, it doesn't seem to work. I have it narrowed down to the following example:

class Test {
  const Test({
    Color color,
    BoxBorder border,
  }) : decoration = const BoxDecoration(color: const color, border: const border);

  final BoxDecoration decoration;
}

But when creating the BoxDecoration I'm getting the following error:
The constructor returns type 'dynamic' that isn't of expected type 'Color'. The same error exists also for the border.
When I remove the const however, I get this:
Invalid constant value.

What am I missing here?

I would have done it like below:

class Test {
   const Test({
    Color color,
    BoxBorder border,
  }): assert(color != null),
      assert(border != null),
      _color = color,
      _border = border;

  final Color _color;
  final BoxBorder _border;
  
  BoxDecoration get decoration  => BoxDecoration(color : _color, border: _border);
  
}

and then you can utilize it like this:

Container(decoration: Test(color: yourColor, border: yourBorder).decoration)

Note that in your case _color and _border has been declered internally and are not accessible outside the Test class. The only accessible field is decoration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM