Search code examples
flutterdartdart-async

why statement is getting called before await function in flutter


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');
            },
          ),
        ),
      ),
    );
  }
}


Solution

  • Use like this.

        first() async  {
            await Future.delayed(Duration(seconds: 10), () {
              print('first');
            });
          }
    
        second() async   {
            await Future.delayed(Duration(seconds: 1), () {
          print('second');
        });
      }