textField and textEditControl ,Get user input on button click - Flutter

Viewed 195

I am building a chat screen and trying to get messages from textEditController instead of getting them from the message model

Code below:

 TextEditingController _controller =
  new TextEditingController();

String _text = '';

....

 IconButton(
        icon: Icon(Icons.send),
        iconSize: 25.0,
        color: Theme.of(context).primaryColor,
        onPressed: () async {
          DataModel? data = await submitData(_controller);
          _dataModel = data;
          setState(
            () {
              _text = _controller.text.toString();
            },
          );
        },
      ),

....

 child: TextField(
          controller: _controller, 
          textCapitalization: TextCapitalization.sentences,
          onChanged: (value) {},
          decoration: InputDecoration(hintText: 'Send a message...'),
        ),
1 Answers

What you need to do is to invoke the addListener function on your TextEditingController and do your actions on it. Here is an example:

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late final TextEditingController _controller;

  @override
  void initState() {
    _controller = TextEditingController();
    _controller.addListener(() {
      final text = _controller.text;
      // do something with text here
    });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home Page'),
      ),
      body: TextField(
        controller: _controller,
      ),
    );
  }
}
Related