In Dart, the @required
annotation indicates that a named parameter must have a value assigned to it for the class where it is defined to work correctly.
It specifies that a named parameter is not optional.
Note: Since the release of Dart 2.12(Null safety) and subsequent versions, the
@required
annotation is now replaced by therequired
keyword.
The following example shows how to use Dart’s @required
annotation.
class AddNum {final int x;final int y;AddNum({required this.x, // required parameterthis.y = 1, // assigned default value});void displayMessage(){var sum = x + y;print("Sum of $x and $y: $sum");}}void main() {var addNum = AddNum(x:10);addNum.displayMessage();print('Reassigning values =====');var addNumbers = AddNum(x:8, y: -5);addNumbers.displayMessage();}
Lines 1–14: We defined a class called AddNum
, which has two parameters, x
and y
, and a method called displayMessage()
.
In the AddNum
class:
x
parameter of type int
.y
parameter of type int
.x
parameter required
and assign a default value to the y
parameter.displayMessage()
method that sum up the values of x
and y
, and display the result.Line 15: We define the main()
function.
Line 17: We create an instance of the class AddNum
and assign value to the required
parameter x
.
Line 18: We called the displayMessage()
method using the class’s object addNum
.
Line 20: We use the print()
function to display a message.
Line 21: We create another class’s object called addNumbers
and reassign values to the parameters.
Line 22: We called the displayMessage()
method using the class’s object addNumbers
.
Free Resources