When setState
is called in a widget’s state, the corresponding element in the element tree gets marked as dirty, and the widget gets rebuilt. However, how does it handle descendents? For example, the Text
widget below gets rebuilt when its ancestor SampleWidgetState
gets rebuilt.
Why?
class SampleWidget extends StatefulWidget {
@override
SampleWidgetState createState() => SampleWidgetState();
}
class SampleWidgetState extends State<SampleWidget> {
String text = "text1";
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(text),
ElevatedButton(
child: Text('call SetState'),
onPressed: () {
setState(() {
text = "text2";
});
},
),
],
);
}
}
2
Answers
from Flutter’s official documentation, inside Flutter:
I guess this answer what Flutter does under the hood in the updating process of the widget’s descendents.
SampleWidgetState
is a state class, when you calling thesetState()
its meanbuild()
method will reinvoke, everything inside will rebuild. thats how its works.if you want to prevent the descendents to not rebuild, there is several ways,
const
keyword.in your case,
Text
widget consumeSampleWidgetState
:String text = "text1";
, its mean Text widget is not independent, its dependent on that state.