When specifying widget size in flutter should I use int or double? For example, should it be SizedBox(width:8), or SizedBox(width:8.0)?
I tried looking into flutter docs, but could find anything about this, so instead I looked for examples: https://docs.flutter.dev/development/ui/layout and https://api.flutter.dev/flutter/widgets/SizedBox-class.html, but they seem to be inconsistent...
When you want to set round value, you don't need to use double but otherwise you need it.
If you go inside the SizedBox you will see a Double waiting there. When you type 8, SizedBox treats it as 8.0 anyway.
Inside SizedBox it is
const SizedBox({ super.key, this.width, this.height, super.child });
const SizedBox.expand({ super.key, super.child })
: width = double.infinity,
height = double.infinity;
I'm getting height and width of the screen size using Get.context!.height and Get.context!.width. This works perfect in Debug mode. But in the release APK, it's not working at all due to which all the elements based on these are disappearing.
I also tried using MediaQuery but as the height and width are being used inside a class that doesn't have any BuildContext, MediaQuery is not the solution. So I went with Get.context! which works great in debug version. Once I switch to release version, bam, it no longer works.
Here is the code which is not working in release mode but working in debug mode :
class Dimensions {
static double screenHeight = Get.context!.height;
static double screenWidth = Get.context!.width;
static double pageView = screenHeight / 3.08;
static double pageViewContainer = screenHeight / 4.00;
static double pageDetailsContainer = screenHeight / 7.40;
static double imageButtonSectionHeight = screenHeight * 0.195;
}
Try using Get.overlayContext instead of Get.context`.
I'm using Getx also, please if this also didn't work, consider passing the context as a parameter from the constructor of that class or from your method and use the MediaQuery.of(context) instead.
the BuildContext topic is essential, and it can also be problematic if used incorrectly.
I want to display a double (or int) similar to how you would a string with a Text() widget. Is there an equivalent to this widget for ints or doubles in Flutter? Sorry if this is obvious, but I could not find anything.
Text("${<Your double/int variable>"})
You use a Text widget for this as well, simply use string interpolation to display your variables as a String:
final int two = 2;
final double pi = 3.14;
return Text("$two is an integer, and $pi is a double.");
You can also use the toString() method on any object in Dart (which is what the string interpolation above does implicitly). So if you want to print a double by itself, it's possible to write:
Text(pi.toString());
More on Strings and interpolation
Does the dx property of the Offset class return the double value of the logical pixels on the x-axis? I need to know if I can measure say a percentage of the dx against MediaQuery.of(context).size.width?
Short answer: The dx property of an Offset object and the Width size of a Media Query are both doubles (pixel, yes) thus you can divide, multiply or do any math operation with them (separately or with each other). So, you can do your OffsetObject.dx/MediaQuery(context).Size.Width to get the percentage. You can run the code block below on Dart pad.
Loooong Answer: Not sure it adds more info.
Yes, of course you can measure the dx property of an Offset object against the width property of a MediaQuery because they are both of type double.
The mere fact that they are both of type doubles should allow you to carry out any math/arithmetic calculation you need. See the sample app below. the text returns the numbers (you can run it on Dartpad). I explained the variables/objects defined below as well.
ScreenWidthSize: the MediaQuery width, note the type is double. MediaQuery.of(context).size.width returns an object of type double.
offsetMagnitude: This defines the Offset object (I am not sure how you will get your Offset object so this for illustration. Then I need to get the dx.
horizontalOffset: This defines/extracts the dx property of the offsetMagnitude, the offset object. Note it is a double too.
horizontalOffsetToScreenWidthRatio: Since both ScreenWidthSize and horizontalOffset are doubles, I can carry out any mathematical operation, as long as they are applicable to the type double. I have therefore measured the percentage (we can format the result better but you get it).
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
double screenWidthSize = MediaQuery.of(context).size.width;
Offset offsetMagnitude = Offset(12,25);
double horizontalOffset = offsetMagnitude.dx;
double horizontalOffsetToScreenWidthRatio = offsetMagnitude.dx/screenWidthSize;
return Text(
'Hello, my screen is $screenWidthSize wide and my horizontal offset is $horizontalOffset, so the horizontal offset to screen width ratio is $horizontalOffsetToScreenWidthRatio',
style: Theme.of(context).textTheme.headline4,
);
}
}
/* Not sure what you are trying to achieve but it seems like some form of adaptive or responsive operation. I think if you check the docs, you will find a close widget needing only little manipulation to achieve what you want. Check the Align widget, might be what you need*/
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 ?