Flutter adaptive screen

Vlad Konoshenko
2 min readJun 17, 2020

This is my first article, try to be brief

Introduction

Mobile applications must support a variety of display sizes, pixel densities and orientations. Applications should be able to scale, handle orientation changes and at the same time maintain the state of the screen. In this article, we will consider one of the possible solutions to this problem using the Practice Guru application as an example. Flutter gives you the freedom to choose your solution methods, however I will demonstrate the one we selected in the project.

Check screen sizes.

To obtain the result, it is necessary to determine a number of parameters, namely, the screen size on which the application is running and the current orientation. We can get both of these parameters by executing the following code:

MediaQuery.of(context).orientation;
MediaQuery.of(context).size;

Having these parameters, we use them to determine the type of device

var isTablet = MediaQuery.of(context).size.width > 600;

After which we have the opportunity to set the available orientation types for the current screen using the code:

SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight]);

Check screen orientation.

Okay, now we can handle the rotation of the screen, however. Such an implementation does not cause a turn for the tablet either. Add the necessary check, which determines the type of device and the orientation for it.

var isTablet = MediaQuery.of(context).size.width > 600;
SystemChrome.setPreferredOrientations(isTablet
? [
DeviceOrientation.landscapeLeft,DeviceOrientation.landscapeRight, DeviceOrientation.portraitUp,DeviceOrientation.portraitDown
]
: [DeviceOrientation.portraitUp,DeviceOrientation.portraitDown]);

Ok, let’s move on to building the screen itself, the first method that begs for it is simply to compare to get the orientation and add if case. The problem with this approach is that we get this screen only during the first build and we do not rebuild the screen when turning it.

As for me, it’s better to use the OrientationBuilder widget.

OrientationBuilder(
builder: (_, orientation) {
return orientation == Orientation.landscape?
isLargeScreen?Row(
children[
Expanded(child:_buildHorizontalScreen()),
Expanded(child: _buildPortraitScreen())
],
)
: _buildHorizontalScreen()
: _buildPortraitScreen();
},)

Conclusion

That’s all, now we can split the screen into different states, as well as build ui depending on the current position of the device. The results of the application in the screenshot.

We got an application that has only portrait orientation on mobile devices. But the tablet has two states in horizontal orientation, we display two fragments, and in the portrait main screen

--

--