0
0
Fluttermobile~5 mins

Functions and arrow syntax in Flutter

Choose your learning style9 modes available
Introduction

Functions help you organize your code into small reusable pieces. Arrow syntax is a short way to write simple functions.

When you want to reuse a block of code multiple times.
When you want to make your code cleaner and easier to read.
When you need to return a single expression from a function quickly.
When you want to pass a small function as a parameter.
When you want to keep your widget code simple and neat.
Syntax
Flutter
ReturnType functionName(ParameterType parameter) {
  // code block
  return value;
}

// Arrow syntax for single expression functions
ReturnType functionName(ParameterType parameter) => expression;

The arrow syntax is used only for functions with a single expression.

Arrow syntax automatically returns the value of the expression.

Examples
This is a normal function that adds two numbers and returns the result.
Flutter
int add(int a, int b) {
  return a + b;
}
This is the same add function written with arrow syntax for simplicity.
Flutter
int add(int a, int b) => a + b;
A function with no return value that prints a message using arrow syntax.
Flutter
void printHello() => print('Hello!');
Sample App

This Flutter app shows two texts. One uses a normal function to multiply numbers. The other uses arrow syntax to greet a person.

Flutter
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // Function using normal syntax
  int multiply(int x, int y) {
    return x * y;
  }

  // Function using arrow syntax
  String greet(String name) => 'Hello, $name!';

  @override
  Widget build(BuildContext context) {
    int result = multiply(4, 5);
    String message = greet('Alice');

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Functions and Arrow Syntax')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('4 x 5 = $result'),
              Text(message),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Use arrow syntax only for simple functions with one expression.

Functions help keep your code organized and easy to understand.

In Flutter, functions are often used inside widgets to build UI or handle events.

Summary

Functions let you reuse code by grouping instructions.

Arrow syntax is a shortcut for functions with a single return expression.

Use functions to make your Flutter apps cleaner and easier to maintain.