Flutter Tricks
Published on

Circular Avatars in Flutter: A Complete Guide

Circular avatars are a common design element in many mobile apps. They're a great way to showcase user profile pictures or app icons in a visually appealing way. In this guide, we’ll show you how to create and customize circular avatars in Flutter.

Creating a Circular Avatar

Creating a circular avatar in Flutter is quite straightforward, thanks to the CircleAvatar widget. This widget automatically shapes its child widget into a circle, making it perfect for avatars.

Here is a simple example:

CircleAvatar(
  radius: 50,
  backgroundImage: NetworkImage('https://link-to-image.com/image.jpg'),
),

In this example, we set the radius property to determine the size of the avatar. The backgroundImage property is used to set the image for the avatar, using the NetworkImage widget, which grabs an image from a URL.

Customizing Your Avatar

Flutter makes it easy to customize your avatars. You can add a border, change the background color, add initials when there's no image, and more.

Here's an example of a customized circular avatar:

CircleAvatar(
  radius: 50,
  backgroundColor: Colors.blue,
  backgroundImage: NetworkImage('https://link-to-image.com/image.jpg'),
  onBackgroundImageError: (_, __) => {},
  child: Text(
    'JD',
    style: TextStyle(
      color: Colors.white,
      fontSize: 40,
    ),
  ),
)

In this example, we've added a few new elements. The backgroundColor property sets a background color for the avatar. The child property adds text to the avatar, which can be useful for displaying initials when there's no image available. The onBackgroundImageError property is a function that's called when the NetworkImage fails to load. In this case, we've provided an empty function as a placeholder – you can fill this in with your own error handling code.

Final Thoughts

Creating and customizing circular avatars in Flutter is a simple but effective way to add polish to your app's user interface. The CircleAvatar widget is flexible and customizable, making it easy to create avatars that fit your app's design needs. Whether you're just starting out with Flutter or are a seasoned developer, I hope this guide has been helpful to you. Happy coding!