Issue
void main() {
final square = Square(side: 10.0);
print(square.area());
}
abstract class Shape {
double area();
}
class Square implements Shape {
Square({this.side});
final double side;
double area() => side * side;
}
Solution
Your Square class has a member declared final double side;. With Dart 2.12 and null-safety enabled, this means that side is not allowed to be null.
The constructor for your Square class is Square({this.side});. It initializes side using an optional named parameter. If callers neglect to provide an argument for an optional parameter, it will be initialized to its default value. If no default value is specified, null will be used. In this case, that therefore contradicts the declaration that side cannot be null.
There are multiple ways to fix this; pick the one most appropriate for your needs:
- Make the
sidemember nullable:final double? side;. (Note that this would require adding null-checks everywhere thatsideis used. This is likely not what you want for your particular case.) - Provide a non-null default value for
side:Square({this.side = 0});. - Make
sidenon-optional by marking it as a required named parameter (Square({required this.side});) or as a required positional parameter (Square(this.side);).
Answered By - jamesdlin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.