How can Flutter handle dpi text and image size differences

Viewed 36169

We are currently in the process of evaluating whether Flutter is a good platform to build a new app on. So we wanted to make sure that our app looks good on devices with different DPIs. Given that we are supporting both iOS and Android, and the folder structure of iOS and Android to support the different image sizes vary, is there a solution available on Flutter to achieve this?

The same question applies to text sizes where we hope to change our text sizes depending on dpi.

3 Answers

For smaller devices, I created an optional scaler.

We test on many different devices including the iPhone SE 4" and Android devices with extremely high DPI as default. Works well.

double scaleSmallDevice(BuildContext context) {
  final size = MediaQuery.of(context).size;
  // For tiny devices.
  if (size.height < 600) {
    return 0.7;
  }
  // For normal devices.
  return 1.0;
}

Some useful math utils for responsive scaling:

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

/// This method is used to set padding/margin (for the left and Right side)
/// and width of the screen or widget according to the Viewport width.
double getHorizontalSize(double px) => px * (size.width / 375);

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

/// This method is used to set smallest px in image height and width.
double getSize(double px) {
  final height = getVerticalSize(px);
  final width = getHorizontalSize(px);

  if (height < width) {
    return height.toInt().toDouble();
  } else {
    return width.toInt().toDouble();
  }
}

/// This method is used to set text font size according to Viewport.
double getFontSize(double px) => getSize(px);
Related