Search code examples
flutterflutter-layoutflutter-textinputfield

how to set textfield width based on it's text in flutter


I want to size the textfield based on text length...while typing it's length should be changed according to text..I was suggested to use IntrinsicWidth but its not working..

Container(
              height: 300,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(30)
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 40.0),
                      child: IntrinsicWidth(
                        child: TextField(
                          keyboardType: TextInputType.number,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 30,
                          ),

                          decoration: InputDecoration(
                              hintStyle: TextStyle(fontSize: 20,color: Colors.grey[400]),
                              hintText: 'Enter Income Amount'
                          ),
                        ),
                      ),
                    ),

Solution

  • Create a TextEditingController instance and call setState to update the UI. I am changing hintText to null based on userInput.

     final TextEditingController controller = TextEditingController();
     .....
    
    Padding(
      padding: const EdgeInsets.symmetric(horizontal: 40.0),
      child: IntrinsicWidth(
        child: TextField(
          textAlign: TextAlign.center,
          controller: controller,
          onChanged: (value) {
            setState(() {});
          },
          style: TextStyle(
            fontSize: 30,
          ),
          decoration: InputDecoration(
            hintStyle: TextStyle(fontSize: 20, color: Colors.grey[400]),
            hintText:
                controller.text.isEmpty ? 'Enter Income Amount' : null,
          ),
        ),
      ),
    ),