Example:
Container(
height: 100, // fixed value
weight: 100, // fixed value
...
);
As far as I understand, due to fixed widget sizes, when scaling the screen, widget rendering errors (for example, lack of free space) may appear. Is it possible to make the widget size change dynamically as the screen scales?
CodePudding user response:
Yes, I would recommend using layout builder & mediaquery. Essentially you can create different break points for different screen sizes.
Just like @rajaghaneshan mention, using mediaQuery and percentages allows your ui to scale dynamically based on the device screen size.
Here’s a starter sample project that touched on the basis of this. Hope this helps!
https://github.com/shavar67/Responsive-ui-flutter/blob/master/lib/widget/responsive_layout.dart
CodePudding user response:
It is always better to use dynamic sizes.
If you are inside the widget, you can specify size dynamically using the MediaQuery
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
height: size.height * 0.5,
width: size.width * 0.5,
);
}
}
where 0.5 means 50% of the width/height. You can specify what percentage of screen it should use.
Another approach is to use the below code which does not need BuildContext context.
Use the code in a separate file or somewhere globally and you can use it from anywhere
import 'dart:ui';
class AppConstants {
static Size logicalScreenSize = window.physicalSize / window.devicePixelRatio;
static double get screenWidth {
return logicalScreenSize.width;
}
static double get screenHeight {
return logicalScreenSize.height;
}
}
import 'package:flutter/material.dart';
import 'package:flutter_app/utils/app_constants.dart';
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
height: AppConstants.screenHeight * 0.5,
width: AppConstants.screenWidth * 0.5,
);
}
}