How to make flutter application height and width adapt to different screen sizes? - flutter

I and my team are working on a different screen size emulator. While integrating we notice that some properties are overlapped by others, and some are not visible only. So how we can make our app adaptive to different screen sizes. Went through the mediaquery() widget but I didn't understood much.

Using MediaQuery class:
MediaQueryData queryData;
queryData = MediaQuery.of(context);
MediaQuery: Establishes a subtree in which media queries resolve
to the given data.
MediaQueryData: Information about a piece of media (e.g., a
window).
To get Device Pixel Ratio:
queryData.devicePixelRatio
To get width and height of the device screen:
queryData.size.width
queryData.size.height
To get text scale factor:
queryData.textScaleFactor
Using AspectRatio class:
From doc:
A widget that attempts to size the child to a specific aspect ratio.
The widget first tries the largest width permitted by the layout
constraints. The height of the widget is determined by applying the
given aspect ratio to the width, expressed as a ratio of width to
height.
For example, a 16:9 width:height aspect ratio would have a value of
16.0/9.0. If the maximum width is infinite, the initial width is determined by applying the aspect ratio to the maximum height.
Now consider a second example, this time with an aspect ratio of 2.0
and layout constraints that require the width to be between 0.0 and
100.0 and the height to be between 0.0 and 100.0. We'll select a width of 100.0 (the biggest allowed) and a height of 50.0 (to match the
aspect ratio).
//example
new Center(
child: new AspectRatio(
aspectRatio: 100 / 100,
child: new Container(
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.orange,
)
),
),
),
Also you can use:
LayoutBuilder
FittedBox
CustomMultiChildLayout

MediaQuery is a good option for this scenario
for example, I just want to create a container with half of the available width and height of my mobile screen
class MyContainer extends StatelessWidget {
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Container(
color:Colors.orange,
width: size.width/2,
height: size.height/2
);
}
}

Related

Is flutter render infinity size?

I am new in flutter I can't understand that is infinity size render in flutter
If I use container with infinity width then it will render but in box constraints documentation infinity size can't render
This is because there is something constraining the widget, when you set as an example:
Container(
width: double.infinity,
),
it will try to take an infinity size, which usually will throw an error to you, but it's constrained so it takes the max possible width.
The Container widget is built on top of different multiples widgets such as ConstrainedBox, DecoratedBox, Align, LimitedBox... , the ConstrainedBox defaults to the BoxConstraints.expand(), check it's source code:
// ...
child: ConstrainedBox(constraints: const BoxConstraints.expand()),
);
but if you check also the Scaffold source code :
// ....
final BoxConstraints fullWidthConstraints = looseConstraints.tighten(width: size.width);
so trying to expand that Container even within infinity, will expand it at maximum on the fullWidthConstraints which is, in this case, the screen's width.

How can i make image in full screen without to lose some parts of image on screen

to display image according to it's original size i do the following
Image.file(File(fileCreated!.path)),
to display image to fit height and width (full screen) i do the following
Image.file(File(fileCreated!.path),fit: BoxFit.cover,height: double.infinity,width: double.infinity,),
ok it is now in full screen but i noticed there is some missing parts of the image contents is no longer visible on screen like 20 pixel from width and height , i know flutter do it for keeping the image quality the same. but How i ignore that behavior
How could i display image in full screen so the whole image parts is visible on screen ?
i tried with following
height:MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
whatever i change the height. the width will be auto changing too, even if i did not change the width !!!!
but same result
edit :
full parent
#override
Widget build(BuildContext context) {
return Scaffold(
body: Image.file(File(widget.imageFile,),fit: BoxFit.cover,height: MediaQuery.of(context).size.height,),
);
}
}
You can use MediaQuery, but I will prefer using LayoutBuilder on top widget. Also check the parent widget if it is having padding/margin.
Image.file(
File(fileCreated!.path),
fit: BoxFit.fill,
height:MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
),

Flutter. Set parent's height based on child canvas drawing's

