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 @required annotation is now replaced by the required keyword.

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 parameter
this.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, x and y, and a method called displayMessage(). In the AddNum class:

    • Line 2: We define the x parameter of type int.
    • Line 3: We define the y parameter of type int.
    • Lines 5–8: We define the class constructor. Next, we make the x parameter required and assign a default value to the y parameter.
    • Lines 10–13: We define the 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

Copyright ©2025 Educative, Inc. All rights reserved