I am trying to have a sequence of events happen on button press:
But it seems like the onPressed function only allows one setState() to update the view, because the problem is that the button text never changes.
Here is the button widget:
new RaisedButton(
child: Text(_calculating ? "Stop" : "Start"),
onPressed: () {
if (_calculating) {
_setCalculating(false);
// stop calculating
} else {
_setCalculating(true);
_doCalc();
}
},
),
Here are the callbacks:
void _doCalc() {
setState(() {
sleep(const Duration(seconds:1));
// Do some calculation and display the result ...
_setCalculating(false);
});
}
void _setCalculating(bool calculating) {
setState(() {
_calculating = calculating;
print ("Setting state: " + calculating.toString());
});
}
The calculation is displaying but the button text never changes to "Stop" while the calculation is in progress (note the sleep for 1 second). However the print statement is printing so I know that _setCalculating is being called as expected.
Is it only possible to do one update per button press, or is there another way to go about it?
It simpler than you think
class Main extends StatefulWidget {
@override
MainState createState() {
return new MainState();
}
}
class MainState extends State<Main> {
bool _calculating = false;
void _doCalc() async {
_setCalculating(true);
await Future.delayed(const Duration(seconds: 2));
_setCalculating(false);
}
void _setCalculating(bool calculating) {
setState(() {
_calculating = calculating;
print("Setting state: " + calculating.toString());
});
}
@override
Widget build(BuildContext context) {
return new RaisedButton(
child: Text(_calculating ? "Stop" : "Start"),
onPressed: _doCalc,
);
}
}
You were calling setState twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With