I have been learning to deal with the async functions in the flutter. I have defined an async function and I have called it for two places
1. From the build function.
2. From the initState.
The Functions is when called from the build function gets executed and the text is printed to the terminal, however, calling it from the initstate no text is logged into the terminal.
Here is the Code.
import 'package:flutter/material.dart';
void main() => runApp(Test());
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
@override
void initState() {
random();
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
// random();
return MaterialApp(home: Scaffold(body: Center(child: Text("Wattup"))));
}
Future<void> random() async {
await Future.delayed(Duration(seconds: 2));
print("I'm Back baby");
}
}
You need to call your method after super.initState like this:
@override
void initState() {
// TODO: implement initState
super.initState();
random();
}
I think, Super.initState() should be called first So, put it in first line. Try this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With