text
stringlengths
1
372
<topic_start>
the StatefulWidget
a StatefulWidget is a widget that changes state.
use the setState method to manage the
state changes for a StatefulWidget.
a call to setState() tells the flutter
framework that something has changed in a state,
which causes an app to rerun the build() method
so that the app can reflect the change.
state is information that can be read synchronously when a widget
is built and might change during the lifetime of the widget.
it’s the responsibility of the widget implementer to ensure that
the state object is promptly notified when the state changes.
use StatefulWidget when a widget can change dynamically.
for example, the state of the widget changes by typing into a form,
or moving a slider.
or, it can change over time—perhaps a data feed updates the UI.
checkbox, radio, slider, InkWell,
form, and TextField
are examples of stateful widgets that subclass
StatefulWidget.
the following example declares a StatefulWidget
that requires a createState() method.
this method creates the state object that manages the widget’s state,
_MyStatefulWidgetState.
<code_start>
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({
super.key,
required this.title,
});
final string title;
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
<code_end>
the following state class, _MyStatefulWidgetState,
implements the build() method for the widget.
when the state changes, for example, when the user toggles
the button, setState() is called with the new toggle value.
this causes the framework to rebuild this widget in the UI.
<code_start>
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool showText = true;
bool toggleState = true;
timer? t2;
void toggleBlinkState() {
setState(() {
toggleState = !togglestate;
});
if (!togglestate) {
t2 = timer.periodic(const duration(milliseconds: 1000), (t) {
toggleShowText();
});
} else {
t2?.cancel();
}
}
void toggleShowText() {
setState(() {
showText = !showtext;
});
}
@override
widget build(BuildContext context) {
return scaffold(
body: center(
child: column(
children: <widget>[
if (showtext)
const text(
'this execution will be done before you can blink.',
),
padding(
padding: const EdgeInsets.only(top: 70),
child: ElevatedButton(
onPressed: toggleBlinkState,
child: toggleState
? const Text('Blink')
: const Text('Stop blinking'),
),
),
],
),
),
);
}
}
<code_end>
<topic_end>
<topic_start>
what are the StatefulWidget and StatelessWidget best practices?
here are a few things to consider when designing your widget.
in flutter, widgets are either stateful or stateless—depending on whether
they depend on a state change.
in flutter, there are three primary ways to manage state:
when deciding which approach to use, consider the following principles:
the MyStatefulWidget class manages its own state—it extends
StatefulWidget, it overrides the createState()
method to create the state object,