skip to Main Content

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

2

Answers


  1. getdata is a async method, you need to return Future<void> to await.

    Now the initState() cant be async, you can create another method to await and place it here.

    void newMethod() async {
      await getdata();
      print('object');
    }
    

    And place newMethod() inside initState.

    Or you can use .then

     getdata().then((_) {
        print('object');
      });
    
    Login or Signup to reply.
  2. 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’.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search