Bird
Raised Fist0
Fluttermobile~20 mins

Functions and arrow syntax in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Arrow Function Demo
This screen demonstrates how to use functions and arrow syntax in Flutter by showing a button that updates a greeting message when pressed.
Target UI
-------------------------
| Arrow Function Demo    |
|-----------------------|
|                       |
| Greeting: Hello!      |
|                       |
| [Press Me]            |
|                       |
-------------------------
Display a greeting message text starting with 'Hello!'
Add a button labeled 'Press Me'
When the button is pressed, update the greeting to 'Hello, Flutter!' using a function with arrow syntax
Use a StatelessWidget for the main app and a StatefulWidget for the screen
Starter Code
Flutter
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: ArrowFunctionDemo(),
    );
  }
}

class ArrowFunctionDemo extends StatefulWidget {
  const ArrowFunctionDemo({super.key});

  @override
  State<ArrowFunctionDemo> createState() => _ArrowFunctionDemoState();
}

class _ArrowFunctionDemoState extends State<ArrowFunctionDemo> {
  String greeting = 'Hello!';

  // TODO: Add a function using arrow syntax to update greeting

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Arrow Function Demo')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Greeting: $greeting', style: const TextStyle(fontSize: 24)),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // TODO: Call the arrow function here
              },
              child: const Text('Press Me'),
            ),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Solution
Flutter
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: ArrowFunctionDemo(),
    );
  }
}

class ArrowFunctionDemo extends StatefulWidget {
  const ArrowFunctionDemo({super.key});

  @override
  State<ArrowFunctionDemo> createState() => _ArrowFunctionDemoState();
}

class _ArrowFunctionDemoState extends State<ArrowFunctionDemo> {
  String greeting = 'Hello!';

  void updateGreeting() => setState(() => greeting = 'Hello, Flutter!');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Arrow Function Demo')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Greeting: $greeting', style: const TextStyle(fontSize: 24)),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: updateGreeting,
              child: const Text('Press Me'),
            ),
          ],
        ),
      ),
    );
  }
}

We created a function updateGreeting using arrow syntax. It calls setState with an arrow function to update the greeting variable. This triggers the UI to rebuild and show the new greeting. The button's onPressed directly calls this function, keeping the code clean and simple.

Final Result
Completed Screen
-------------------------
| Arrow Function Demo    |
|-----------------------|
|                       |
| Greeting: Hello, Flutter! |
|                       |
| [Press Me]            |
|                       |
-------------------------
When the user taps the 'Press Me' button, the greeting text changes from 'Hello!' to 'Hello, Flutter!'
Stretch Goal
Add a second button that resets the greeting back to 'Hello!' using another arrow function.
💡 Hint
Create another arrow function that calls setState to reset the greeting, then add a button that calls it.

Practice

(1/5)
1. What does the arrow syntax => in a Flutter function do?
easy
A. It marks a function as private.
B. It declares a function without any return value.
C. It creates a function that returns the expression after the arrow.
D. It defines a function that runs asynchronously.

Solution

  1. Step 1: Understand arrow syntax meaning

    The arrow => is a shortcut for functions that return a single expression.
  2. Step 2: Compare with normal function

    Instead of writing curly braces and return, arrow syntax returns the expression directly.
  3. Final Answer:

    It creates a function that returns the expression after the arrow. -> Option C
  4. Quick Check:

    Arrow syntax = single expression return [OK]
Hint: Arrow syntax means single expression return [OK]
Common Mistakes:
  • Thinking arrow means no return value
  • Confusing arrow with async keyword
  • Assuming arrow marks function private
2. Which of the following is the correct arrow function syntax in Flutter to return the sum of two integers a and b?
easy
A. int sum(int a, int b) => a + b;
B. int sum(int a, int b) { a + b; }
C. int sum(int a, int b) => { return a + b; };
D. int sum(int a, int b) => return a + b;

Solution

  1. Step 1: Check arrow function syntax

    Arrow functions use => followed by an expression without braces or return keyword.
  2. Step 2: Validate each option

    int sum(int a, int b) => a + b; correctly uses arrow syntax with expression a + b. The other options misuse braces or return keyword.
  3. Final Answer:

    int sum(int a, int b) => a + b; -> Option A
  4. Quick Check:

    Arrow function = expression after => without braces [OK]
Hint: Arrow functions omit braces and return keyword [OK]
Common Mistakes:
  • Adding braces {} with arrow syntax
  • Using return keyword after arrow
  • Missing semicolon at end
3. What is the output of this Flutter Dart code?
int multiply(int x, int y) => x * y;
void main() {
  print(multiply(3, 4));
}
medium
A. Error
B. 7
C. 34
D. 12

Solution

  1. Step 1: Understand the multiply function

    The function returns the product of x and y using arrow syntax.
  2. Step 2: Calculate multiply(3, 4)

    3 * 4 equals 12, so the print statement outputs 12.
  3. Final Answer:

    12 -> Option D
  4. Quick Check:

    3 * 4 = 12 [OK]
Hint: Multiply returns product directly with arrow syntax [OK]
Common Mistakes:
  • Adding numbers instead of multiplying
  • Confusing output as string concatenation
  • Thinking arrow syntax causes error
4. Identify the error in this Flutter Dart function using arrow syntax:
int add(int a, int b) => {
  return a + b;
};
medium
A. Missing semicolon after return statement.
B. Arrow functions cannot have braces and return statements.
C. Function must be async to use arrow syntax.
D. Function parameters must be optional.

Solution

  1. Step 1: Check arrow function syntax rules

    Arrow syntax functions must have a single expression without braces or return keyword.
  2. Step 2: Analyze the given code

    The code uses braces and return inside an arrow function, which is invalid syntax.
  3. Final Answer:

    Arrow functions cannot have braces and return statements. -> Option B
  4. Quick Check:

    Arrow syntax = single expression, no braces [OK]
Hint: Arrow syntax disallows braces and return keyword [OK]
Common Mistakes:
  • Adding braces {} in arrow functions
  • Using return keyword after arrow
  • Thinking arrow requires async keyword
5. You want to write a Flutter function using arrow syntax that returns the length of a string only if it is not empty; otherwise, it returns zero. Which is the correct function?
hard
A. int lengthOrZero(String s) => s.isNotEmpty ? s.length : 0;
B. int lengthOrZero(String s) => if (s.isNotEmpty) s.length else 0;
C. int lengthOrZero(String s) => { return s.length; };
D. int lengthOrZero(String s) => s.length > 0;

Solution

  1. Step 1: Use arrow syntax with conditional expression

    Arrow functions can return a single expression, here a ternary operator checks if string is not empty.
  2. Step 2: Validate each option

    int lengthOrZero(String s) => s.isNotEmpty ? s.length : 0; correctly uses ternary with s.isNotEmpty. int lengthOrZero(String s) => if (s.isNotEmpty) s.length else 0; uses invalid if-else syntax. int lengthOrZero(String s) => { return s.length; }; uses braces and return which is invalid for arrow. int lengthOrZero(String s) => s.length > 0; returns a boolean instead of int.
  3. Final Answer:

    int lengthOrZero(String s) => s.isNotEmpty ? s.length : 0; -> Option A
  4. Quick Check:

    Arrow + ternary = conditional return [OK]
Hint: Use ternary inside arrow for conditional return [OK]
Common Mistakes:
  • Using if-else instead of ternary in arrow
  • Adding braces and return in arrow function
  • Returning boolean (length > 0) instead of int
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard