byhuang1998
byhuang1998

Reputation: 417

flutter: how to suit all the screen sizes with the same program?

I'm new in flutter. UI designers provide an XD based on the iPad. When I deal with the size of the widgets, I just set the size the same as the XD shows (in px). For example: height: 100, width: 100. But today I tested the app on a physical device(a mobile phone much smaller than an iPad), everything is overflow. I ignore this problem all the time when I use an emulator the same size as the iPad in XD. So how to adapt to different devices with different screen sizes? Is there a function or some other tools helpful?

Upvotes: 0

Views: 7086

Answers (2)

sidrao2006
sidrao2006

Reputation: 1328

Flutter has some built in widgets to solve this problem.

As stated in the responsive UI design page,

1. LayoutBuilder

LayoutBuilder is a great option as it accepts a builder which provides BuildContext and BoxConstraints. The builder is called every time a layout changes.

2. MediaQuery.of()

MediaQuery.of() gives you the size, orientation, etc, of your current app. This is more useful if you want to make decisions based on the complete context rather than on just the size of your particular widget. Again, if you use this, then your build function automatically runs if the user somehow changes the app’s size.

3. OrientationBuilder, FractionallySizedBox, AspectRatio

OrientationBuilder gives you the current screen orientation.

FractionallySizedBox and AspectRatio give you the parent's size.

You could also use some third party packages -

1. flutter_screenutil

This package creates a design draft and lets you use pixel-like values which are highly responsive.

2. auto_size_text

This package is useful for responsive sized text.

Upvotes: 3

Yash Dixit
Yash Dixit

Reputation: 276

When I usually create a flutter app, for its responsiveness I usually use these points:

  • Use of Expanded, Flexible, and Spacer Widgets when using Rows and Columns: All of these have a property called flex which is highly useful. Whenever I use rows or columns I use these widgets.

  • Use of Layout Builder and Media Query widgets: These are there in the documentation: Creating responsive apps (There are more articles on this flutter documentation which are recommended), can be used to know the screen size, the width, and the height, also how your apps function in different orientations. MediaQuery gives the width and height as follows: double w = MediaQuery.of(context).size.width;

    double h: MediaQuery.of(context).size.height;

  • Use of external libraries: There are two libraries on pub.dev which I frequently use in my projects, which are Device Preview (Shows how your app will work on different screen sizes, helps me out a lot) and the other one is for the text, which is Auto Size Text: Might not be preferable as this resizes the text and which then may not be constant throughout the app, but it is useful sometimes!

Upvotes: 1

Related Questions