如何将毫米单位的设计值转换为Flutter逻辑像素?
Hey there! Great question—you’re on the right track with device pixel ratio, but the docs note you rarely need to handle it directly because Flutter handles most visual scaling automatically. That said, when you need to map physical measurements (like millimeters) to logical pixels for precise layout, a straightforward conversion exists.
The Core Idea
Flutter’s logical pixels are based on a 160dpi baseline: that means 1 inch = 160 logical pixels. Since 1 inch = 25.4 millimeters, we can use this fixed ratio to convert mm directly to logical pixels, no need to mess with devicePixelRatio directly (Flutter will handle scaling to physical pixels under the hood).
The Simplified Conversion Formula
Here’s a ready-to-use function:
double mmToLogicalPixels(double mm) { // 1 inch = 25.4 mm; 1 inch = 160 logical pixels (Flutter's baseline) return mm * 160 / 25.4; }
How It Works
Let’s break it down:
- Convert millimeters to inches:
mm / 25.4 - Multiply by Flutter’s baseline logical pixels per inch (160) to get the equivalent logical pixel value.
Flutter will automatically scale this logical pixel value to the device’s physical pixels using devicePixelRatio, ensuring the final on-screen size matches your original millimeter measurement across different devices.
Optional: Minor Precision Tweak
If you’re targeting iOS specifically (where the baseline is 163dpi instead of 160), you can adjust the formula to:
double mmToLogicalPixels(double mm) { return mm * 163 / 25.4; }
For cross-platform apps, the 160dpi baseline works perfectly for most use cases—users won’t notice the tiny difference.
Quick Test
To verify, create a Container with width: mmToLogicalPixels(10) and measure its on-screen width with a ruler. It should be roughly 10mm, regardless of the device’s screen density.
内容的提问来源于stack exchange,提问作者Bram Vanbilsen

