Flutter UI Orientation

Using the UI based  Orientation:

In certain cases, it can be handy to update the design of an app when the user rotates their screen from portrait mode to landscape mode. For example, we may want to show one item after the next in portrait mode and side-by-side in landscape mode.

 

In this Flutter app, we are building two different layouts depending on a given Orientation. In this example, we’ll build a list that displays 2 columns in portrait mode and 3 columns in landscape mode.

Using Orientation in Flutter App:

  • Creating a GridView with 2 columns
  • Use an OrientationBuilder to change the number of columns

Creating a GridView with 2 columns:

First, we  need a list of items to work with. Rather than using a normal list, we’ll want a list that displays items in a Grid view. For that, we are creating a grid view with 2 columns.

GridView.count(
// A list with 2 columns
crossAxisCount: 2,
// ...
);

Use an OrientationBuilder to change the number of columns in flutter App:

In identify the current Orientation, we will use the OrientationBuilder Widget. The OrientationBuilder  widget calculates the current Orientation by comparing its width and height available to the parent widget, and rebuilds when the size of the parent changes.

Use  the below code for Orientation, we can build a list that displays 2 columns in portrait mode, or 3 columns in landscape mode.

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,
);
},
);

Below is the Complete Example code for Orientation Flutter App:

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'Orientation Demo';

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)),
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.headline,
),
);
}),
);
},
),
);
}
}

Congratulations You Have Learned UI Orientation In Flutter App..!!!

 

If it is useful please share it with your Friends…!!!

If  You Have Any Query Please make A Comment….!!!

Leave a Reply

Categories