How to Update an UI Based on Orientation in Flutter?
Tags: flutter, programming, tutorial, webdev
Published: 2022-10-17 12:48:16

There are several cases where the user needs to change the screen’s orientation, like while streaming a movie or reading something. Once the orientation changes from landscape to portrait and vice versa, certain UI elements also get updated.

Find Flutter developer to customize an UI elements update after an orientation changes from one type to another. In this blog, we have given the brief idea by the entire process of coding, and the changes that is being Followed for UI elements. In the Flutter development , an screen is rotated from portrait to landscape or from landscape to portrait.

##How to form GridView for columns?

First of all, let’s understand what the grid and columnar views are. Suppose you have nine items you want to display on the screen in a particular order. For this, you usually choose the normal method to display them like a series of numbers, one after another, vertically. This is known as the columnar view because all the items are listed in a single column.

But it doesn’t look good, especially when you have many items listed. It becomes difficult to find the required data, but if you apply the same concept to the UI layout, everything will look like they have been forcefully shifted to one side of the screen. This is where the grid view comes into play. The best way to define the grid view is to consider an MxN matrix. Here, m is the number of columns, and n is the number of rows.

For m = 1 and n = 1, you will place the first item and then for m = 2 and n = 1, you will place the second item. This way you go on filling the cells of the matrix till you don’t have any item left with you. The combinatorial structure of rows and columns is known as the grid. It is one of the best ways to display items on the UI since when you want to code according to the screen’s orientation, you need to position the elements or define their functional and visual attributes based on a grid.

To define a grid in Flutter, you need to use the GridView widget. Within it, you need to use the GridView.count() constructor for defining the number of columns. You can change the style of the UI elements according to the way you want them to be displayed. You have created a grid view with this constructor and included 10 columns.

##How to Implement the OrientationBuilder function that change column numbers?

Now, you need to determine the present orientation of the app on the device. For this, you need to use the OrientationBuilder widget. It is linked to the parent orientation class. Once the parent orientation changes, it calculates the current orientation by comparing the height and width ratio to that of the parent. Accordingly, it sets the value of the OrientationBuilder widget.

Using the Orientation variable, you can set the number of columns in portrait mode to be 2 and for the landscape orientation mode, set it as 3. Using a conditional operation, you need to detect if the current orientation has two or three columns. The best way to define this statement in your codebase is:

```dart
columnNumber: orientation == Orientation.portrait ? 2:3
```

Here, you are determining if the number of columns for the current orientation is two or three. If it is two, then the list of UI elements will be displayed in portrait mode. On the other hand, if columnNumber is 3, then the UI elements will be displayed in landscape mode.

You can also use the if and else block to set the orientation mode based on the comparison between the pre-defined or parent orientation and the value calculated by the Orientation builder. The statement block will look like this:

```dart
if (orientation==Orientation.portrait)
{ return portraitMode(); } else {return landscapeMode()};
```

The portraitMode() and landscapeMode() will now define the state of the UI elements like the text blocks and pictures. Once a particular function is called, for example, say the else condition is true and landscapeMode() is called, the code block within this method will be executed.

Here, the width of the screen will be more than the height. Therefore, you can accommodate more items along each row than the column. On the contrary, if we consider the if statement is true, the portraitMode() method will be called. Here, you need to define the UI elements so that the column widgets can hold more items than the rows.

If you have more UI elements or want to resize the elements when the orientation changes, you need to define the approximate number of columns within the GridView widget. Do ensure to balance the number of items displayed in the grid view as it will impact the negative and positive screen space.

##Example:

```dart
import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    const appTitle = 'Orientation Demo';
    return const MaterialApp(
      title: appTitle,
      home: OrientationList(
        title: appTitle,
      ),
    );
  }
}
class OrientationList extends StatelessWidget {
  final String title;
  const OrientationList({super.key, required this.title});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: OrientationBuilder(
        builder: (context, orientation) {
          return GridView.count(
            // Create a grid with 2 columns in portrait mode, or 3 columns in
            // landscape mode.
            crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
            // Generate 100 widgets that display their index in the List.
            children: List.generate(100, (index) {
              return Center(
                child: Text(
                  'Item $index',
                  style: Theme.of(context).textTheme.headline4,
                ),
              );
            }),
          );
        },
      ),
    );
  }
}
```

##Output:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dawrapr0mi9a8ameapx6.gif)

##Conclusion

In this article, we have defined how the UI elements can be updated once the screen orientation changes from portrait to landscape or landscape to portrait in Flutter. It is very easy to complete the codebase because you need to extend the Stateless Widget class and use two built-in widgets, namely GridView for defining the number of columns and OrientationBuilder to detect the current orientation and decide whether the screen view is in portrait or landscape.

##Frequently Asked Questions (FAQs)

**1. What is an OrientationBuilder widget in Flutter development?**

An orientation builder will calculate the current orientation by comparing its width and height, which is available to a parent widget and will rebuild when the size of a parent changes. With orientation, create a list that will display the two columns in portrait mode or three columns in landscape mode.

**2. Define the GridView widget in Flutter app development.**

The Gridview widget in Fluter will display the items in two-dimensional rows and columns. It is used when we want to view the items in the grid. Moreover, we can select the desired item from a grid list by tapping on them.

**3. State the stateless widget in Flutter.**

The widget will describe a part of the user interface by creating a constellation of the other widgets that will represent a more tangible user interface.