Search code examples
flutterflutter-layout

Adding text to a CircleAvatar changes its position in the layout


When adding text to a CircleAvatar, its position in the Layout changes slightly. Since my CircleAvatars are displayed in a dynamic ListView, where some will be having text and others just an image, they need to be consistent in size and position.

I'm putting just the code example of the CircleAvatar here, since i think its positioning should be completely independent of its contents.

CircleAvatar(
      backgroundColor: getColor(),
      radius: radius,
      child: Text(
        initials,
        style: Theme.of(context).textTheme.bodyLarge?.copyWith(
              fontSize: radius * 0.8,
            ),
      ),
    );

I tried the following things to get rid of this difference:

  • fit everything in a ConstrainedBox/SizedBox
  • set minRadius/maxRadius of the CircleAvatar
  • centering the text
  • setting TextStyle.height
  • placing the Text via Stack
  • reducing the Size of the Text (changes the amount of the offset, but even a tiny size already messes up the position)

However, nothing of that worked and I couldn't figure out where this difference comes from.

I don't think that it should matter, but it is used in the subtitle of several ListTiles.

Dumbed down example, can easily be tested in DartPad:

ListView(
    shrinkWrap: true,
    physics: const NeverScrollableScrollPhysics(),
    children: const [
      Card(
        child: ListTile(
          title: Text("Item1"),
          subtitle: CircleAvatar(
            backgroundColor: Colors.white,
            radius: 12,
          ),
        ),
      ),
      Card(
        child: ListTile(
          title: Text("Item2"),
          subtitle: CircleAvatar(
            backgroundColor: Colors.white,
            radius: 12,
            child: Text(
              "_",
              style: TextStyle(fontSize: 10),
            ),
          ),
        ),
      ),
    ]),

The layout looks like this

Overlay of two exact same ListTiles to emphasize the change in position, one with a Text(), and one without


Solution

  • I solved it by simply adding an empty Text to the CircleAvatar.

    Not optimal, but at least it's consistent.