Flutter Dart Create Function With Default Optional Arguments Example Tutorial

Functions are basically a set of statements which allows user to perform a certain task when needed. Basically function should be same on defining time and calling time like their arguments should be same. But we can easily manage them in Dart and assign default values to function. So when app user dose not pass certain value with function it’ll call the default value. Using this structure we can provide more compatibility to app developer. So in this tutorial we would learn about Flutter Dart Create Function With Default Optional Arguments in Android iOS Example Tutorial.

What we are doing in current tutorial:

We are calculating Area of a rectangle in this tutorial. We would make a function with 2 values Height and Width. Here Height is fixed value and should pass on function calling time. Width however has default value 20. If user dose not pass 2nd value on function calling time then it will by-default call the Width 20 default value and calculate the Area of triangle.

Contents in this project Flutter Dart Create Function With Default Optional Arguments Android iOS Example Tutorial:

1. Import material.dart package in your app’s main.dart file.

2. Create void main runApp() method and here we would call our main MyApp class.

3. Create our main View class named as MyApp extends StatelessWidget. This is our main Widget class.

4. Create a function named as getArea() with 2 parameters. Here Height is not default and should be pass on function calling time. However Width is set as default optional with default value 20. If developer dose not pass Width on function calling time then it would call the default value of Width and then calculate the Area.

5. Create Widget Build area in MyApp. Then would make Scaffold Widget -> Center Widget -> Column Widget.

6. Creating 2 Raised Button widget in Column widget. Now we would call getArea() function with single value from first button and both double values from second button.

7. Complete source code for main.dart file:

Screenshots:

Flutter Dart Create Function With Default Optional Arguments Example Tutorial Flutter Dart Create Function With Default Optional Arguments Example Tutorial

Leave a Reply

Your email address will not be published.