Home > Back-end >  Centered text in TextField is slightly offset
Centered text in TextField is slightly offset

Time:10-24

enter image description here

import 'package:flutter/material.dart';

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

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/': (context) => ExampleScreen(),
      },
    );
  }
}

class ExampleScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      body: Center(
        child: Container(
          color: Colors.blue,
          width: 70,
          height: 70,
          child: Center(
            child: TextField(
              controller: TextEditingController.fromValue(TextEditingValue.empty.copyWith(text: '8')),
              autofocus: false,
              style: Theme.of(context).primaryTextTheme.headline2!.copyWith(
                color: Theme.of(context).colorScheme.onBackground,
              ),
              textAlign: TextAlign.center,
              textAlignVertical: TextAlignVertical.center,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.zero,
                border: OutlineInputBorder(
                  borderSide: BorderSide(color: Theme.of(context).disabledColor),
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Hey,

I'm trying to center text in a TextField. As you can see, the text is slightly offset to the top left. Is there something else I have to consider in order to center the text?

edit: This has nothing to do with the rest of the widget tree. You can reproduce this issue on dartpad.dev using only the code above.

CodePudding user response:

While you are using Container,

use alignment: Alignment.center,

 Container(
          alignment: Alignment.center,
          color: Colors.blue,
          child: TextField(
             controller: controller,
             focusNode: focusNode,
            autofocus: false,
            style: theme.primaryTextTheme.headline4!.copyWith(
             color: theme.colorScheme.onBackground,
            ),
            textAlign: TextAlign.center,
            textAlignVertical: TextAlignVertical.center,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.zero,
              border: OutlineInputBorder(
                borderSide: BorderSide(color: theme.disabledColor),
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          ),
        ),

More about Container-class.

CodePudding user response:

Change 2 to correct value like this

decoration: InputDecoration( contentPadding: EdgeInsets.only(left: 2),

  • Related