In Dart programming, parameters are used to pass data into functions or constructors. Dart supports different types of parameters to provide flexibility when defining and calling functions. Let's explore them with examples:
These parameters are mandatory and must be passed in the correct order.
Example:
void intro(String name, int age){
print('My name is $name & age is $age');
}
void main()
{
intro('Sandeep', 33);
}
Enclosed in square brackets [].
If not provided, they default to null.
Example:
void intro(String name, [int? age])
{
if(age!=null) {
print('Hello, $name! You are $age years old');
}
else {
print('Name is $name');
}
}
void main()
{
intro('Sam',23);
intro('san');
}
Enclosed in curly braces {}.
Can be passed in any order.
Example:
void intro({required String name, required int age})
{
print('Hi! My name is $name & age is $age');
}
void main()
{
intro(name: "Sandewep", age: 45);
//intro(name: 'San'); Error
intro(age: 78, name: "san");
}
Use {} and assign default values to the parameters.
Example:
void intro({ String name="Guest", int age=23})
{
print('Hi! My name is $name & age is $age');
}
void main()
{
intro();
intro(name: "Sandewep", age: 45);
intro(name: 'San');
intro(age: 78, name: "san");
}
Use the required keyword to ensure the parameter must be provided.
Example:
void greet({required String name, required int age}) {
print('Hello, $name! You are $age years old.');
}
void main() {
greet(name: 'Alice', age: 25); // Output: Hello, Alice! You are 25 years old.
}
Note: Omitting a required parameter will result in a compile-time error.
Functions can combine positional, optional positional, and named parameters.
Example:
void describe(String name, [int? age], {String country = 'Unknown'}) {
print('Name: $name, Age: ${age ?? 'Unknown'}, Country: $country');
}
void main() {
describe('Alice', 25, country: 'USA'); // Output: Name: Alice, Age: 25, Country: USA
describe('Bob'); // Output: Name: Bob, Age: Unknown, Country: Unknown
}
Provide default values for optional parameters to avoid null checks.
Example:
void greet(String name, [String title = 'Guest']) {
print('Hello, $title $name!');
}
void main() {
greet('Alice'); // Output: Hello, Guest Alice!
greet('Alice', 'Dr.'); // Output: Hello, Dr. Alice!
}
Functions can be passed as parameters to other functions.
Example:
void main() {
// Calling the function with different parameter combinations
calculateTotal(100, 5, discount: 10, tax: 8); // Example with all parameters
calculateTotal(200, 3, discount: 20); // Example without tax
calculateTotal(150, 4); // Example with only required parameters
}
// Function with a mix of parameters
void calculateTotal(
double price,
int quantity,
{double discount = 0, double tax = 0}) {
// Calculate subtotal
double subtotal = price * quantity;
// Apply discount and tax
double discountedPrice = subtotal - (subtotal * (discount / 100));
double totalPrice = discountedPrice + (discountedPrice * (tax / 100));
// Print the result
print('Subtotal: \$${subtotal.toStringAsFixed(2)}');
print('Discount: ${discount.toStringAsFixed(1)}%');
print('Tax: ${tax.toStringAsFixed(1)}%');
print('Total Price: \$${totalPrice.toStringAsFixed(2)}');
}
Example with Named and Positional Parameters:
class Person {
String name;
int age;
Person(this.name, {required this.age});
void display() => print('Name: $name, Age: $age');
}
void main() {
var person = Person('Alice', age: 25);
person.display(); // Output: Name: Alice, Age: 25
}
Example:
class Person {
String name;
int age;
Person(this.name, this.age);
void display() => print('Name: $name, Age: $age');
}
void main() {
var person = Person('Bob', 30);
person.display(); // Output: Name: Bob, Age: 30
}
void greet(String name, int age) {
print('Hello, $name! You are $age years old.');
}
void main() {
greet('Alice', 25); // Output: Hello, Alice! You are 25 years old.
}
int add(int a, int b) => a + b;
void main() {
print(add(10, 20)); // Output: 30
}
void greet(String name, [int? age]) {
print('Hello, $name! Age: ${age ?? "Unknown"}');
}
void main() {
greet('Alice'); // Output: Hello, Alice! Age: Unknown
greet('Bob', 30); // Output: Hello, Bob! Age: 30
}
void greet(String name, [String title = 'Guest']) {
print('Hello, $title $name!');
}
void main() {
greet('Alice'); // Output: Hello, Guest Alice!
greet('Bob', 'Dr.'); // Output: Hello, Dr. Bob!
}
void greet({required String name, required int age}) {
print('Hello, $name! You are $age years old.');
}
void main() {
greet(name: 'Alice', age: 25); // Output: Hello, Alice! You are 25 years old.
}
void greet({String name = 'Guest', int age = 18}) {
print('Hello, $name! You are $age years old.');
}
void main() {
greet(); // Output: Hello, Guest! You are 18 years old.
greet(name: 'Alice'); // Output: Hello, Alice! You are 18 years old.
}
void describe(String name, {int? age, String country = 'Unknown'}) {
print('Name: $name, Age: ${age ?? "Unknown"}, Country: $country');
}
void main() {
describe('Alice', age: 25, country: 'USA');
describe('Bob');
}
void performOperation(int a, int b, Function operation) {
print('Result: ${operation(a, b)}');
}
void main() {
performOperation(4, 5, (a, b) => a + b); // Output: Result: 9
performOperation(4, 5, (a, b) => a * b); // Output: Result: 20
}
Function createMultiplier(int factor) {
return (int value) => value * factor;
}
void main() {
var triple = createMultiplier(3);
print(triple(4)); // Output: 12
}
void displayDetails({String? name, int? age}) {
print('Name: ${name ?? "Unknown"}, Age: ${age ?? "Unknown"}');
}
void main() {
displayDetails(name: 'Alice'); // Output: Name: Alice, Age: Unknown
}
int sum(List<int> numbers) => numbers.reduce((a, b) => a + b);
void main() {
print(sum([1, 2, 3])); // Output: 6
}
bool isPrime(int n) {
return n > 1 && List.generate(n - 2, (i) => i + 2).every((i) => n % i != 0);
}
void main() {
print(isPrime(7)); // Output: true
print(isPrime(4)); // Output: false
}
String reverse(String input) => input.split('').reversed.join();
void main() {
print(reverse('Dart')); // Output: traD
}
double calculateArea({required double length, required double width}) {
return length * width;
}
void main() {
print(calculateArea(length: 5.0, width: 3.0)); // Output: 15.0
}
void performOperation(Function(int, int) operation) {
print(operation(5, 3));
}
void main() {
performOperation((a, b) => a - b); // Output: 2
}
double power(double base, [int exponent = 2]) {
return base * base;
}
void main() {
print(power(4)); // Output: 16.0
print(power(4, 3)); // Still uses default, Output: 16.0
}
void main()
{
course('android', 'flutter'); //both are required to call
}
void course(String course1, String course2) //bydefault required function
{
print('course1 is $course1');
print('course2 is $course2');
}
-----------------------------------------------------------------------------------------------------
In Dart, a required parameter ensures that a value must be passed to the function when it is called.
You can use required keyword to explicitly specify named parameters as required.
void main() {
double areaOfRectangle({required double length, required double width}) {
return length * width;
}
print("Area: ${areaOfRectangle(length: 5.0, width: 3.0)}"); // Output: Area: 15.0
}
void main() {
String concatenate({required String str1, required String str2}) {
return str1 + str2;
}
print(concatenate(str1: "Hello, ", str2: "World!")); // Output: Hello, World!
}
void main() {
int power({required int base, required int exponent}) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
print("Result: ${power(base: 2, exponent: 3)}"); // Output: Result: 8
}
void main() {
int maxOfTwo({required int a, required int b}) {
return (a > b) ? a : b;
}
print("Greater: ${maxOfTwo(a: 10, b: 20)}"); // Output: Greater: 20
}
void main() {
double simpleInterest({required double principal, required double rate, required double time}) {
return (principal * rate * time) / 100;
}
print("Interest: ${simpleInterest(principal: 1000, rate: 5, time: 2)}"); // Output: Interest: 100.0
}
void main() {
void printFullName({required String firstName, required String lastName}) {
print("Full Name: $firstName $lastName");
}
printFullName(firstName: "Alice", lastName: "Johnson"); // Output: Full Name: Alice Johnson
}
void main() {
double calculateBMI({required double weight, required double height}) {
return weight / (height * height);
}
print("BMI: ${calculateBMI(weight: 70, height: 1.75)}"); // Output: BMI: 22.857142857142858
}
import 'dart:math';
void main() {
double distance({required double x1, required double y1, required double x2, required double y2}) {
return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
print("Distance: ${distance(x1: 1, y1: 2, x2: 4, y2: 6)}"); // Output: Distance: 5.0
}
void main() {
double areaOfTriangle({required double base, required double height}) {
return 0.5 * base * height;
}
print("Area of Triangle: ${areaOfTriangle(base: 10, height: 5)}"); // Output: Area of Triangle: 25.0
}
void main() {
double discountedPrice({required double originalPrice, required double discountPercentage}) {
return originalPrice - (originalPrice * discountPercentage / 100);
}
print("Discounted Price: ${discountedPrice(originalPrice: 200, discountPercentage: 10)}"); // Output: Discounted Price: 180.0
}
You can define optional positional parameters by enclosing them in square brackets ([]).
void main()
{
course('c', 'c++');
course('c', 'c++','java');
}
course(String c1, String c2, [String? c3])
{
print('courses are $c1, $c2, $c3');
}
Ex=
void main()
{
// Function with optional positional parameter
void greet(String name, [String? message]) {
if (message != null) {
print("$message, $name!");
} else {
print("Hello, $name!");
}
}
// Calling the function with and without the optional parameter
greet("Alice");
greet("Bob", "Good morning");
}
------------------------------------------------------------------------------------------------------------------------------
In Dart, positional parameters can be made optional by enclosing them in square brackets ([]). These parameters do not need to be passed when calling the function.
void main() {
void greet(String name, [String title = ""]) {
print("Hello, ${title.isEmpty ? name : '$title $name'}");
}
greet("Alice"); // Output: Hello, Alice
greet("Bob", "Dr."); // Output: Hello, Dr. Bob
}
void main() {
int power(int base, [int exponent = 2]) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
print("5^2: ${power(5)}"); // Output: 25
print("5^3: ${power(5, 3)}"); // Output: 125
}
void main() {
void printAddress(String city, String state, [String? zipCode]) {
print("Address: $city, $state${zipCode != null ? ', $zipCode' : ''}");
}
printAddress("New York", "NY"); // Output: Address: New York, NY
printAddress("Los Angeles", "CA", "90001"); // Output: Address: Los Angeles, CA, 90001
}
void main() {
double area(double length, [double width = 1.0]) {
return length * width;
}
print("Area (length=5): ${area(5)}"); // Output: 5.0
print("Area (length=5, width=3): ${area(5, 3)}"); // Output: 15.0
}
void main() {
void printStudent(String name, [String grade = "Not Assigned"]) {
print("Student: $name, Grade: $grade");
}
printStudent("Alice"); // Output: Student: Alice, Grade: Not Assigned
printStudent("Bob", "A"); // Output: Student: Bob, Grade: A
}
void main() {
void productInfo(String name, double price, [double discount = 0]) {
double finalPrice = price - (price * discount / 100);
print("Product: $name, Price: \$${finalPrice.toStringAsFixed(2)}");
}
productInfo("Laptop", 1000); // Output: Product: Laptop, Price: $1000.00
productInfo("Laptop", 1000, 10); // Output: Product: Laptop, Price: $900.00
}
void main() {
double totalCost(double itemCost, [double shipping = 5.0]) {
return itemCost + shipping;
}
print("Total Cost: \$${totalCost(50)}"); // Output: Total Cost: $55.0
print("Total Cost with free shipping: \$${totalCost(50, 0)}"); // Output: Total Cost: $50.0
}
void main() {
void contactInfo(String name, [String? phone]) {
print("Contact: $name${phone != null ? ', Phone: $phone' : ''}");
}
contactInfo("Alice"); // Output: Contact: Alice
contactInfo("Bob", "123-456-7890"); // Output: Contact: Bob, Phone: 123-456-7890
}
void main() {
void examResult(String student, double score, [String? remarks]) {
print("Student: $student, Score: $score${remarks != null ? ', Remarks: $remarks' : ''}");
}
examResult("Alice", 85.5); // Output: Student: Alice, Score: 85.5
examResult("Bob", 90, "Excellent"); // Output: Student: Bob, Score: 90, Remarks: Excellent
}
void main() {
double calculatePrice(double amount, [double taxRate = 0.05]) {
return amount + (amount * taxRate);
}
print("Price with default tax: \$${calculatePrice(100)}"); // Output: $105.0
print("Price with custom tax: \$${calculatePrice(100, 0.1)}"); // Output: $110.0
}
Dart supports named parameters, which are enclosed in curly braces ({}) and called using their names.
void main() {
// Function with optional named parameters
void describePerson({String? name, int? age}) {
print("Name: ${name ?? "Unknown"}, Age: ${age ?? 0}");
}
// Calling the function with named parameters
describePerson(name: "Alice", age: 25);
describePerson(age: 30);
}
Ex=
void main()
{
int data= volume(3,width:2, length:4);
print(data);
}
int volume(int height, {int? width, int? length})=> length!*width!*height;
-------------------------------------------------------------
Dart, named parameters can be made optional by using curly braces ({}) around them, and you can also set default values for them.
void main() {
void greet(String name, {String title = "Mr./Ms."}) {
print("Hello, $title $name");
}
greet("Alice"); // Output: Hello, Mr./Ms. Alice
greet("Bob", title: "Dr."); // Output: Hello, Dr. Bob
}
void main() {
double area(double length, {double width = 1.0}) {
return length * width;
}
print("Area: ${area(5)}"); // Output: Area: 5.0
print("Area with width: ${area(5, width: 3)}"); // Output: Area: 15.0
}
void main() {
void printUserInfo(String name, {int? age}) {
print("Name: $name${age != null ? ', Age: $age' : ''}");
}
printUserInfo("Alice"); // Output: Name: Alice
printUserInfo("Bob", age: 25); // Output: Name: Bob, Age: 25
}
void main() {
double calculatePrice(double price, {double discount = 0.0}) {
return price - (price * discount / 100);
}
print("Price: ${calculatePrice(100)}"); // Output: Price: 100.0
print("Price with discount: ${calculatePrice(100, discount: 10)}"); // Output: Price: 90.0
}
void main() {
void displayProduct(String name, {int stock = 0}) {
print("Product: $name, Stock: ${stock > 0 ? stock : 'Out of Stock'}");
}
displayProduct("Laptop"); // Output: Product: Laptop, Stock: Out of Stock
displayProduct("Laptop", stock: 5); // Output: Product: Laptop, Stock: 5
}
void main() {
double simpleInterest(double principal, double rate, {double time = 1.0}) {
return (principal * rate * time) / 100;
}
print("Interest: ${simpleInterest(1000, 5)}"); // Output: Interest: 50.0
print("Interest for 2 years: ${simpleInterest(1000, 5, time: 2)}"); // Output: Interest: 100.0
}
void main() {
void createProfile(String name, {String jobTitle = "Unemployed"}) {
print("Name: $name, Job Title: $jobTitle");
}
createProfile("Alice"); // Output: Name: Alice, Job Title: Unemployed
createProfile("Bob", jobTitle: "Engineer"); // Output: Name: Bob, Job Title: Engineer
}
void main() {
void examResult(String student, double score, {String remarks = "No remarks"}) {
print("Student: $student, Score: $score, Remarks: $remarks");
}
examResult("Alice", 85.5); // Output: Student: Alice, Score: 85.5, Remarks: No remarks
examResult("Bob", 90, remarks: "Excellent"); // Output: Student: Bob, Score: 90, Remarks: Excellent
}
void main() {
void orderDetails(String product, double price, {String? deliveryDate}) {
print("Product: $product, Price: $price${deliveryDate != null ? ', Delivery Date: $deliveryDate' : ''}");
}
orderDetails("Laptop", 1200); // Output: Product: Laptop, Price: 1200.0
orderDetails("Tablet", 600, deliveryDate: "2023-12-20"); // Output: Product: Tablet, Price: 600.0, Delivery Date: 2023-12-20
}
void main() {
double generateInvoice(double amount, {double taxRate = 0.05}) {
return amount + (amount * taxRate);
}
print("Invoice without custom tax: ${generateInvoice(100)}"); // Output: Invoice without custom tax: 105.0
print("Invoice with custom tax: ${generateInvoice(100, taxRate: 0.1)}"); // Output: Invoice with custom tax: 110.0
}
Default parameters in Dart allow us to assign default values to function parameters, which means they will use the specified value unless overridden.
void main() {
void greet(String name, {String greeting = "Hello"}) {
print("$greeting, $name!");
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob", greeting: "Hi"); // Output: Hi, Bob!
}
void main() {
double area(double length, {double width = 1.0}) {
return length * width;
}
print("Area: ${area(5)}"); // Output: Area: 5.0
print("Area with width: ${area(5, width: 3)}"); // Output: Area: 15.0
}
void main() {
double calculateInterest(double principal, {double rate = 5.0, double time = 1.0}) {
return (principal * rate * time) / 100;
}
print("Interest: ${calculateInterest(1000)}"); // Output: Interest: 50.0
print("Interest with custom rate: ${calculateInterest(1000, rate: 7.0)}"); // Output: Interest: 70.0
}
void main()
{
void printUserInfo(String name, {int age = 18})
{
print("Name: $name, Age: $age");
}
printUserInfo("Alice"); // Output: Name: Alice, Age: 18
printUserInfo("Bob", age: 25); // Output: Name: Bob, Age: 25
}
void main()
{
double totalCost(double itemCost, {double shipping = 5.0}) {
return itemCost + shipping;
}
print("Total Cost: \$${totalCost(50)}"); // Output: Total Cost: $55.0
print("Total Cost with free shipping: \$${totalCost(50, shipping: 0)}"); // Output: $50.0
}
void main() {
void productInfo(String name, {int stock = 10}) {
print("Product: $name, Stock: $stock");
}
productInfo("Laptop"); // Output: Product: Laptop, Stock: 10
productInfo("Laptop", stock: 5); // Output: Product: Laptop, Stock: 5
}
void main() {
double generateInvoice(double amount, {double taxRate = 0.05}) {
return amount + (amount * taxRate);
}
print("Invoice without custom tax: ${generateInvoice(100)}"); // Output: Invoice without custom tax: 105.0
print("Invoice with custom tax: ${generateInvoice(100, taxRate: 0.1)}"); // Output: Invoice with custom tax: 110.0
}
void main() {
void printAddress(String city, String state, {String country = "USA"}) {
print("Address: $city, $state, $country");
}
printAddress("New York", "NY"); // Output: Address: New York, NY, USA
printAddress("Toronto", "ON", country: "Canada"); // Output: Address: Toronto, ON, Canada
}
void main() {
void examResult(String student, double score, {double passingScore = 50.0}) {
String result = (score >= passingScore) ? "Passed" : "Failed";
print("Student: $student, Score: $score, Result: $result");
}
examResult("Alice", 85); // Output: Student: Alice, Score: 85, Result: Passed
examResult("Bob", 45); // Output: Student: Bob, Score: 45, Result: Failed
}
void main() {
double calculateSalary(double baseSalary, {double bonus = 100.0}) {
return baseSalary + bonus;
}
print("Salary with default bonus: \$${calculateSalary(2000)}"); // Output: Salary with default bonus: $2100.0
print("Salary with custom bonus: \$${calculateSalary(2000, bonus: 300)}"); // Output: Salary with custom bonus: $2300.0
}