Dart Functions: Default Optional Parameter

Dart Functions: Default Optional Parameter

ยท

2 min read

In dart Default Optional Parameter means that if we do not need to print null value than we can define the value in function , so whenever we do not call the value in main function than by default pre-define value will be print which we have define in function at the time of creation. this method we can use in Named parameter and Optional parameter.

And . if we define the value in main function than the function call the value which is define in the main function and ignore the default value which is ser by default.

I have already write both example to learn easily.

//Named Parameter
void student(var name ,{ var roll })

{
  print("Name = $name");
  print("Roll No = $roll");


}


// Optional Parameter 
void student1(var name ,[ var roll ])

{
  print("Name = $name");
  print("Roll No = $roll");

}

void main() {
student("Vinit");
student1("Jay");

}

Name = Vinit
Roll No = null
Name = Jay
Roll No = null
  • In above example we can see that we use both name and optional parameter and we did not pass any value of this in main function , hence we can see output as null.

  • In below example we use by default value.

    ```dart //Named Parameter void student(var name ,{ var roll = 2 })

    { print("Name = $name"); print("Roll No = $roll");

}

// Optional Parameter void student1(var name ,[ var roll = 2 ])

{ print("Name = $name"); print("Roll No = $roll");

}

void main() { student("Vinit"); student1("Jay");

}

Name = Vinit Roll No = 1 Name = Jay Roll No = 2 ```

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย