skip to Main Content

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


  1. you can initialize you sizes on your build function instead of initState

    like this code

      double windowwidth = 0;
      double anyvariable = 0;
      @override
      Widget build(BuildContext context) {
        windowwidth = MediaQuery.of(context).size.width;
        double anyvariable = _mediaQueryData.size.width/2;
        return const Placeholder();
      }
    
    Login or Signup to reply.
  2. You are calling setState inside initState, 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:

    double anyvariable = 30.0;
    
    @override
    void initState() {
        super.initState();
    
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    
           var windowwidth = MediaQuery.of(context).size.width;
    
           setState(() {
               anyvariable = _mediaQueryData.size.width/2;
            });
    
         });
    
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search