Is there any way to set parent container's height based on height of what is drawn in the child canvas?
I am using a custom painter like this:
double width = MediaQuery.of(context).size.width;
return Container(
color: Colors.yellow,
height: 240,
width: width,
child: CustomPaint(
painter: ShapePainter(),
),
);
Then ShapePainter() draws different shapes (1 shape for each canvas in the list).
But as you can see, some shapes like 2nd rectangle, take twice the space they actually need.
I can calculate height of a shape inside ShapePainter() easily,
but I have no idea how to apply it to its parent's height. (Except calling an insta-setState() from child, but there should be a better way, because this may flicker for one frame)
Thanks for any help!
Flutter has several phases that it goes through when creating a frame, including building, layout, and painting. The size of widgets is determined during the layout phase. So you can't set the height based it what was painted. (Except, as you've said, by using something like setState to generate a new frame.) You'll have to determine the the size you want before any painting has happened. For example, you can give your CustomPainter a getter to provide the shape:
class ShapePainter extends CustomPainter {
ShapePainter({#required this.shape});
final Shape shape;
void paint(Canvas canvas, Size size) {
// the painting
}
Size get size {
// determine size based on shape
}
}
...
Widget build(BuildContext context) {
final shapePainter = ShapePainter();
return Container(
color: Colors.yellow,
height: shapePainter.size.height,
align: Alignment.center,
child: CustomPaint(
painter: shapePainter,
),
);
}

How flutter calculates screen width

I have a simple flutter setup to get the width of the screen on device with resolution 2960*1440.
However, flutter returns a screen width of 411 when I run the application on resolution 2960*1440. How does flutter calculate width of a device?
class page extends StatelessWidget {
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width.toString();
return Container(
child: Text("Height : $height and Width : $width"),
);
}
}
flutter depends on the MediaQuery method to calculate screen size :
MediaQuery.of(context).size.width ;
as per the documentation it returns the number of the "logical pixels" of your screen which each one of them represent several physical pixels by a factor that differs from a device to another, and if you want the actual number of pixels you can use :
MediaQuery.of(context).size.width * MediaQuery.of(context).devicePixelRatio ;
and for the actual pixels of your screen height:
MediaQuery.of(context).size.height * MediaQuery.of(context).devicePixelRatio ;

How to Determine Screen Height and Width

I've created a new application on Flutter, and I've had problems with the screen sizes when switching between different devices.
I created the application using the Pixel 2XL screen size, and because I've had containers with a child of ListView it's asked me to include a height and width for the container.
So when I switch the device to a new device the container is too long and throws an error.
How can I go about making it so the application is optimized for all screens?
You can use:
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
To get height just of SafeArea (for iOS 11 and above):
var padding = MediaQuery.of(context).padding;
double newheight = height - padding.top - padding.bottom;
Getting width is easy but height can be tricky, following are the ways to deal with height
// Full screen width and height
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
// Height (without SafeArea)
var padding = MediaQuery.of(context).viewPadding;
double height1 = height - padding.top - padding.bottom;
// Height (without status bar)
double height2 = height - padding.top;
// Height (without status and toolbar)
double height3 = height - padding.top - kToolbarHeight;
To clarify and detail the exact solution for future researchers:
Without context:
import 'dart:ui';
var pixelRatio = window.devicePixelRatio;
//Size in physical pixels
var physicalScreenSize = window.physicalSize;
var physicalWidth = physicalScreenSize.width;
var physicalHeight = physicalScreenSize.height;
//Size in logical pixels
var logicalScreenSize = window.physicalSize / pixelRatio;
var logicalWidth = logicalScreenSize.width;
var logicalHeight = logicalScreenSize.height;
//Padding in physical pixels
var padding = window.padding;
//Safe area paddings in logical pixels
var paddingLeft = window.padding.left / window.devicePixelRatio;
var paddingRight = window.padding.right / window.devicePixelRatio;
var paddingTop = window.padding.top / window.devicePixelRatio;
var paddingBottom = window.padding.bottom / window.devicePixelRatio;
//Safe area in logical pixels
var safeWidth = logicalWidth - paddingLeft - paddingRight;
var safeHeight = logicalHeight - paddingTop - paddingBottom;
With context:
//In logical pixels
var width = MediaQuery.of(context).size.width;
var height = MediaQuery.of(context).size.height;
var padding = MediaQuery.of(context).padding;
var safeHeight = height - padding.top - padding.bottom;
Extra info about physical and logical pixels for the curious:
https://blog.specctr.com/pixels-physical-vs-logical-c84710199d62
The below code doesn't return the correct screen size sometimes:
MediaQuery.of(context).size
I tested on SAMSUNG SM-T580, which returns {width: 685.7, height: 1097.1} instead of the real resolution 1920x1080.
Please use:
import 'dart:ui';
window.physicalSize;
Using the following method we can get the device's physical height.
Ex. 1080X1920
WidgetsBinding.instance.window.physicalSize.height
WidgetsBinding.instance.window.physicalSize.width
MediaQuery.of(context).size.width and MediaQuery.of(context).size.height works great, but every time need to write expressions like width/20 to set specific height width.
I've created a new application on flutter, and I've had problems with the screen sizes when switching between different devices.
Yes, flutter_screenutil plugin available for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes!
Usage:
Add dependency:
Please check the latest version before installation.
dependencies:
flutter:
sdk: flutter
# add flutter_ScreenUtil
flutter_screenutil: ^0.4.2
Add the following imports to your Dart code:
import 'package:flutter_screenutil/flutter_screenutil.dart';
Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option
//fill in the screen size of the device in the design
//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);
//If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);
Use:
//for example:
//rectangle
Container(
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
...
),
////If you want to display a square:
Container(
width: ScreenUtil().setWidth(300),
height: ScreenUtil().setWidth(300),
),
Please refer updated documentation for more details
Note: I tested and using this plugin, which really works great with all devices including iPad
Hope this will helps someone
Hey you can use this class to get Screen Width and Height in percentage
import 'package:flutter/material.dart';
class Responsive{
static width(double p,BuildContext context)
{
return MediaQuery.of(context).size.width*(p/100);
}
static height(double p,BuildContext context)
{
return MediaQuery.of(context).size.height*(p/100);
}
}
and to Use like this
Container(height: Responsive.width(100, context), width: Responsive.width(50, context),);
How to access screen size or pixel density or aspect ratio in flutter ?
We can access screen size and other like pixel density, aspect ration etc.
with helps of MediaQuery.
syntex : MediaQuery.of(context).size.height
Just declare a function
Size screenSize() {
return MediaQuery.of(context).size;
}
Use like below
return Container(
width: screenSize().width,
height: screenSize().height,
child: ...
)
A bit late as I had asked the question about 2 years ago and was a newbie back then, but thanks all for the responses as at the time when learning it was a massive help.
To clarify, what I probably should have been asking for was a the Expanded widget, as I believe (hazy memory on what I was trying achieve) I was looking to have a ListView as one of the children of a Column. Instead of using the specific screen size to fit this ListView in the Column I should have been looking to optimise the maximum space available, therefore wrapping the ListView in the Expanded would have had the desired impact.
MediaQuery is great, but I try only to use it to decipher what form factor the screen is using the Material breakpoints, otherwise I try to use the Expanded/Spacer widgets as much as possible, with BoxConstaints on minimum/max sizes, also need to consider the maximum space that is actually available using the SafeArea widget to avoid notches/navigation bar,
Initally I also got stucked in to the issue.
Then I got to know that for mobile we get the exact screen height using MediaQuery.of(context).size.height but for web we will not use that approach so i have use window.screen.height from dart.html library then I also added the max screen size that we can use in web by making some calculations...
import 'dart:html';
getViewHeight =>
window.screen!.height! *
((window.screen!.height! -
kToolbarHeight -
kBottomNavigationBarHeight -
120) /
window.screen!.height!);
kIsWeb
? getViewHeight
: MediaQuery.of(context).size.height * 0.7)
By Using this approach we get max usable screen size dynamically.
import 'dart:ui';
var pixelRatio = window.devicePixelRatio;
//Size in physical pixels
var physicalScreenSize = window.physicalSize;`
Very good, problem is that when you build for --release it does not work.
The reason is that Size is zero at app start so if the code is fast the value of phisicalSize is (0.0, 0.0).
did you find a solution for this ?