Skip to content

Using native_device_orientation in a Flutter Project

  • by

Using native_device_orientation in a Flutter Project

The native_device_orientation plugin provides a way to read the device’s native orientation, either from the UI orientation or from the sensors. This can be especially useful for applications that need to differentiate between landscape left and landscape right orientations, or portrait up and portrait down.

Step-by-Step Implementation

We’ll create a mini-project named Device Orientation Demo to showcase the usage of this plugin. The app will display the current orientation of the device on the screen and allow the user to toggle between using the device’s sensors and the UI orientation.

1. Project Setup

First, create a new Flutter project:

flutter create device_orientation_demo
cd device_orientation_demo

Update your pubspec.yaml to include the necessary dependencies:

dependencies:
  flutter:
    sdk: flutter
  native_device_orientation: ^2.0.3

2. Main Dart Code

Create a main.dart file and implement the following code:

import 'package:flutter/material.dart';
import 'package:native_device_orientation/native_device_orientation.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  bool useSensor = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Device Orientation Demo'),
          actions: <Widget>[
            const Center(child: Text('Sensor:')),
            Switch(
              value: useSensor,
              onChanged: (val) => setState(() => useSensor = val),
            ),
          ],
        ),
        body: NativeDeviceOrientedWidget(
          landscape: (context) {
            return const Center(child: Text('Native Orientation: Landscape (Unknown Side)\n'));
          },
          landscapeLeft: (context) {
            return const Center(child: Text('Native Orientation: Landscape Left\n'));
          },
          landscapeRight: (context) {
            return const Center(child: Text('Native Orientation: Landscape Right\n'));
          },
          portrait: (context) {
            return const Center(child: Text('Native Orientation: Portrait (Unknown Side)\n'));
          },
          portraitUp: (context) {
            return const Center(child: Text('Native Orientation: Portrait Up\n'));
          },
          portraitDown: (context) {
            return const Center(child: Text('Native Orientation: Portrait Down\n'));
          },
          fallback: (context) {
            return const Center(child: Text('Native Orientation: Unknown\n'));
          },
          useSensor: useSensor,
        ),
        floatingActionButton: Builder(
          builder: (context) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                FloatingActionButton(
                  child: const Text('Sensor'),
                  onPressed: () async {
                    final orientation = await NativeDeviceOrientationCommunicator().orientation(useSensor: true);
                    if (!context.mounted) return;
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('Native Orientation read: $orientation'),
                        duration: const Duration(milliseconds: 500),
                      ),
                    );
                  },
                ),
                const SizedBox(height: 10),
                FloatingActionButton(
                  child: const Text('UI'),
                  onPressed: () async {
                    final orientation = await NativeDeviceOrientationCommunicator().orientation(useSensor: false);
                    if (!context.mounted) return;
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('Native Orientation read: $orientation'),
                        duration: const Duration(milliseconds: 500),
                      ),
                    );
                  },
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

Explanation

  1. Main Setup: The main.dart file sets up a simple Flutter app with a switch to toggle between using the device’s sensors and the UI orientation.

  2. AppBar: The AppBar contains a switch to enable or disable the use of sensors.

  3. NativeDeviceOrientedWidget: This widget automatically updates the display based on the device’s orientation. It differentiates between landscape left, landscape right, portrait up, and portrait down.

  4. FloatingActionButton: Two buttons allow the user to get the orientation either using sensors or UI orientation. When pressed, they display the orientation using a Snackbar.

Running the Application

Ensure your development environment is set up for both Android and iOS, and then run the application:

flutter run

Conclusion

This mini-project demonstrates how to use the native_device_orientation plugin to read and display the device’s orientation. By integrating this plugin, you can build more sophisticated applications that respond dynamically to changes in device orientation, providing a better user experience.

FAQ Section

Q1: What is the purpose of the native_device_orientation plugin?

A: The native_device_orientation plugin provides a way to read the device’s native orientation, either from the UI orientation or from the device’s sensors. This is useful for applications that need to differentiate between specific orientations, such as landscape left, landscape right, portrait up, and portrait down.

Q2: How do I install the native_device_orientation plugin in my Flutter project?

A: To install the plugin, add the following dependency to your pubspec.yaml file:

dependencies:
  native_device_orientation: ^2.0.3

Then, run flutter pub get to install the plugin.

Q3: What permissions do I need to add for this plugin to work on Android and iOS?

A: The native_device_orientation plugin doesn’t require special permissions beyond the default ones for Flutter applications. However, make sure your Info.plist (iOS) and AndroidManifest.xml (Android) files have the necessary permissions for general app functionality.

Q4: How can I switch between using the device’s sensors and the UI orientation?

A: In the provided code example, there’s a Switch widget in the AppBar that allows you to toggle between using the device’s sensors (useSensor = true) and the UI orientation (useSensor = false). You can control this behavior by updating the useSensor state.

Q5: What are the different orientation states provided by the native_device_orientation plugin?

A: The plugin can detect the following orientation states:

  • Landscape (unknown side)
  • Landscape Left
  • Landscape Right
  • Portrait (unknown side)
  • Portrait Up
  • Portrait Down
  • Unknown

Q6: How do I display the current orientation in my app?

A: You can use the NativeDeviceOrientedWidget to automatically update the UI based on the current orientation. This widget provides different builder functions for each orientation state, allowing you to customize the display for each orientation.

Q7: How can I manually fetch the device orientation using this plugin?

A: You can fetch the orientation using the NativeDeviceOrientationCommunicator class. It has methods like orientation(useSensor: bool) to get the current orientation and onOrientationChanged(useSensor: bool) to listen for orientation changes. Here’s an example:

final orientation = await NativeDeviceOrientationCommunicator().orientation(useSensor: true);

Q8: What should I do if the plugin throws a build error on iOS after updating to version 2.*?

A: If you encounter a build error on iOS, follow these steps:

  1. Update to native_device_orientation version 2.*
  2. Remove your Podfile.lock file
  3. Run flutter clean
  4. Rebuild your iOS project using flutter build ios or run for an iOS device

Q9: Can I use this plugin to differentiate between specific landscape or portrait orientations?

A: Yes, the plugin provides specific orientation states for landscape left, landscape right, portrait up, and portrait down, allowing you to handle each orientation uniquely.

Q10: Where can I find more information or report issues with the plugin?

A: You can find more information, read the documentation, and report issues on the plugin’s pub.dev page.

Leave a Reply

Your email address will not be published. Required fields are marked *