await in initState possible?
Flutter Tutorial
Install Flutter in Win/Linux/Mac
Flutter Widgets:
Bottom Navigation Bar in Flutter
Auto Close Keyboard in Flutter
Screen size handling in Flutter
Flutter REST API
Flutter Advance
Wrap vs Builder vs OverBarFlow
Circular progress contain Icon
Flutter State management Comparison
Flutter Database
Flutter Token Expired Handling
Flutter Provider
Flutter GetX
Flutter with Native
Flutter Tips
Interview Questions
First you understand the concept of await in Flutter . Then you can easily understand that it is not possible to use await in initState because initState method is non-async and StatefulWidget lifecycle will not run smoothly, which will result in screen not loading, hence, adding await in initState is not recommended. Because initState is not marked as asynchronous. However await for a separate asynchronous method to be received or required and call it within initState.
In the below example fetchData method is aync and used in initState()
import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
String data = 'Loading...';
@override
void initState() {
super.initState();
//Here we call async function
fetchData();
}
Future<void> fetchData() async {
//asynchronous operation, such as fetching data
await Future.delayed(Duration(seconds: 2));
// Update the state after the asynchronous operation
setState(() {
data = 'Data loaded successfully!';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Async initState Example'),
),
body: Center(
child: Text(data),
),
);
}
}
void main() {
runApp(MaterialApp(
home: MyWidget(),
));
}