In flutter basically we would use the normal function syntax where every code we want to execute in function in function body. But it would make the function bigger in size so to make functions smaller in size and easier to update we would use Fat Arrow function declaration method. Using the Fat Arrow we can declare the function in one line without declaring the function body. This is used to make the function in-line in dart flutter. So in this tutorial we would Flutter Dart Create Call Fat Arrow One Line Function Example Tutorial.
Contents in this project Flutter Dart Create Call Fat Arrow One Line Function Example Tutorial:
1. Import material.dart package in your app’s main.dart file.
1 |
import 'package:flutter/material.dart'; |
2. Create void main runApp() method and here we would call our main MyApp class.
1 |
void main() => runApp(MyApp()); |
3. Creating our main MyApp extends StatelessWidget. This is our main Root View class.
1 2 3 4 5 |
class MyApp extends StatelessWidget { } |
4. Create a function named as shortFunction(). In this function we would use the Fat Arrow method to explain function body and pass single Printing statement using Fat Arrow.
Note: – We cannot use Curly Brackets { } with Fat Arrow method so we must declare all the executable code in single line.
1 |
void shortFunction() => print('Fat Arrow One Line Function Called'); |
5. Creating Widget Build area and here we would make a Raised Button widget and call the above declared function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( margin: const EdgeInsets.fromLTRB(20, 0, 20, 0), child: RaisedButton( onPressed: () => shortFunction(), child: Text('Call One Line Short Function'), textColor: Colors.white, color: Colors.red, padding: EdgeInsets.fromLTRB(12, 12, 12, 12), ) ), ]) ) ) ); } |
6. Complete source code for main.dart file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { void shortFunction() => print('Fat Arrow One Line Function Called'); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( margin: const EdgeInsets.fromLTRB(20, 0, 20, 0), child: RaisedButton( onPressed: () => shortFunction(), child: Text('Call One Line Short Function'), textColor: Colors.white, color: Colors.red, padding: EdgeInsets.fromLTRB(12, 12, 12, 12), ) ), ]) ) ) ); } } |
Screenshots:
