I want to center a SizedBox that I have created, so I wrapped it with a Center widget, like so:
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
title: 'My app',
home: SafeArea(
child: MyScaffold(),
),
),
);
}
class MyScaffold extends StatelessWidget {
const MyScaffold({super.key});
@override
Widget build(BuildContext context) {
return Material(
child: Column(
children: [
TextInputWidget(),
],
),
);
}
}
class TextInputWidget extends StatelessWidget {
const TextInputWidget({super.key});
@override
Widget build(BuildContext context) {
return Row(
children: [
Center(
child: SizedBox(
width: 200.0,
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
),
),
],
);
}
}
But unfortunately, it does not work, as you can see on the picture below, the SizedBox is still on the left side on the window:
I have been looking for an answer, but did not find one yet.
Any solution for this?
Thanks
3
Answers
Instead of using a
Center
widget you should use theMainAxisAlignment
of the row:You are trying to Center your SizedBox widget but the problem is, SizedBox won’t able to know where it’s position to centeralized because of its parent widget.
You can control that property with 2 options.
1st Solution using
mainAxisAlignment
property.2nd Solution using Flexible at here because you are limiting your SizedBox’s width property, if you wan’t to cover all the available space at Row’s available zone’s use Expanded instead.
According to the
Center
documentation:In a
Row
, children are unconstrained on the primary axis. To make a child widget such as theCenter
take up all the available space, wrap it in anExpanded
widget.(The
Row
API documentation has a detailed explanation of its layout mechanics. It’s a very nice read.)Alternatively, you could set the
Row
alignment usingmainAxisAlignment
instead.