Scale whole app or widget contents to a screen size in Flutter
Starting from the most internal part:
- SizedBox, to hard code a logical dimensions of the area that will be used by a child widget.
- FittedBox, to scale its child to entirely fit the parent, maintaining its proportions.
- Container, to set the background color of unused parts of the screen.
- SizedBox.expand, to scale the background container to fit the whole screen.
class ScalingBox extends StatelessWidget {
@override
Widget build(BuildContext context) {
double logicWidth = 600;
double logicHeight = 600;
return SizedBox.expand(
child: Container(
color: Colors.blueGrey,
child: FittedBox(
fit: BoxFit.contain,
alignment: Alignment.center,
child: SizedBox(
width: logicWidth,
height: logicHeight,
child: Contents(),
))));
}
}
To have a full example, below are the contents of the screen, but they are not an important part here.
class Contents extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.lightBlue,
child: Stack(
children: [
Positioned(
left: 100,
top: 100,
child: SizedBox(
width: 150,
height: 150,
child: Container(color: Colors.amber),
),
),
Positioned(
left: 350,
top: 350,
child: SizedBox(
width: 180,
height: 180,
child: ClipOval(
child: Container(color: Colors.greenAccent),
)),
),
Positioned(
left: 50,
top: 300,
child: Text(
"Test text",
style: TextStyle(color: Colors.white, fontSize: 50),
),
),
],
));
}
}
Lee Luong – Co-Founder & CEO