40

I tried finding in a lot of resources but unfortunately i could not find a way to align the text vertically centre in a textfield. I also tried using suffixIcon instead of suffix but still not luck. Here is my code :

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Icon(
          Icons.menu,
          color: Colors.black,
        ),
        backgroundColor: Colors.white,
        title: Container(
          margin: EdgeInsets.only(bottom: 10),
          child: Image.asset(
            "icons/logo.png",
          ),
        ),
        bottom: PreferredSize(
          child: Padding(
            padding: EdgeInsets.only(
              left: 10,
              right: 10,
              bottom: 10,
            ),
            child: Container(
              height: 40,
              child: TextField(
                textAlignVertical: TextAlignVertical.center,
                textAlign: TextAlign.left,
                maxLines: 1,
                style: TextStyle(
                  fontSize: 13,
                ),
                decoration: InputDecoration(
                    suffixIcon: IconButton(icon: Icon(Icons.search, color: Colors.black,), onPressed: (){}),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(15)),
                    )
                ),
              ),
            ),
          ),
          preferredSize: Size(MediaQuery.of(context).size.width, 50),
        ),
      ),
      body: Container(
        margin: EdgeInsets.only(top: 11),
        child: Column(
          children: <Widget>[
            Carousel(),
          ],
        ),
      ),
    );
  }
}

class Carousel extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CarouselState();
  }
}

class _CarouselState extends State<Carousel> {
  List<String> urls = [];

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: Stack(
        children: <Widget>[
          Image.network(
              "someImageUrlHere."),
          Positioned(
            bottom: 5,
            width: MediaQuery.of(context).size.width - 20,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text("•"),
                Text("•"),
                Text("•"),
                Text("•"),
                Text("•"),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

What could be the issue that is causing this problem ? and how can i solve this issue ?

10 Answers10

40
TextField(
   textAlign: TextAlign.center,
   decoration: InputDecoration(
     hintText: "Centered Hint",
   ),
)

Hope so that this will be helpful.

Aashar Wahla
  • 2,785
  • 1
  • 13
  • 19
  • actually this is the correct answer, but without votes – Mohamed Yousof Mar 31 '21 at 15:18
  • 5
    @MohamedYousof no, this doesn't make textAlign VERTICALLY center, just horizontally. – Arsen Tatraev Apr 07 '21 at 14:01
  • @ArsenTatraev for that you will have to make text-align property center. – Aashar Wahla Apr 09 '21 at 17:40
  • 13
    `textAlign: TextAlign.center` will align the text horizontally. To vertically align, you need to use `textAlignVertical: TextAlignVertical.center` property. – Ahmad Khan Nov 19 '21 at 12:49
  • 2
    If the problem comes from the "contentPadding" in the "decoration: InputDecoration" of the TextField, then this does not help. As outlined in the answer by komnataDeveloper, you need to set the contentPadding. I would set it to zero, then the centering works. – Stephan Mar 01 '23 at 19:26
34

I have solution for Single-line TextField. Placing TextField inside a Container with height property,(in my case, also width) and then giving a contentPadding value inside decoration with a value of height / 2.

Code is below:

          Container(
            height: textfieldDimension,
            width: textfieldDimension,
            alignment: Alignment.center,

            child: TextField(
              decoration: InputDecoration(
                border: InputBorder.none,
                contentPadding: EdgeInsets.only(
                  bottom: textfieldDimension / 2,  // HERE THE IMPORTANT PART
                )

              ),
              // textAlignVertical: TextAlignVertical.center,  THIS DOES NOT WORK



              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 10,   // This is not so important
              ),
            ),
          ),
12

enter image description here

try this:

Container(
      height: 36,
      child: TextField(
        maxLines: 1,
        style: TextStyle(fontSize: 17),
        textAlignVertical: TextAlignVertical.center,
        decoration: InputDecoration(
          filled: true,
          prefixIcon:
              Icon(Icons.search, color: Theme.of(context).iconTheme.color),
          border: OutlineInputBorder(
              borderSide: BorderSide.none,
              borderRadius: BorderRadius.all(Radius.circular(30))),
          fillColor: Theme.of(context).inputDecorationTheme.fillColor,
          contentPadding: EdgeInsets.zero,
          hintText: 'Search',
        ),
      ),
    )
8

Please try to wrap by Column and add 'mainAxisAlignment' property with 'MainAxisAlignment.center'

    Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start, // If you want align text to left
          children: <Widget>[
            TextField(
                textAlignVertical: TextAlignVertical.center,
                textAlign: TextAlign.left,
                maxLines: 1,
                style: TextStyle(
                  fontSize: 13,
                ),
                decoration: InputDecoration(
                    suffixIcon: IconButton(icon: Icon(Icons.search, color: Colors.black,), onPressed: (){}),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(15)),
                    )
                ),
              ),
          ],
        ),
      )
KuKu
  • 6,654
  • 1
  • 13
  • 25
4

The simplest way would be to use the built-in TextAlign properties to align vertically or horizontally:

TextField(
   textAlign: TextAlign.center, // Align horizontally
   textAlignVertical: TextAlignVertical.center, // Align vertically
)
CoderUni
  • 5,474
  • 7
  • 26
  • 58
4

Put contentPadding and isDense like this.

 decoration: InputDecoration(
    contentPadding: EdgeInsets.zero,
     isDense: true,
       hintText: 'Name',)
2

If anything doesn't work, try to use:

textAlignVertical: TextAlignVertical.bottom,
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
1

you can use textAlignVertical property availabe inside Textfield/ Textformfield.

Demo: TextField( textAlignVertical: TextAlignVertical.center, decoration: InputDecoration( hintText: 'Text aligned vertically centered', ) )

0

Date time is picking perfect but hint alignment and date value is not align in same place.

 Container(
                  child: Padding(
                    padding: const EdgeInsets.only(
                        left: 15.0, right: 15.0, top: 15.0, bottom: 10.0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Center(
                          child: Image.asset(
                            "assets/images/date.png",
                            // width: 20,
                            width: SizeConfig.safeBlockHorizontal * 4,
                          ),
                        ),
                        SizedBox(
                          width: 15,
                        ),
                        Flexible(
                          child: Center(
                            child: DateTimeField(
                              decoration: InputDecoration.collapsed(
                                hintText: "Start date and time",
                                hintStyle: TextStyle(
                                  // fontSize: 14,
                                  fontSize: SizeConfig.safeBlockHorizontal * 3,
                                ),
                                border: InputBorder.none,
                              ),
                              validator: validateStartDate,
                              onSaved: (DateTime val) {
                                _startDate = val;
                              },
                              format: format,
                              style: TextStyle(
                                fontSize: SizeConfig.safeBlockHorizontal * 3,
                              ),
                              onShowPicker: (context, currentValue) async {
                                // FocusScope.of(context).previousFocus();
                                final Startdate = await showDatePicker(
                                    context: context,
                                    firstDate: DateTime.now()
                                        .subtract(Duration(days: 1)),
                                    initialDate: currentValue ??    DateTime.now(),
                                    lastDate: DateTime(2100));
                                if (Startdate != null) {
                                  final StartTime = await showTimePicker(
                                    context: context,
                                    initialTime: TimeOfDay.fromDateTime(
                                        currentValue ?? DateTime.now()),
                                  );
                                  setState(() {
                                    StartDate = DateTimeField.combine(
                                        Startdate, StartTime);
                                  });
                                  return DateTimeField.combine(
                                      Startdate, StartTime);
                                } else {
                                  return currentValue;
                                }
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

`]1

Mohankumar Shan
  • 131
  • 1
  • 3
0
TextField(
      controller: controller,
      onSubmitted: (searchInfo) async {},
      textAlignVertical: TextAlignVertical.center,
      textAlign: TextAlign.left,
      textInputAction: TextInputAction.go,
      decoration: InputDecoration(
        contentPadding: EdgeInsets.zero,
        isDense: true,
        hintText: hint,
        hintStyle: TextStyle(
          color: Colors.black.withOpacity(.35),
          fontSize: 15.0,
        ),
        prefixIcon: Padding(
          padding: const EdgeInsets.all(6),
          child: Image.asset(
            ImageConstant.searchbox,
            color: Colors.black.withOpacity(.7),
          ),
        ),
        

        focusedBorder: InputBorder.none,
        border: InputBorder.none,
      ),
    ),