Dart Functions: Optional Positional Parameters

Dart Functions: Optional Positional Parameters

ยท

2 min read

In dart optional positional parameters are defined within square braces [ ] in a function's parameter list. which means it will be optional that whenever we call function at that it is not mandatory to declare this variable which are in square backet , by default their value shown as null.

But , if we want to define this value then we can simple declare the value in function unlike named parameter we do not need to write named before the value for declare.

I have already write both example to learn easily.

void student(var name ,[ var roll , var age])

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

}

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

}

//Name = Vinit
//Roll No = null
//Age = null
  • In this we only get value of name in function at the call time , so other both files are null shown in output .

  • While , in the below code we can see that when we call function I have pass all three value ,and It all the value are shown without any error even I did not write named parameter before the value.

    
      void student(var name ,[ required var roll , var age])
    
      {
        print("Name = $name");
        print("Roll No = $roll");
        print("Age = $age");
    
      }
    
      void main() {
      student("Vinit" ,10 , 20);
    
      }
    
      //Name = Vinit
      //Roll No = 10
      //Age = 20
    

Did you find this article valuable?

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

ย