What is the @required annotation in Dart?
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
@requiredannotation is now replaced by therequiredkeyword.
Code
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();}
Explanation
-
Lines 1–14: We defined a class called
AddNum, which has two parameters,xandy, and a method calleddisplayMessage(). In theAddNumclass:- Line 2: We define the
xparameter of typeint. - Line 3: We define the
yparameter of typeint. - Lines 5–8: We define the class constructor. Next, we make the
xparameterrequiredand assign a default value to theyparameter. - Lines 10–13: We define the
displayMessage()method that sum up the values ofxandy, and display the result.
- Line 2: We define the
-
Line 15: We define the
main()function. -
Line 17: We create an instance of the class
AddNumand assign value to therequiredparameterx. -
Line 18: We called the
displayMessage()method using the class’s objectaddNum. -
Line 20: We use the
print()function to display a message. -
Line 21: We create another class’s object called
addNumbersand reassign values to the parameters. -
Line 22: We called the
displayMessage()method using the class’s objectaddNumbers.
Free Resources