Flutter: three column Row: how center the middle column when the left and right columns are unequal sizes?

Viewed 562

I have a Flutter Row() with three columns. I want to contents of the middle column 'B' perfectly in the center, no matter how wide the left and right columns are.

Row(children: [Text('AAAAAAAAAA'), Text('B'), Text('C')],
    mainAxisAlignment: MainAxisAlignment.spaceEvenly),

This seems like it should be really easy, but the 'B' is too far right.

I've tried wrapping each Text() with Flexible(..., flex:3) thinking it would do 33% 33% and 33%, but that doesn't work.

I wish there was a widget where the first and third columns are somehow constrained/tied together.

I could "cheat" by wrapping the Text() with SizedBox() but that is inflexible.

2 Answers

You can use Expanded + Center to let 3 columns center in equal spaces (1/3 each)

|----- A -----|----- B -----|----- C -----|

@override
Widget build(BuildContext context) {
  return Row(
    children: [
      Expanded(child: Center(child:Text('AAAAAAAAAA'))),
      Expanded(child: Center(child:Text('B'))),
      Expanded(child: Center(child:Text('C'))),
    ],
  );
}

Or use Stack + Align to make position equally 1/4 between

Align: -1.0     -0.5        0        0.5      1.0
         |------- A ------- B ------- C -------|

@override
Widget build(BuildContext context) {
  return Stack(
    children: [
      Align(alignment: Alignment(-0.5, 0), child: Text('AAAAAAAAAA')),
      Align(alignment: Alignment(0, 0), child: Text('B')),
      Align(alignment: Alignment(0.5, 0), child: Text('C')),
    ],
  );
}

Works using a Stack widget. Don't know whether you strictly need a Row.

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              child: Text('AAAAAAAAAA'),
            ),
            Container(
              child: Text('C'),
            ),
          ],
        ),
        Positioned.fill(
          child: Align(
            alignment: Alignment.center,
            child: Text("B"),
          ),
        ),
      ],
    );
  }
Related