Irfan Ganatra
Irfan Ganatra

Reputation: 1398

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

Upvotes: 0

Views: 112

Answers (3)

Rohit Soni
Rohit Soni

Reputation: 1447

Use like this.

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

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

Upvotes: 1

Mobin Ansar
Mobin Ansar

Reputation: 710

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

Upvotes: 0

Renik Shiroya
Renik Shiroya

Reputation: 379

You should use async await in first() and second() function also before Future.delayed()

Upvotes: 3

Related Questions