In Flutter, you can show different content based on the device’s orientation. To determine the device orientation, just use:
MediaQuery.of(context).orientation
To understand the job more thoroughly, see the example below.
Example
This sample app displays different text based on the device orientation:
- Portrait mode: Your phone is on landscape mode
- Landscape mode: Your phone is on portrait mode
body: MediaQuery.of(context).orientation == Orientation.landscape
?
// Landscape
const Text(
'Your phone is on landscape mode',
style: TextStyle(fontSize: 30, color: Colors.purple),
)
:
// Portrait
const Text(
'Your phone is on portrait mode',
style: TextStyle(fontSize: 18, color: Colors.red),
),
);
Screenshots:
The complete code in main.dart:
// main.dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'KindaCode.com',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('KindaCode.com'),
),
body: MediaQuery.of(context).orientation == Orientation.landscape
?
// Landscape
const Text(
'Your phone is on landscape mode',
style: TextStyle(fontSize: 30, color: Colors.purple),
)
:
// Portrait
const Text(
'Your phone is on portrait mode',
style: TextStyle(fontSize: 18, color: Colors.red),
),
);
}
}
From here, you can build more complex things.
Further reading:
- Flutter: Creating OTP/PIN Input Fields (2 approaches)
- Flutter: 6 Best Packages to Create Cool Bottom App Bars
- Flutter: TextField and Negative Numbers
- Flutter: AbsorbPointer example
- Using BlockSemantics in Flutter: Tutorial & Example
- Using Provider for State Management in Flutter
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.