35.2 C
New York
Tuesday, August 9, 2022

Flutter: Show different content based on device orientation

- Advertisement -

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
- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles