Flutter: Show different content based on device orientation

Updated: February 6, 2023 By: A Goodman Post a comment

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:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles