What is required?
The required keyword marks a named parameter as mandatory — the caller must provide it. Without required, named parameters are optional by default. With null safety, required is essential for non-nullable named parameters.
Syntax
void greet({required String name, required int age}) {
print('Hello $name, you are $age years old!');
}
void main() {
greet(name: 'Alice', age: 25); // OK
// greet(name: 'Bob'); ← COMPILE ERROR: age is required
}
required vs Optional Parameters
| Scenario | Declaration | Must provide? |
| Optional with default | {String name = 'Guest'} | No |
| Optional nullable | {String? name} | No (defaults to null) |
| Required non-nullable | {required String name} | Yes ✅ |
required in Classes
Use required in class constructors to enforce mandatory fields:
class User {
final String name;
final String email;
final int age;
User({
required this.name,
required this.email,
required this.age,
});
@override
String toString() => 'User($name, $email, age=$age)';
}
void main() {
var user = User(name: 'Alice', email: 'alice@example.com', age: 28);
print(user);
// User(Alice, alice@example.com, age=28)
}
Example
class Product {
final String id;
final String name;
final double price;
final String? description; // optional
Product({
required this.id,
required this.name,
required this.price,
this.description, // no required — defaults to null
});
}
void main() {
var p1 = Product(id: 'P001', name: 'Laptop', price: 999.99);
var p2 = Product(
id: 'P002',
name: 'Phone',
price: 499.99,
description: 'Latest model smartphone',
);
print('$${p1.name}: \$$${p1.price}');
print('$${p2.name}: $${p2.description}');
}
Output:Laptop: $999.99
Phone: Latest model smartphone
🧠 Quiz
1. What happens if you omit a required named parameter when calling a function?
- A) Runtime error
- B) Compile error ✅
- C) Uses null as default
- D) Uses empty string
2. Can a required parameter also be nullable (String?)?
- A) No
- B) Yes ✅
- C) Only if it has a default
- D) Only in constructors
Summary
The required keyword enforces that named parameters must be provided by the caller. Omitting a required parameter is a compile-time error. Use it in functions and class constructors to make the API clear and safe, especially for non-nullable named parameters.