There are two types of devices in mobile range, Tablet and Mobile. Tablet device has different layout than mobile device because in Tablet view default mode is Landscape. Some times there are few differences between mobile and tablet device. So we have to make separate layout for both of them. This type of functionality is called as loading layout according to orientation. In flutter we can do this with OrientationBuilder widget.
Flutter Detect Device Orientation & Load Separate Layout
1. Creating PortraitScreen class. This is our default View for portrait mobile design.
class PortraitScreen extends StatelessWidget {
const PortraitScreen({super.key});
@override
Widget build(BuildContext context) {
return const Text('Portrait Screen',
textAlign: TextAlign.center, style: TextStyle(fontSize: 24));
}
}
2. Creating another class LandscapeScreen. This will be our Landscape screen.
class LandscapeScreen extends StatelessWidget {
const LandscapeScreen({super.key});
@override
Widget build(BuildContext context) {
return const Text('Landscape Screen',
textAlign: TextAlign.center, style: TextStyle(fontSize: 24));
}
}
3. Creating OrientationBuilder widget in body section of our main app and call both above PortraitScreen and LandscapeScreen class with Ternary operator. If device orientation is Portrait it will load the PortraitScreen class and If the device orientation is landscape it will load the LandscapeScreen class.
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(home:
Scaffold(body: OrientationBuilder(builder: (context, orientation) {
return Center(
child: orientation == Orientation.portrait
? const PortraitScreen()
: const LandscapeScreen());
})));
}
}
Source code for main.dart file:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class PortraitScreen extends StatelessWidget {
const PortraitScreen({super.key});
@override
Widget build(BuildContext context) {
return const Text('Portrait Screen',
textAlign: TextAlign.center, style: TextStyle(fontSize: 24));
}
}
class LandscapeScreen extends StatelessWidget {
const LandscapeScreen({super.key});
@override
Widget build(BuildContext context) {
return const Text('Landscape Screen',
textAlign: TextAlign.center, style: TextStyle(fontSize: 24));
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(home:
Scaffold(body: OrientationBuilder(builder: (context, orientation) {
return Center(
child: orientation == Orientation.portrait
? const PortraitScreen()
: const LandscapeScreen());
})));
}
}
Comments
Post a Comment