13

Is it possible to get the String value from a Text() Widget after it is defined?

Example code

Text txt = Text("example text");

getValueFromtxt() {
  var value = txt.text;                  <------
}

@override
Widget build(BuildContext context) {
  return txt;
}
3
  • 1
    That code smells, you are probably doing something wrong. In 99.9999% of all cases, there should be no need to read a property from a defined widget. Commented Aug 21, 2018 at 14:41
  • My code is just an example on how you could get the value from the widget and could you explain why there is no need to read a property from a defined widget? You could use it to set it to a different value. We can all learn from eachother! Commented Aug 21, 2018 at 14:54
  • 1
    Widgets should be (and the default widgets are) immutable. To change the value of a widget, you just trigger a rebuild of the enclosing widget (that's what the build method is for), usually by calling setState in one of the parent widgets. It's the same technique that powers the React framework. Commented Aug 22, 2018 at 9:56

2 Answers 2

24

It's not that difficult I had to use Text().data:

Text txt = Text("example text");

getValueFromtxt() {
  var value = txt.data;                  <------
}

@override
Widget build(BuildContext context) {
  return txt;
}
Sign up to request clarification or add additional context in comments.

Comments

0

@FoxyError you can do that as above answer but You can Avoid that by just storing value in String variable.

String string = "hello World";

You can use it to print or change the value.

 new Text("Any String" + string);

1 Comment

Ofcourse that's true my example didn't really represent the situation I really had. The Text() Widget came from another method in another class. But thanks, your answer could solve someone elses problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.