Open In App

Flutter – UI Orientation

Improve
Improve
Like Article
Like
Save
Share
Report

All applications should be able to adjust their User Interface (UI) based on the orientation of the phone. By orientation, we implicate the portrait and landscape mode in smartphones rather the physical orientation. In, Flutter it is done so by using the OrientationBuilder, which determines the app’s current orientation. We will look into the same by building a simple application and change its orientation and display the UI changes.

Follow the below steps to build the application that changes UI based on the orientation of the phone:

  • Create a GridView of 3 columns
  • Use the OrientationBuilder to alter the number of columns.

Let’s discuss them in detail.

Create a GridView:

To create a GridView of 3 columns, use the code as shown below:

Dart




GridView.count(
  crossAxisCount: 3,
);


Using OrientationBuilder:

As discussed earlier, the orientationBuilder determines the orientation of the current application. We will design the Orientationbuilder in such a way that it displays 3 columns in portrait mode and 4 columns in landscape mode. to do so follow the below code:

Dart




OrientationBuilder(
  builder: (context, orientation) {
    return GridView.count(
      crossAxisCount: orientation == Orientation.portrait ? 3 : 4,
    );
  },
);


The complete code would look like below:

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'GeeksForGeeks';
  
    return MaterialApp(
      title: appTitle,
      home: OrientationList(
        title: appTitle,
      ),
    );
  }
}
  
class OrientationList extends StatelessWidget {
  final String title;
  
  OrientationList({Key key, this.title}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text(title),
          backgroundColor: Colors.green),
      body: OrientationBuilder(
        builder: (context, orientation) {
          return GridView.count(
             
            //grid with 3 and 4 columns for portrait and landscape mode respectively
            crossAxisCount: orientation == Orientation.portrait ? 3 : 4,
              
            // random item generator
            children: List.generate(100, (index) {
              return Center(
                child: Text(
                  'A $index',
                  style: Theme.of(context).textTheme.headline4,
                ),
              );
            }),
          );
        },
      ),
    );
  }
}


Output:



Last Updated : 16 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads