In Flutter, the IconButton widget is a button that contains an icon. It is commonly used to create simple buttons with icons for various actions in your application. Here are some of the key attributes and properties of the IconButton widget:
Attributes and Properties:
icon: The icon to be displayed on the button. It typically takes an instance of the Icon widget or any other widget that represents an icon.
onPressed: A callback function that is triggered when the button is pressed.
tooltip: A text that appears as a label when the user long-presses the button.
Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('IconButton Example'),
),
body: Center(
child: IconButton(
icon: Icon(Icons.favorite),
onPressed: () {
// Handle button press
print('Button Pressed!');
},
tooltip: 'Like',
),
),
),
);
}
}
In this example, we have a simple Flutter application with a single screen (Scaffold) containing an AppBar and a Center widget. Inside the Center widget, we use the IconButton with a heart-shaped icon from the Material Icons library. The onPressed callback is set to print a message to the console when the button is pressed.
Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('IconButton Full Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Press the IconButton:',
style: TextStyle(fontSize: 18),
),
SizedBox(height: 20),
IconButton(
icon: Icon(Icons.thumb_up),
onPressed: () {
// Handle button press
print('Thumbs Up!');
},
tooltip: 'Like',
color: Colors.blue,
iconSize: 40,
),
],
),
),
);
}
}
In this example, we've added a bit more structure to the app by creating a separate MyHomePage class. The IconButton is customized with additional properties such as color and iconSize. The onPressed callback still prints a message to the console when the button is pressed.