20.4 C
New York
Sunday, April 2, 2023

Flutter: Show different content based on device orientation

In Flutter, you can show different content based on the device orientation. To determine the device orientation, just use:

MediaQuery.of(context).orientation

Example

This sample app displays different text based on the device orientation:Advertisements

 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
  _HomePageState 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.

Advertisements

Related Articles

Latest Articles