Search code examples
androidflutterdartasync-awaitfuture

How Print('Object') is executing before getData() function gets finished in Dart


I was Learning Async and Future Functions in Dart but I got confused because I still not get it like how print("object") is compiled before getData() function because traditionally next Line is read by compiler once the before line or Function is fully compiled/Executed . If I am making a Mistake Please correct me out , I am noob tbh


import 'package:flutter/material.dart';

class Loading extends StatefulWidget {
const Loading({super.key});

@override
State\<Loading\> createState() =\> \_LoadingState();
}

class \_LoadingState extends State\<Loading\> {
void getdata() async {
String parth = await Future.delayed(Duration(seconds: 3), () {
return 'parth';
});
print('Hey');
print(parth);
}

@override
int count = 0;
void initState() {
// TODO: implement initState
super.initState();
getdata();
print('object');
}

@override
Widget build(BuildContext context) {
// print(' Setstae vala + $count');
return Scaffold(
appBar: AppBar(
title: Text('Loading'),
),
body: ElevatedButton(
onPressed: () {
setState(() {
count++;
});
},
child: Text('$count')),
);
}
}

Solution

  • Your output should be like this:

    1. object
    2. Hey
    3. parth

    because traditionally next Line is read by compiler once the before line or Function is fully compiled/Executed

    Normaly, yes. But since you are using the async keyword in this case, it works a little differently.

    What happens here:

    You call getData first in your initState. In getData you have a future delayed in it, which you wait for with keywoard await. So it waits 3 seconds until you return 'parth' as a string. At the same time, however, it continues to run in your initState to return 'object'.