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.
In this article, we will look into the same by building a simple application and change its orientation and display the UI changes.
Steps to Implement UI Orientation
Step 1 : Create a GridView
To create a GridView of 3 columns, use the code as shown below:
GridView.count(
crossAxisCount: 3,
);
To know more about gridview in flutter refer this article: Flutter – GridView
Step 2 : 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.
Follow the below code:
OrientationBuilder(
builder: (context, orientation) {
return GridView.count(
crossAxisCount: orientation == Orientation.portrait ? 3 : 4,
);
},
);
Complete source code(main.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,
debugShowCheckedModeBanner: false,
home: OrientationList(
title: appTitle,
),
);
}
}
class OrientationList extends StatelessWidget {
final String title;
OrientationList({super.key, required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
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.headlineMedium,
),
);
}),
);
},
),
);
}
}
Output: