in the code below that is for throwing dice, I want to wait 2 seconds after each dice throwing. I tested sleep(duration) and await Future.delayed(duration); the first one makes a delay before updating the screen which means when I tap the TextButton, it waits for 2 seconds and then changes the screen, but I want it to be changed and then waits for 2 seconds. The second one actually does nothing and there is no delays. Here is the code:
Duration delay = const Duration(seconds: 2);
CodePudding user response:
You can call delay inside WidgetsBinding
, like this:
setState(() {
...
});
WidgetsBinding.instance.addPostFrameCallback((_) async {
await Future.delayed(Duration(seconds: 2));
print("call"); // update the view then print call after 2 second
});
CodePudding user response:
try..
//Move your onPressCode to a function
Future<void> rollDice() async{
await Future.delayed(Duration(milliseconds: 0), () {
/// your onPressCode
});
}
And on your onPress :
onPressed:() async {
await rollDice();
await Future.delayed(Duration(milliseconds: 2000), () {});
print('this print is show after 2 secs');
}