I have created a demo for learning async and await
Here it is happening that a statement is executed before await function..
According to me
output should be A second Z First
but its giving
output : A Z second first
here is my coding
class _MyHomePageState extends State<MyHomePage> {
first() {
Future.delayed(Duration(seconds: 10), () {
print('first');
});
}
second() {
Future.delayed(Duration(seconds: 1), () {
print('second');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Async demo'),
),
body: Center(
child: Container(
color: Colors.white,
child: TextButton(
child: Text('Click Me'),
onPressed: () async {
print('A');
first();
await second();
print('Z');
},
),
),
),
);
}
}
CodePudding user response:
You should use async await in first()
and second()
function also before Future.delayed()
CodePudding user response:
Use like this.
first() async {
await Future.delayed(Duration(seconds: 10), () {
print('first');
});
}
second() async {
await Future.delayed(Duration(seconds: 1), () {
print('second');
});
}
CodePudding user response:
this code is working fine .According to you output " A second Z First"
class HomePage extends StatelessWidget {
first() async {
await Future.delayed(Duration(seconds: 10), () {
print('first');
});
}
second() async {
await Future.delayed(Duration(seconds: 1), () {
print('second');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Async demo'),
),
body: Center(
child: Container(
color: Colors.white,
child: TextButton(
child: Text('Click Me'),
onPressed: () async {
print('A');
first();
await second();
print('Z');
},
),
),
),
);
}
}
here is output:
Performing hot restart...
Waiting for connection from debug service on Chrome...
Restarted application in 397ms.
A
second
Z
first