0

I have a situtation where i would like to access to text of a text controller, from the Widget part of a statefull widget.

So what i would like to do is is write a method getText() that returns the current text in my _textController.

I know how to do this from the other way around. If i need to get data from my widget from the State part of my widget is use "widget.", but i dont know how to do this the other way around.

class MyTextWidget extends StatefulWidget { String getText() { // how can i access the _textController.text from here? } @override _MyTextWidgetState createState() => _MyTextWidgetState(); } class _MyTextWidgetState extends State<MyTextWidget> { final TextEditingController _textController = TextEditingController(); _MyTextWidgetState(); @override void dispose() { _textController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2.0), child: TextField( controller: _textController, key: ValueKey('MyTextWidgetinput_Key'), maxLines: null, autofocus: true, keyboardType: TextInputType.multiline, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: const BorderRadius.all(Radius.circular(15.0))), ), )); } } 

1 Answer 1

2

Simply move it up and access it in your state class using widget._textController:

class MyTextWidget extends StatefulWidget { final TextEditingController _textController = TextEditingController(); String getText() { _textController.text // do something with it // how can i access the _textController.text from here? } @override _MyTextWidgetState createState() => _MyTextWidgetState(); } class _MyTextWidgetState extends State<MyTextWidget> { _MyTextWidgetState(); @override void dispose() { widget._textController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2.0), child: TextField( controller: widget._textController, key: ValueKey('MyTextWidgetinput_Key'), maxLines: null, autofocus: true, keyboardType: TextInputType.multiline, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: const BorderRadius.all(Radius.circular(15.0))), ), )); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.