简体   繁体   中英

The property 'window' can't be unconditionally accessed because the receiver can be 'null'

This error appears on my flutter app after connecting it to the firebase. Not really sure if that has something to do with the cause of the error. here is the code


Size size = WidgetsBinding.instance.window.physicalSize /
    WidgetsBinding.instance.window.devicePixelRatio;

///This method is used to set padding/margin (for the left and Right side) & width of the screen or widget according to the Viewport width.
double getHorizontalSize(double px) {
  return px * (size.width / 360);
}

///This method is used to set padding/margin (for the top and bottom side) & height of the screen or widget according to the Viewport height.
double getVerticalSize(double px) {
  num statusBar = MediaQueryData.fromWindow(WidgetsBinding.instance.window)
      .viewPadding
      .top;
  num screenHeight = size.height - statusBar;
  return px * (screenHeight / 800);
}

///This method is used to set text font size according to Viewport
double getFontSize(double px) {
  var height = getVerticalSize(px);
  var width = getHorizontalSize(px);
  if (height < width) {
    return height.toInt().toDouble();
  } else {
    return width.toInt().toDouble();
  }
}

///This method is used to set smallest px in image height and width
double getSize(double px) {
  var height = getVerticalSize(px);
  var width = getHorizontalSize(px);
  if (height < width) {
    return height.toInt().toDouble();
  } else {
    return width.toInt().toDouble();
  }
}``` 

If you are not using Flutter 3 yet, WidgetsBinding.instance is nullable .

That means you have to either use WidgetsBinding.instance!.window or WidgetsBinding.instance?.window .

You can also call WidgetsBinding.ensureInitialized() in your main() method to make sure an instance of WidgetsBinding exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM