flutteruser-interfacedarttextfield

Flutter : How to center an icon next to hint text inside an input decoration?


Example of desired effect

I have a TextField with an InputDecoration where I set a hintText and a prefixIcon, however the prefixIcon property that I am using will always pull the Icon all the way to the left.

TextField(
  textAlign: TextAlign.center,
  decoration: InputDecoration(
    contentPadding: EdgeInsets.fromLTRB(0, 30, 0, 30),
    prefixIcon: Icon(Icons.search),
    hintText: 'Search',
    fillColor: Color(0xffF1F4FB),
    filled: true,
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25),
      borderSide: BorderSide(
        color: Color(0xffF1F4FB),
      ),
    ),
    disabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25),
      borderSide: BorderSide(
        color: Color(0xffF1F4FB),
      ),
    ),
  ),
),

I'm trying to change this to have the search icon and the hint text initially centered next to each other. How can I achieve this effect?


Solution

  • Here is a solution using IntrinsicWidth.

    With this solution, the search icon will be next to the hinttext and then it will stay next to the text input from the User.

    enter image description here

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(
        MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter Demo',
          home: HomePage(),
        ),
      );
    }
    
    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Container(
              height: 48.0,
              padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 0.0),
              margin: EdgeInsets.all(8.0),
              decoration: BoxDecoration(
                color: Colors.amber.shade300,
                border: Border.all(
                  color: Colors.brown,
                  width: 3.0,
                ),
                borderRadius: BorderRadius.circular(25),
              ),
              child: Center(
                child: IntrinsicWidth(
                  child: TextField(
                    textAlignVertical: TextAlignVertical.center,
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.search),
                      hintText: 'Search',
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      }
    }