In Flutter, the AppBar is a common widget used at the top of many screens. It’s a great place to put your app’s title and other important information that needs to be easily accessible to users.
One way to customize an AppBar in Flutter is by adding icons to it. This can include icons for navigation, settings, sharing, or any other purpose you need them for. In this article, we’ll look at how to add an icon to the AppBar.
Adding Icons with IconButton Widget
You can add an icon to the AppBar by adding an IconButton widget to the actions list of the AppBar.
AppBar( title: Text('My App'), actions: <Widget>[ IconButton( icon: Icon( Icons.settings, color: Colors.white, ), onPressed: () { // do something }, ) ], ),
This code snippet above shows how to add an IconButton widget with the settings icon from Flutter’s material icons library. The Icon widget is used here, which takes in several parameters such as the icon data and its color.
Customizing Icon Colors and Sizes
You can customize the colors of your icons by changing the color parameter when using the Icon widget inside the IconButton.
IconButton( icon: Icon( Icons.settings, size: 30.0, color: Colors.white, ), )
You can also change the size of your icons with the size parameter. Note that this size is relative to the original size which is usually set by the designer.
Using Leading and Actions for Different Icon Positions
In Flutter, when you want to add an icon on either side of the title in your AppBar, you have two properties: leading and actions. The leading property should be used when adding a left-sided icon and the actions property when adding right-sided icons.
AppBar( centerTitle: true, title: Text('AppBar'), leading: IconButton( onPressed: () {}, icon: Icon(Icons.home), ), actions: [ IconButton( onPressed: () {}, icon: Icon(Icons.call), ), IconButton( onPressed: () {}, icon: Icon(Icons.more_vert), ), ], )
This code snippet above shows how to use the leading property for a left-sided icon and the actions property for right-sided icons. The centerTitle property is used here to ensure that the title remains centered.
Conclusion
In this article, we’ve learned how to add icons to an AppBar in Flutter by using the IconButton widget with different properties such as leading, actions, icon color, and size. With these tips and tricks, you can customize your AppBar to suit your app’s needs.
Remember to check out the Flutter documentation for more information on how to use icons in Flutter and also see the See Also section below for related articles.