Depend On Inherited Element was called before init state in flutter
Error
Unhandled Exception: inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before _ScreenState.initState() completed.
When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget.
Solution
when “dependOnInheritedElement() was called before initState()” could also be to access BuildContext safely in the initState method. It could be done by the following:
WidgetsBinding.instance.addPostFrameCallback((_) async {
// your code goes here
});
Example
Map dataSet = {};
bool isLoading = true;
getdata(id) async {
var collection = FirebaseFirestore.instance.collection('requests');
var querySnapshot =
await collection.where('driverId', isEqualTo: id).limit(1).get();
Map data = {};
for (var snapshot in querySnapshot.docs) {
data = snapshot.data();
print(data);
}
setState(() {
dataSet = data;
isLoading = false;
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
UserProvider userProvider =
Provider.of<UserProvider>(context, listen: false);
getdata(userProvider.userModel?.id);
});
}