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: AZ 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');
},
),
),
),
);
}
}
You should use async await in first()
and second()
function also before Future.delayed()
Use like this.
first() async {
await Future.delayed(Duration(seconds: 10), () {
print('first');
});
}
second() async {
await Future.delayed(Duration(seconds: 1), () {
print('second');
});
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.