I would like to initialize some of the widgets with the size
and width
of the screen.
When I try to use the initState
method like
double anyvariable = 30.0;
@override
void initState() {
super.initState();
var windowwidth = MediaQuery.of(context).size.width;
setState(() {
anyvariable = _mediaQueryData.size.width/2;
});
}
I receive the error
dependOnInheritedWidgetOfExactType<MediaQuery>() or dependOnInheritedElement() was called before
_CustomWidgetState.initState() completed. ...
How do I fix this error or how to I init the widgets with information about the width and height of the screen available before build?
2
Answers
you can initialize you sizes on your build function instead of initState
like this code
You are calling
setState
insideinitState
, with is not a good practice and can also give you the error you’re facing.To solve this, you can write this way.
1. You can wrap the code with
WidgetsBinding.instance.addPostFrameCallback
: