Build: IconButton Demo
This screen shows an IconButton that changes a text message when pressed.
Target UI
--------------------- | IconButton Demo | |-------------------| | [IconButton] | | | | Message: | | | | | ---------------------
--------------------- | IconButton Demo | |-------------------| | [IconButton] | | | | Message: | | | | | ---------------------
import 'package:flutter/material.dart'; class IconButtonDemo extends StatefulWidget { @override State<IconButtonDemo> createState() => _IconButtonDemoState(); } class _IconButtonDemoState extends State<IconButtonDemo> { String message = 'Press the icon'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('IconButton Demo'), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ // TODO: Add IconButton here // TODO: Add Text widget here to show message ], ), ), ); } }
import 'package:flutter/material.dart'; class IconButtonDemo extends StatefulWidget { @override State<IconButtonDemo> createState() => _IconButtonDemoState(); } class _IconButtonDemoState extends State<IconButtonDemo> { String message = 'Press the icon'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('IconButton Demo'), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ IconButton( icon: Icon(Icons.favorite), color: Colors.red, iconSize: 48.0, onPressed: () { setState(() { message = 'You pressed the heart!'; }); }, tooltip: 'Favorite', ), SizedBox(height: 16), Text( message, style: TextStyle(fontSize: 18), ), ], ), ), ); } }
We use a StatefulWidget to keep track of the message text. The IconButton shows a heart icon in red color and a bigger size for visibility. When the user taps the IconButton, the onPressed callback runs, updating the message state to 'You pressed the heart!'. The Text widget below shows the current message. The UI is centered vertically and horizontally using Center and Column with mainAxisSize.min to keep content compact.
--------------------- | IconButton Demo | |-------------------| | ♥ | | | | You pressed the | | heart! | | | ---------------------
IconButton widget primarily display in a Flutter app?onPressed for tap actions, not onTap or onClick.() { print('Clicked'); } is correct. Passing print('Clicked') directly calls it immediately, which is wrong.IconButton( icon: Icon(Icons.volume_up), onPressed: null, )
onPressed to null disables the IconButton, making it unclickable.IconButton(
icon: Icon(Icons.search),
onPressed: print('Search pressed'),
)print('Search pressed') immediately and assigns its result (void) to onPressed, which is wrong.() { print('Search pressed'); } or () => print('Search pressed').tooltip, not hint or label.onPressed as a function, not onTap or a direct call.tooltip and onPressed with a function, so it is correct.Pass the test and this pattern moves unknown