Like the below code:
class TestWidget extends StatefulWidget {
String name;
TestWidget(this.name);
void updateName(String name) {
//how to update Text data
}
@override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<KMSelectionItem> {
@override
Widget build(BuildContext context) {
return Text(widget.name);
}
}
I want to change the text data through the method updateName
. But I don't know how can do it.
CodePudding user response:
you should use setState method for this purpose, this method updates the ui based on the changes made. insert the function code like this and declare the function inside your stateful widget. to update the text:
class _TestWidgetState extends State<KMSelectionItem> {
@override
Widget build(BuildContext context) {
return Text(widget.name);
}
void updateName() {
//how to update Text data
setState(() {
widget.name = YOUR_NEW_TEXT;
});
}
}
CodePudding user response:
class TestWidget extends StatefulWidget {
String name;
TestWidget(this.name);
void updateName(String name) {
setState(() {
name ="updated_name";
});
}
@override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<KMSelectionItem> {
@override
Widget build(BuildContext context) {
return Text(widget.name);
}
}