Menu
CoddyTech

Your Own Functions

Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 6 of 34.

When two buttons do the same thing, you can write the code once and give it a name. That is a function:

void sayHello() {
  print('Hello!');
}

sayHello is its name, the code inside the braces is what it does, and void means it gives nothing back. Write it on its own, outside class MyApp, for example right under main.

To run it, write its name with parentheses: sayHello();. To hand it to a button, write the name without them:

ElevatedButton(onPressed: sayHello, child: Text('Hi'))

Without parentheses you give the button the function itself, and the button runs it on every tap. With them, onPressed: sayHello(), Dart would run it right away and hand the button its result, which is nothing, so the code does not compile.

challenge icon

Challenge

Easy

Both buttons should print Hello!. Write a function sayHello that prints Hello!, and give it to the Say hello button and to the floating button with the waving hand.

Try it yourself

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              print('Hello!');
            },
            child: Text('Say hello'),
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.waving_hand),
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Making It Interactive

Practice on your own: Online Flutter compiler