Flutter change focus color and icon color but not works

342

Solution 1

If you wish to change the color of Icon on focus then you can use this instead

Color iconColor = Colors.grey;//add this as a variable

//use the focus widget in place of your textfield.
 Focus(
     onFocusChange: (hasFocus)
        {
         if(hasFocus)
             {
               iconColor = Colors.red;
              }
         else{
                iconColor = Colors.grey;
             }
             setState((){});
           },
          child: TextField(
             decoration: InputDecoration(prefix: Icon(Icons.phone, color: iconColor,)),
            ),
      ),

Solution 2

Try using FocusNode.

  late FocusNode focusNode = FocusNode()
    ..addListener(() {
      setState(() {});
    });
TextFormField(
  focusNode: focusNode,
  cursorColor: Colors.red[600],
  decoration: InputDecoration(
    icon: Icon(
      Icons.phone,
      color: focusNode.hasFocus ? Colors.red : Colors.grey,
    ),
  ),

Also, dispose the focus node

  @override
  void dispose() {
    focusNode.dispose();
    super.dispose();
  }

More about FocusNode

Share:
342
Roger Wong
Author by

Roger Wong

Updated on November 25, 2022

Comments

  • Roger Wong
    Roger Wong 28 days

    Change focus color and icon color but not work

    TextFormField(
                  cursorColor: Colors.red[600],
                  decoration: const InputDecoration(
                    border: UnderlineInputBorder(),
                    filled: false,
                    iconColor: Colors.red,
                    focusColor: Colors.red,
                    icon: Icon(Icons.phone),
                    hintText: 'Where can we reach you?',
                    labelText: 'Phone Number *',
                    prefixText: '+86',
                  ),
                  keyboardType: TextInputType.phone,
                  onSaved: (String? value) {
                    this._phoneNumber = value;
                    print('phoneNumber=$_phoneNumber');
                  },
                  // TextInputFormatters are applied in sequence.
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ],
                ),
    
    

    I have changed the focus color and icon color to red. I do hot restart but the output still is blue. My theme primary color is also red.

    theme: ThemeData(primaryColor: Colors.red, fontFamily: 'Poppins'),
    

    What is the problem? Here are the current output.