Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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’.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading