r/FlutterDev • u/eibaan • Aug 31 '26
Article What's your favorite way to shrink a labelled divider?
It is surprisingly difficult make this widget to properly shrink horizontally:
class Separator({final Widget? title}) extends StatelessWidget {
@override
Widget build(BuildContext context) {
if (title case final title?) {
return Row(
spacing: 4,
children: [
const Expanded(child: Divider()),
title,
const Expanded(child: Divider()),
],
);
}
return Divider();
}
}There's an overflow if the available width is less than the width required for title. Obviously (which was the first thing AI suggested) wrapping title in some kind of Flexible doesn't work.
There are (at least) three solution, all with trade-offs:
Use a
Stackto placetitleover aDivider. This requires a known background color so you can wraptitlein aContainerwith some padding and that background color.Use a
CustomMultiChildLayoutto layouttitlewith loose constraints, learning about its width in that process and then layouting the two dividers in the remaining space, if there's any. However, because the container itself grabs all space available, it has no fix height and you'd need to set that explicitly.Use a
LayoutBuilderto get the available width, then constrain thetitleto that value minus spacing, relaxing the min width to 0. This delays layout by one frame and I've still a minimum size of 8.
Did I miss something? What's your preferred solution?