CodeBlanks Logo Icon CodeBlanks

onPressed and child

Learn the roles of onPressed callback and child content.

Roles of onPressed and child

onPressed is the callback function called when the button is pressed. child is the widget shown inside the button, most often a Text. If you set onPressed to null, the button becomes disabled; it appears gray and cannot be pressed.

ElevatedButton(
  onPressed: null,
  child: Text('Disabled'),
)

child can be different widgets

child is usually a Text widget, but you can give other widgets too. For example, you can put an icon and text inside a Row to make an icon button. child determines the button's size and content.

ElevatedButton(
  onPressed: () {},
  child: Row(
    mainAxisSize: MainAxisSize.min,
    children: [Icon(Icons.save), Text('Save')],
  ),
)

Practice Make a cancel button with ElevatedButton

Write a function cancel that prints Iptal. In main call cancel. Add an ElevatedButton; wire onPressed to cancel and child to Text('Iptal').

Starter code

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

// iptal fonksiyonu yaz: "Iptal" yazdirsin

void main() {
  // iptal'i cagir
  runApp(const Uygulama());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          // ElevatedButton ekle: onPressed ve child ver
          child: SizedBox(),
        ),
      ),
    );
  }
}

Sample solution

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

void iptal() {
  print('Iptal');
}

void main() {
  iptal();
  runApp(const Uygulama());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: iptal,
            child: Text('Iptal'),
          ),
        ),
      ),
    );
  }
}

Expected output

Iptal

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if null is given to the onPressed parameter?

  • The button becomes disabled and cannot be pressed Correct answer
  • An empty function is automatically assigned to onPressed
  • The app crashes
  • child is removed

Explanation: If onPressed is null, ElevatedButton becomes disabled; it appears gray and no callback is called when pressed.

2 Add the child parameter

Question
ElevatedButton(
  onPressed: () {},
  ____: Text('Tamam'),
)
Answer
ElevatedButton(
  onPressed: () {},
  child: Text('Tamam'),
)

Explanation: ElevatedButton's content is set by the child parameter; children, title or subtitle are not valid parameters.

3 onPressed and child

Term Meaning
onPressed Callback called on press
child Widget shown inside the button
null Disables the button
Text Common choice for child

All lessons in Beginner