0
0
FlutterConceptBeginner · 3 min read

What is IconButton in Flutter: Simple Explanation and Example

IconButton in Flutter is a clickable button widget that shows an icon instead of text. It lets users tap the icon to trigger an action, like going back or opening a menu.
⚙️

How It Works

Think of IconButton as a small picture on your app screen that you can tap, just like pressing a button on a remote control. Instead of words, it shows an icon, such as a heart, a menu, or a back arrow.

When you tap the icon, it runs a piece of code you provide, called a callback. This callback is like telling the app, "Hey, do this now!" For example, it might open a new page or like a post.

The IconButton widget handles the look and the tap detection, so you only need to decide what icon to show and what happens when it is tapped.

💻

Example

This example shows a simple IconButton with a heart icon. When tapped, it prints a message in the console.

dart
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(
      home: Scaffold(
        appBar: AppBar(title: const Text('IconButton Example')),
        body: Center(
          child: IconButton(
            icon: const Icon(Icons.favorite),
            color: Colors.red,
            iconSize: 40,
            onPressed: () {
              print('Heart icon tapped!');
            },
          ),
        ),
      ),
    );
  }
}
Output
A red heart icon button appears centered on the screen. When tapped, the console shows: Heart icon tapped!
🎯

When to Use

Use IconButton when you want a button that is just an icon without text. It is perfect for toolbar actions, like search, favorite, share, or navigation buttons.

For example, apps often use IconButton for a back arrow in the top left corner or a menu icon in the top right corner. It keeps the interface clean and easy to understand.

Key Points

  • IconButton shows an icon that acts like a button.
  • It requires an icon and an onPressed callback.
  • You can customize its color, size, and tooltip.
  • It is commonly used in app bars and toolbars.
  • It improves user experience by providing clear, tappable icons.

Key Takeaways

IconButton is a Flutter widget that displays a tappable icon as a button.
It needs an icon and a function to run when tapped (onPressed).
Use IconButton for toolbar actions like back, favorite, or menu icons.
You can easily change its color, size, and add tooltips for accessibility.
It helps keep app interfaces simple and intuitive with icon-only buttons.