Reputation: 517
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))),
),
));
}
}
Upvotes: 0
Views: 38
Reputation: 28368
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))),
),
));
}
}
Upvotes: 2