Reputation: 75
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?
Upvotes: 3
Views: 156
Reputation: 141
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.
Upvotes: 1