flutterdarttextpaddingflutter-textformfield

How to add margin to hintText and Text in a TextFormField in flutter?


I would like to move the text down to be centered in the TextFormField.

[This is what it looks like] (https://i.sstatic.net/0SoHm.png) [This is what I want it to look - move the text down a few pixels to be centered] (https://i.sstatic.net/b2wKi.png)

My font it is proximaNova and the designer requires this font.

  Widget petNameField() {
    return TextFormField(
      controller: nameCn,
      focusNode: nameFn,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      validator: FieldValidator.validateName,
      textInputAction: TextInputAction.next,
      inputFormatters: [
        LengthLimitingTextInputFormatter(25),
      ],
      keyboardType: TextInputType.name,
      style: R.decoration.fieldStyle(context),
      decoration: R.decoration.fieldDecoration(
        radius: 26,
        fillColor: R.colors.textFieldFillColor.withOpacity(0.15),
        borderColor: R.colors.textFieldFillColor.withOpacity(0.15),
        context: context,
        hintText: "pet_name",
      ).copyWith(
        //contentPadding: EdgeInsets.fromLTRB(12, 18, 12, 12),
      ),
    );
  }

I tried using contentPadding: / wrapping the field in Padding() / adding a prefixIcon container with margin / but this padding modifies the entire field box and the text doesn't become centered.

I've been banging my head against the wall for the past day so any help is greatly appreciated!


Solution

  • You can fix the alignment of the text by using the height factor of the textStyle and content padding. Here is the working code and output image.

    https://i.sstatic.net/4blVp.png

    Try to run the code on dartPad.dev

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      final String title;
    
      const MyHomePage({
        Key? key,
        required this.title,
      }) : super(key: key);
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(widget.title),
          ),
          body: Center(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
                petNameField(),
              ],
              ),
            )
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
        );
      }
    
      Widget petNameField() {
        final controller = TextEditingController();
        return TextFormField(
          controller: controller,
    //       focusNode: nameFn,
          autovalidateMode: AutovalidateMode.onUserInteraction,
    //       validator: FieldValidator.validateName,
          textInputAction: TextInputAction.next,
          inputFormatters: [
            LengthLimitingTextInputFormatter(25),
          ],
          keyboardType: TextInputType.name,
          style: Theme.of(context).textTheme.bodyMedium!.copyWith(
            height: 1.3,
          ),
          decoration: InputDecoration(
            fillColor: Colors.grey.shade200,
            hintText: "pet_name",
            border: OutlineInputBorder(
              borderRadius: const BorderRadius.all(Radius.circular(40.0)),
              borderSide: BorderSide(color: Colors.grey.shade200, width: 1),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: const BorderRadius.all(Radius.circular(40.0)),
              borderSide: BorderSide(color: Colors.grey.shade400, width: 1),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: const BorderRadius.all(Radius.circular(40.0)),
              borderSide: BorderSide(color: Colors.grey.shade400, width: 1),
            ),
            filled: true,
            contentPadding: const EdgeInsets.symmetric(horizontal: 25, vertical: 0),
          ),
    
        );
      }
    }