0

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

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

Use like this.

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

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

Comments

0

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

1 Comment

yes but I did not add async and await in my first and second method,It is solved by adding it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.