In this Flutter post, we will see how to define and use Flutter function. We will be using a proper Flutter example to understand it. Each and everything about Flutter function will be discussed in detail so you can have a proper idea of how to use Flutter function in Flutter apps with ease.
What is Flutter Function?
Flutter function is used to perform an action. It defines some work which can be used again and again using the same code. It helps in removing the bulkiness of code and also make the code more professional. Let’s now understand how to use functions in Flutter practically.
Syntax of Flutter Function
Let’s first see the syntax of Flutter function. See below code:
returnType functionName(parameters){ // do something here }
You can see that first is the return type, which defines what type of value this function will return. Then comes the name of the function. In the parenthesis section, we can define parameters, they are used when you want to pass some values to that function. Finally the body of function in parenthesis, you can perform action and return it to where it is called.
Implementing Flutter Function(Easy Example)
We will be using a Flutter text widget as an example. We will define its properties inside an function and will call it with some custom values. We will also see how to give default value to it.
Define Flutter Function(All Steps)
Text customText(string, size, color, {weight = FontWeight.w500, fontStyle = FontStyle.italic}) { return Text( string, style: TextStyle(fontSize: size, fontWeight: weight, fontStyle: fontStyle), ); }
- You can see that as we using the whole Flutter text widget, so the return type is Text, which is a widget.
- We have given that function a name of our choice.
- As parameters, we have defined both the required and the options parameters. Required are outside the curly braces, inside the curly braces we have defined optional parameters with a default value. Make sure that the optional parameters are written after the required ones.
- In the body of Flutter function, we have returned a Flutter text widget and passing all the defined parameters to the constructors of text widget.
Let’s now see how to call that function. See below code:
Call Flutter Function
customText('This is custom text', 20.0, Colors.blue,weight: FontWeight.w900)
Conclusion
To conclude, hope you now have a clear idea on how to use Flutter function. I would love to have your feedback on this post. Thanks for reading this post.