Home > Software engineering >  Flutter: Not able to clear text field with .clear or .text =""
Flutter: Not able to clear text field with .clear or .text =""

Time:01-16

I have created a feedback screen but I am unable to clear the text from my rounded input field even after using controller.clear or controller.text =""

My feedback screen code(only attaching relevant code to make it easy to understand):

class _FeedbackBodyState extends State<FeedbackBody> {
  var _enteredMessage = '';

  final _controller = new TextEditingController();
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    void _sendMessage() async {
      
      FocusScope.of(context).unfocus();

      await FirebaseFirestore.instance.collection('chat').add({
        'text': _enteredMessage,
      });
      _controller.clear();
      //_controller.text = "";
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Feedback submitted')));
    }

    return Scaffold(
      body: FeedbackBackground(
          child: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            

            RoundedInputField(
              hintText: "Send a message",
              onChanged: (value) {
                setState(() {
                  _enteredMessage = value;
                });
              },
            ),
            Container(
                margin: EdgeInsets.symmetric(vertical: 10),
                padding: EdgeInsets.symmetric(horizontal: 40),
                child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      primary: kPrimaryColor, // background
                      
                    ),
                    onPressed:
                        _enteredMessage.trim().isEmpty ? null : _sendMessage,
                    child: Text('Send Feedback'))),
            
          ],
        ),
      )),
    );
  }
}

The submit button should have cleared the field by doing controller.clear but I am not sure how it did not work

Thanks for your help in advance

CodePudding user response:

Try adding it inside the setState((){});

Change

_controller.text = "";

to

setState((){
   _controller.text = "";
});

CodePudding user response:

Use controller in TextField.

final TextEditingController _controller = TextEditingController();

TextField(
  controller: _controller,
...
)
  • Related