Git Product home page Git Product logo

flutter_native_device_orientation's Introduction

Native Device Orientation

pub package

This is a plugin project that allows for getting the native device orientation.

Why?

Flutter provides a couple of way to get the 'orientation', but they all amount to basically checking whether the screen is taller or wider. This could fail for a strangely shaped device, but that isn't the primary issue.

The primary issue is that this method doesn't differentiate between landscape left and landscape right (what you get from rotation an upright phone left or right).

This isn't an issue for most applications, but when I was writing a plugin which displays a camera image, it became a problem as I need to know which way the screen is rotated.

Updating to 2.*

Due to the objective c code being removed from the project, updating to 2.0 can sometimes result in a build error, something like the following:

Definition of 'NativeDeviceOrientationPlugin' must be imported from module 'nativeDeviceOrientation.Swift' before it is required

Unfortunately, this is a build-system issue and as such cannot be fixed easily by the developer. To resolve the issue, you can simply follow these steps:

  • Update to flutter_native_device_orientation version 2.*
  • remove your Podfile.lock
  • run flutter clean
  • run flutter build ios or run for an iOS device

UseSensor

When using either the build-in widget or the plugin directly, there is an option you can pass in which is called useSensor. When it is true, the device's sensors are used directly rather than simply using the window/page orientation. By default it is false, which means the plugin doesn't to much more than simply tell you whether the window is oriented landscapeLeft or landscapeRight.

This has been tested less thoroughly than other parts of the plugin so your mileage may vary and if you run into any issues please open an issue!

Using the plugin - built-in "reader" widget

There are three ways of using the plugin. The simplest entails encapsulating your code in a NativeDeviceOrientationReader widget, and then using NativeDeviceOrientationReader.orientation(context); in a widget encapsulated within the context.

This allows you to control when the device starts listening for orientation changes (which could use a bit of energy) by deciding where the NativeDeviceOrientationReader is instantiated, while being able to access the orientation in a simple way.

Note that there could be a very slight time between when the NativeDeviceOrientationReader widget is instantiated and when the orientation is read where the widget could be built with an incorrect orientation; it uses flutter's method of size until the first message it receives back from the native code (which should be fairly immediate anyways). It assumes that landscape is right and portrait is upright during this time.

See the source code for more details.

Using the plugin - built-in "oriented" widget

The second approach is more involved, but involves slightly less boilerplate, and may be a bit more obvious to use. It wraps the NativeDeviceOrientationReader widget, then automatically checks the orientation for you. Instead of passing in a single builder function, you pass one for each orientation you wish to define: landscapeLeft, landscapeRight, portraitUp, and portaitDown are the most obvious, followed by simply landscape and portrait for situations where you don't care to define different layouts for either of those, and finally the (required) fallback, used in cases where either you don't have a more specific builder defined, or something goes horribly horribly wrong.

You sacrifice a bit of control over when to actually retrieve the orientation info in exchange for the plugin handling orientation updates automatically. Since this approach does a bit more hand holding, processing things like NativeDeviceOrientation.unknown for you, it's the approach in the example app.

See example and source code for more details.

Using the plugin - directly

It is also possible to bypass the helper widget to access the native calls directly. This is done by using the NativeDeviceOrientationCommunicator class. It is a singleton but can be instantiated like a normal class, and handles the communication between the ios/android code and the flutter code.

This class has two interesting methods:

  1. Future<NativeDeviceOrientation> orientation(useSensor: false): This can be called to get the orientation asynchronously.

  2. Stream<NativeDeviceOrientation> onOrientationChanged(useSensor: false): This can be called to get a stream which receives new events whenever the orientation changes. It should also get an initial value pretty much immediately.

flutter_native_device_orientation's People

Contributors

davidmartos96 avatar desmese avatar ethael avatar rmtmckenzie avatar shangyilim avatar valentingrigorean avatar zanesc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

flutter_native_device_orientation's Issues

[Android] When smartphone is flat, orientation(useSensor: true) will fail.

I used to have my smartphone flat on the table while debugging. When I not move the smartphone and want to call the method, the method just fails. It doesn't return and it doesn't throw an Exception. After moving the phone it works as expected, so I think the error is caused of not having a default orientation on init when the vertical and horizontal orientations are overlaying each other.

Implement platform orientation locking [enhancement]

Great package!

Any chance of implementing platform methods to lock orientation on the platform side?

Flutter SystemChrome orientation locks don't work when using a non-standard dart entry point, as we are. We are overlaying a component of our flutter app and using native to display the flutterview.
Being able to lock orientation would be a god-send.

nativeOrientation != null

When I try to get the device Orientation, the plugin throw this error.

Another exception was thrown: 'package:native_device_orientation/native_device_orientation.dart': Failed assertion: line 218 pos 16: 'nativeOrientation != null': is not true.
Flutter 1.22.4

[IOS] The Info.plist key 'BGTaskSchedulerPermittedIdentifiers' must contain a list of identifiers used to submit and handle tasks when 'UIBackgroundModes' has a value of 'processing'.

Generate .ipa file for ios.

Build Error:

Asset validation failed (90771) Missing Info.plist value. The Info.plist key 'BGTaskSchedulerPermittedIdentifiers' must contain a list of identifiers used to submit and handle tasks when 'UIBackgroundModes' has a value of 'processing'. For more information, refer to the Information Property List Key Reference at https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Introduction/Introduction.html.

I tried to solve it in the following way :
The Info.plist key 'BGTaskSchedulerPermittedIdentifiers' must contain a list of identifiers used to submit and handle tasks when 'UIBackgroundModes' has a value of 'processing'. #105

I want to understand why this plugin needs to use BGTaskSchedulerPermittedIdentifiers.

Thanks.

Orientation with UseSensor changes too soon.

On both Android and iOS a deadband is used so that rotation only happens when the device is rotated past a certain point. Also, it doesn't seem that the rotation happens at a particular x-y ratio, but rather it depends on the yaw, pitch and roll (i.e. there's a different x-y ratio when the device is upright compared to when it's almost horizontal).

This isn't really all that important except that it's a better user experience as you won't ever get fast swapping between landscape/portrait, and if you put the device flat it stays in whichever orientation it had previously. And if you have rotation enabled on the device and still use sensor orientation, right now the plugin detects rotation much before the app actually rotates.

More investigation is needed as to what this point (or more likely surface in the x-y-z rotation coordinate system) is to emulate the non-sensor behaviour when rotation is enabled. If I get a chance I'll look into it but likely this is something that won't get done any time soon.

Plugin returns oposite orientation when in landscape on iOS

I am trying to lock device orientation on one of the screens in a flutter app. The problem I am facing is that the plugin returning opposite orientation on iOS when the app in landscape mode, I can manually change it in the app, but I think you should be aware of this issue.

The device used: iPhone xs with iOS 15.0

flutter --version output:
Flutter 2.5.3 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 18116933e7 (5 weeks ago) • 2021-10-15 10:46:35 -0700
Engine • revision d3ea636dc5
Tools • Dart 2.14.4

native_device_orientation: 1.0.0

Overlay not printed properly on iOS

Hey, thanks again for the QR reader package along with this, it works just fine.

I'm facing an issue which if you think is not relevant here I will remove but I appreciate any kind of input and I want to make sure this is not because of this orientation package that you have used.

I'm using this package along with the support for the overlay for which I have modified the code a little bit to get the bounding box from the vision API (I'm happy to create a PR if it is required for the QR package).

I have successfully implemented this on the Android side but now when I'm trying it on the iOS, I'm getting the bounding box and also the overlay but when the device is in portrait mode (it will always be portrait since I have made so while building) the overlay is rotated i.e the overlay is printed as if the device is in landscape mode which is the problem here.

As per my knowledge, this has nothing to do with the orientation package as it is displaying the orientation properly when the device is rotated. If you can confirm once, it will be really helpful.

The code can be found here.

Below is the GIF of the issue that I have mentioned.

ios

[Android] Unable to build - missing semicolon

Cannot build Android app with latest (1.1.3) version of package.

native_device_orientation-1.1.3/android/src/main/java/com/github/rmtmckenzie/native_device_orientation/SensorOrientationListener.java:49: error: ';' expected new OrientationEventListener()

Orientation is different on iOS than on Android

Hi,

I am using your plugin to fix an orientation issue with the flutter camera plugin.

I am experiencing different orientations depending on the platform.

If you use the following code both on a iOS device and an Android device, you will see different orientations being reported.

Rotate the Android phone by 90° to the right (home button on left side), then you get NativeDeviceOrientation.landscapeRight.
If rotating the iOS phone by 90° to the right (home button on left side), then you get NativeDeviceOrientation.landscapeLeft.

If you read the Apple docs on UIDeviceOrientation.landscapeLeft, it states the following

The device is in landscape mode, with the device held upright and the home button on the right side.

NativeDeviceOrientation.portraitDown isn't reported at all for iOS device (also not on simulator).

I am using plugin version 0.0.3.

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

main() {
  runApp(App());
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text('Rotation'),
      ),
      body: buildOrientationReader(),
    ));
  }

  Widget buildOrientationReader() {
    var rotatedBody = NativeDeviceOrientationReader(builder: (context) {
      NativeDeviceOrientation orientation =
          NativeDeviceOrientationReader.orientation(context);
      print(orientation.toString());

      int turns;
      switch (orientation) {
        case NativeDeviceOrientation.landscapeRight:
          turns = 1;
          break;
        case NativeDeviceOrientation.portraitDown:
          turns = 2;
          break;
        case NativeDeviceOrientation.landscapeLeft:
          turns = 3;
          break;
        default:
          turns = 0;
          break;
      }

      print('turns: $turns');

      return RotatedBox(
        child: Image.network(
            'https://cdn-images-1.medium.com/max/1200/1*5-aoK8IBmXve5whBQM90GA.png'),
        quarterTurns: turns,
      );
    });
    return rotatedBody;
  }
}

MissingPluginException

When i run flutter test i get the folowing error:
MissingPluginException(No implementation found for method getOrientation on channel com.github.rmtmckenzie/flutter_native_device_orientation/orientation)

How do I fix this?

[iOS] NativeDeviceOrientation.landscapeRight is DeviceOrientation.landscapeLeft and vice versa

If I get the current orientation with await NativeDeviceOrientationCommunicator().orientation() and then I lock this orientation with SystemChrome.setPreferredOrientations(<DeviceOrientation>[orientation]) the screen reverses itself. If current orientation was landscapeRight, it becomes landscapeLeft and vice versa. This would mean to me that the plugin wrongly reports the landscape orientations (left vs right). I've tested on iPhone and iPad Mini to confirm this. Not sure if it behaves the same for all iOS devices.

On my Android devices, it behaves as expected.

Support for detecting portrait lock orientation

Love the package! We've used it to develop a video player and it works like a charm! I think the only thing this package lacks is the ability to detect if the user has portrait orientation lock on or off. This would really complete the package and allow us to show content to users in a much more attractive way, while also respecting their preferences. Users of this package could implement beautiful custom rotation animations to individual widgets, instead of the glitchy-looking default rotation behavior when using systemChrome.

Null safety

Could be nice to create null safety version

Null check operator used on a null value. Error thrown null.

Hello!

In some cases the factory crash with null:

factory NativeDeviceOrientationCommunicator() {
    if (_instance == null) {
      const methodChannel = MethodChannel('com.github.rmtmckenzie/flutter_native_device_orientation/orientation');
      const eventChannel = EventChannel('com.github.rmtmckenzie/flutter_native_device_orientation/orientationevent');
      _instance = NativeDeviceOrientationCommunicator.private(methodChannel, eventChannel);
    }

    return _instance;
  }

or maybe here:

    if (_stream == null || _stream!.useSensor != useSensor) {
      final params = <String, dynamic>{
        'useSensor': useSensor,
      };
      _stream = _OrientationStream(
        stream: _eventChannel.receiveBroadcastStream(params).map((dynamic event) {
          return _fromString(event);
        }),
        useSensor: useSensor,
      );
    }
    return _stream!.stream
        .map((orientation) => (orientation == NativeDeviceOrientation.unknown) ? defaultOrientation : orientation);

Version: 1.1.4
Flutter: 3.0.5
Both Android and Ios

Does not work in web

If unsupported it could return a sane default like portraitUp so that it does not break the whole project. Please can this be done?

Error: Getter not found: 'detached'.

When using your plugin following error is thrown at compile time:
native_device_orientation-0.3.0/lib/native_device_orientation.dart:149:30: Error: Getter not found: 'detached'. case AppLifecycleState.detached:
It would be really nice, if you could look into that 🙂

When orientation changes iOS reports previous orientation instead of current orientation

I believe this is because OrientationListener uses statusBarOrientation, but adds an observer for UIDeviceOrientationDidChangeNotification instead of UIApplicationDidChangeStatusBarOrientationNotification.

It looks like on iOS device orientation changes before the status bar orientation, so when getDeviceOrientation gets the statusBarOrientation it hasn't changed yet and retrieves the previous orientation.

Property to control the sensibility of the sensors

Hi,

when using the NativeOrientationBuilder with useSensor = true, the system already reacts to very fine
movements. Minimal movements quickly change the orientation, which can lead to a choppy UI (see video in the appendix --> look at the icons in the appbar and the preview image at the bottom):

example.mov

Would it be possible to add another property here to control how fine the sensors react?

[Flutter3.0.1][iOS] GestureDetector taps are not detected when screen refreshes are performed in a short period of time.

GestureDetector taps are not detected when screen refreshes are performed in a short period of time.

I'd like to refresh screen each 100ms.
but, using 'NativeDeviceOrientationReader' does not.

blow is the sample code.
If use 'OrientationBuilder' instead, it works.

help me.

sample code:

import 'dart:async';

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

class TestPage extends StatelessWidget {
  const TestPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            child: MultiProvider(
                providers: [
          ChangeNotifierProvider(
            create: (context) => TestCN(),
          )
        ],
                child: Consumer<TestCN>(
                    // builder: (_, cn, __) => OrientationBuilder(
                    //       builder:
                    builder: (_, cn, __) => NativeDeviceOrientationReader(
                        builder: (context) =>
                            NativeDeviceOrientationReader.orientation(context)
                                .let(
                              (orientation) =>
                                  Column(
                                    children: [
                                      Text(
                                        cn.count.toString(),
                                        style: const TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      GestureDetector(
                                        onTap: () => print("##### onTap test"),
                                        child: Container(
                                          height: 100,
                                          width: 100,
                                          color: Colors.yellow,
                                        ),
                                      )
                                    ],
                                  ),
                            ))))));
  }
}

class TestCN extends ChangeNotifier {
  int count = 0;

  Timer? _timer;

  FitnessIntervalVideoPlayerController? _controller;

  TestCN() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);

    _timer = Timer.periodic(const Duration(milliseconds: 100), (_) {
      count++;
      notifyListeners();
    });
  }

  @override
  void dispose() async {
    await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    _timer?.cancel();
    super.dispose();
  }
}

extension ScopeExtension<T> on T {
  R let<R>(R Function(T it) operation) => operation(this);
}

Landscape left not working as expected

I'm trying to build an app which is landscape only oriented, and a weird issue appeared.
When in LandscapeLeft the orientation built is sometimes LandscapeLeft, sometimes PortraitUp;
Device: iPhone 12 mini.

Sample code:

return NativeDeviceOrientationReader(
        useSensor: true,
        builder: (context) {
          final orientation =
              NativeDeviceOrientationReader.orientation(context);
          print(orientation);
          return SomeWidget();
});

Output:
flutter: NativeDeviceOrientation.landscapeLeft
flutter: NativeDeviceOrientation.portraitUp

Only works when Autorotate is enabled (Android)

I know, when autorotate is disabled I should not rotate.

But there is one use case where this is still valid: Displaying a fullscreen (video). In fact this is also what the official youtube app does (and some others as well)

"Attempt to invoke virtual method" occurs on NativeDeviceOrientationCommunicator.resume

When I call NativeDeviceOrientationCommunicator().resume(), the following error occurs.

I tested on
Platform: Android 12
Plugin version: 1.1.4

PlatformException (PlatformException(error, Attempt to invoke virtual method 'java.lang.String com.github.rmtmckenzie.native_device_orientation.NativeOrientation.name()' on a null object reference, null, java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.github.rmtmckenzie.native_device_orientation.NativeOrientation.name()' on a null object reference
	at com.github.rmtmckenzie.native_device_orientation.NativeDeviceOrientationPlugin$StreamHandler$1.receive(NativeDeviceOrientationPlugin.java:115)
	at com.github.rmtmckenzie.native_device_orientation.SensorOrientationListener.startOrientationListener(SensorOrientationListener.java:45)
	at com.github.rmtmckenzie.native_device_orientation.NativeDeviceOrientationPlugin$MethodCallHandler.onMethodCall(NativeDeviceOrientationPlugin.java:86)
	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
	at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
	at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.java:319)
	at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$TsixYUB5E6FpKhMtCSQVHKE89gQ.run(Unknown Source:12)
	at android.os.Handler.handleCallback(Handler.java:938)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loopOnce(Looper.java:226)
	at android.os.Looper.loop(Looper.java:313)
	at android.app.ActivityThread.main(ActivityThread.java:8669)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
))

NativeDeviceOrientationCommunicator().orientation(useSensor: true) receive NULL

When i updated to flutter 3 and use latest package version, function (useSensor: true) not already work!

i call this :

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

I receive this :

E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): Failed to handle method call
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.rmtmckenzie.native_device_orientation.SensorOrientationReader.getOrientation(com.github.rmtmckenzie.native_device_orientation.IOrientationListener$OrientationCallback)' on a null object reference
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at com.github.rmtmckenzie.native_device_orientation.NativeDeviceOrientationPlugin$MethodCallHandler.onMethodCall(NativeDeviceOrientationPlugin.java:63)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.java:319)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$AIEPqY6mWzaNK15HekX9bftoAXs.run(Unknown Source:12)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at android.os.Handler.handleCallback(Handler.java:873)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at android.os.Handler.dispatchMessage(Handler.java:99)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at android.os.Looper.loop(Looper.java:214)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at android.app.ActivityThread.main(ActivityThread.java:7073)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
E/MethodChannel#com.github.rmtmckenzie/flutter_native_device_orientation/orientation(18329): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
D/permissions_handler(18329): No permissions found in manifest for: []3
E/PLogger (18329): {PlatformException(error, Attempt to invoke virtual method 'void com.github.rmtmckenzie.native_device_orientation.SensorOrientationReader.getOrientation(com.github.rmtmckenzie.native_device_orientation.IOrientationListener$OrientationCallback)' on a null object reference, null, java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.rmtmckenzie.native_device_orientation.SensorOrientationReader.getOrientation(com.github.rmtmckenzie.native_device_orientation.IOrientationListener$OrientationCallback)' on a null object reference
E/PLogger (18329): 	at com.github.rmtmckenzie.native_device_orientation.NativeDeviceOrientationPlugin$MethodCallHandler.onMethodCall(NativeDeviceOrientationPlugin.java:63)
E/PLogger (18329): 	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
E/PLogger (18329): 	at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/PLogger (18329): 	at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.java:319)
E/PLogger (18329): 	at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$AIEPqY6mWzaNK15HekX9bftoAXs.run(Unknown Source:12)
E/PLogger (18329): 	at android.os.Handler.handleCallback(Handler.java:873)
E/PLogger (18329): 	at android.os.Handler.dispatchMessage(Handler.java:99)
E/PLogger (18329): 	at android.os.Looper.loop(Looper.java:214)
E/PLogger (18329): 	at android.app.ActivityThread.main(ActivityThread.java:7073)
E/PLogger (18329): 	at java.lang.reflect.Method.invoke(Native Method)
E/PLogger (18329): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
E/PLogger (18329): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

Flutter version :

Flutter 3.0.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision ee4e09cce0 (13 days ago) • 2022-05-09 16:45:18 -0700
Engine • revision d1b9a6938a
Tools • Dart 2.17.0 • DevTools 2.12.2

And package version : 1.1.2

Thank you!!

[RFC] Support for desktop applications?

Would there be interest in adding support for desktop platforms? A few convertible laptops would be able to provide native data, and we can fall back to the Flutter default as we normally do anyway for the ones that can't. This would allow use of the widgets without needing a platform check, first.

New API for the angle of rotation of the device

Hello! Thanks for plugin.
Can you please add the ability to get the angle of rotation of the device? This would be very useful for custom orientation logic.

API can be something like that:

// angle in radian
Stream<double> onRotationAngleChanged() {
}

The screen propreties

hey! How are you ? I'm writting because I have a problem with your plugin.
The rotate is okay well almost, except that the method was called on null and receiver inull of course and I can't posissioned the widget because they are overflow. May be I need change one parameter but I dont know...

`import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:native_device_orientation/native_device_orientation.dart';

class Camera extends StatefulWidget {
final List cameras;
Camera({Key key, this.cameras}) : super(key: key);

@OverRide
_CameraState createState() => _CameraState();
}

class _CameraState extends State {
Future _initializeControllerFuture;
CameraController _controller;
Color colorbuttom = Colors.white54;

Future initCamera(CameraDescription camera) async {
_controller = CameraController(camera, ResolutionPreset.veryHigh);

_controller.addListener(() {
  if (mounted) {
    setState(() {});
  }
});
if (_controller.value.hasError) {
  print("camera error ${_controller.value.errorDescription}");
}

_initializeControllerFuture = _controller.initialize();

if (mounted) {
  setState(() {});
}

}

Future _cameraToggle() async {
await initCamera(widget.cameras[0]);
}

@OverRide
void initState() {
super.initState();

_cameraToggle();

}

@OverRide
void dispose() {
_controller.dispose();
super.dispose();
}

@OverRide
Widget build(BuildContext context) {
double screenwidth = MediaQuery.of(context).size.width;
double screenheight = MediaQuery.of(context).size.height;

return Scaffold(
  body: NativeDeviceOrientationReader(
    builder: (context) {
      final orientation =
          NativeDeviceOrientationReader.orientation(context);
      int turns;

      switch (orientation) {
        case NativeDeviceOrientation.landscapeLeft:
          turns = -1;

          break;
        case NativeDeviceOrientation.landscapeRight:
          turns = 1;
          break;
        case NativeDeviceOrientation.portraitDown:
          turns = 2;

          break;
        default:
          NativeDeviceOrientation.unknown;
          turns = 0;
      }

      return RotatedBox(
        quarterTurns: turns,
        child: Transform.scale(
          scale: 1 / _controller.value.aspectRatio,
          child: Center(
            child: AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: FutureBuilder(
                future: _initializeControllerFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    return Center(
                      child: CameraPreview(
                        _controller,
                      ),
                    );
                  }
                  return Center(
                    child: Text("loading"),
                  );
                },
              ),
            ),
          ),
        ),
      );
    },
  ),
);

}
}
`
[Error - 20:31:54] Request textDocument/codeAction failed.
Message: An error occurred while handling textDocument/codeAction request
Code: -32001
[Error - 20:31:54] An error occurred while handling textDocument/codeAction request: NoSuchMethodError: The method 'packagesAvailableTo' was called on null.
Receiver: null
Tried calling: packagesAvailableTo("c:\src\flutter\.pub-cache\hosted\pub.dartlang.org\native_device_orientation-0.4.3\lib\native_device_orientation.dart")
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 TransformSetManager.forLibrary (package:analysis_server/src/services/correction/fix/data_driven/transform_set_manager.dart:28:30)
#2 DataDriven._availableTransformSetsForLibrary (package:analysis_server/src/services/correction/dart/data_driven.dart:71:41)
#3 DataDriven.producers. (package:analysis_server/src/services/correction/dart/data_driven.dart:31:21)
#4 _SyncIterator.moveNext (dart:core-patch/core_patch.dart:165:25)
#5 FixProcessor._addFromProducers (package:analysis_server/src/services/correction/fix_internal.dart:1137:46)

#6 FixProcessor.compute (package:analysis_server/src/services/correction/fix_internal.dart:1071:11)
#7 DartFixContributor.computeFixes (package:analysis_server/src/services/correction/fix_internal.dart:174:35)
#8 CodeActionHandler._getFixActions (package:analysis_server/src/lsp/handlers/handler_code_actions.dart:244:46)
#9 CodeActionHandler._getCodeActions (package:analysis_server/src/lsp/handlers/handler_code_actions.dart:205:7)
#10 CodeActionHandler.handle... (package:analysis_server/src/lsp/handlers/handler_code_actions.dart:73:18)
#11 ErrorOr.mapResult (package:analysis_server/lsp_protocol/protocol_special.dart:255:12)
#12 CodeActionHandler.handle.. (package:analysis_server/src/lsp/handlers/handler_code_actions.dart:70:26)
#13 ErrorOr.mapResult (package:analysis_server/lsp_protocol/protocol_special.dart:255:12)
#14 CodeActionHandler.handle. (package:analysis_server/src/lsp/handlers/handler_code_actions.dart:69:26)
#15 ErrorOr.mapResult (package:analysis_server/lsp_protocol/protocol_special.dart:255:12)
#16 CodeActionHandler.handle (package:analysis_server/src/lsp/handlers/handler_code_actions.dart:66:17)
#17 _rootRunUnary (dart:async/zone.dart:1198:47)
#18 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
#19 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
#20 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
#21 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
#22 Future._completeWithValue (dart:async/future_impl.dart:529:5)
#23 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:40:15)
#24 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:311:13)
#25 Handler.requireResolvedUnit (package:analysis_server/src/lsp/handlers/handlers.dart)
#26 _rootRunUnary (dart:async/zone.dart:1198:47)
#27 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
#28 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
#29 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
#30 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
#31 Future._completeWithValue (dart:async/future_impl.dart:529:5)
#32 Future._asyncCompleteWithValue. (dart:async/future_impl.dart:567:7)
#33 _rootRun (dart:async/zone.dart:1190:13)
#34 _CustomZone.run (dart:async/zone.dart:1093:19)
#35 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
#36 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:1037:23)
#37 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#38 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#39 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:118:13)
#40 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:169:5)

If you can help me...😉 thanks a lot and good happy hollidays 🎂

Does not work if using SystemChrome.setPreferredOrientations

We're limit the preferred orientations to just landscapes. However, we'd like to show a camera preview and order to be able to rotate it properly we'd need to know if the device is in landscape right or left mode. This plugin would solve the problem, but it doesn't work if we enforce landscape modes using

SystemChrome.setPreferredOrientations([
  DeviceOrientation.landscapeRight,
  DeviceOrientation.landscapeLeft,
])

This is happening at least with:

flutter --version                                                                                                                                                                   Flutter 1.12.13+hotfix.8 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 0b8abb4724 (6 weeks ago) • 2020-02-11 11:44:36 -0800
Engine • revision e1e6ced81d
Tools • Dart 2.7.0

Here's a minima repro with freshly created flutter project
https://github.com/timolehto/flutter_native_orientation_with_preferred_orientations

crash on ios version 2.0.2

Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: SIGNAL 6 Abort trap: 6
Terminating Process: Runner [5133]

Triggered by Thread: 0

Last Exception Backtrace:
0 CoreFoundation 0x1d513140c __exceptionPreprocess + 160 (NSException.m:202)
1 libobjc.A.dylib 0x1ce40dc28 objc_exception_throw + 56 (objc-exception.mm:356)
2 Foundation 0x1cf9149d4 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 168 (NSException.m:251)
3 Flutter 0x102f8e634 0x1029a8000 + 6186548
4 Flutter 0x102f8e190 0x1029a8000 + 6185360
5 Flutter 0x102f8f3c0 0x1029a8000 + 6190016
6 Flutter 0x102f89d04 0x1029a8000 + 6167812
7 native_device_orientation 0x101f7dcb0 thunk for @escaping @callee_unowned @convention(block) (@unowned Swift.AnyObject?) -> () + 160 (:0)
8 native_device_orientation 0x101f7dcb0 specialized NativeDeviceOrientationPlugin.handle(:result:) + 892 (NativeDeviceOrientationPlugin.swift:35)
9 native_device_orientation 0x101f7ccf8 specialized NativeDeviceOrientationPlugin.handle(
:result:) + 16 (:0)
10 native_device_orientation 0x101f7ccf8 @objc NativeDeviceOrientationPlugin.handle(_:result:) + 84
11 Flutter 0x102f89a38 0x1029a8000 + 6167096
12 Flutter 0x1029ebc00 0x1029a8000 + 277504
13 libdispatch.dylib 0x1dbed57a8 _dispatch_call_block_and_release + 24 (init.c:1518)
14 libdispatch.dylib 0x1dbed6780 _dispatch_client_callout + 16 (object.m:560)
15 libdispatch.dylib 0x1dbeb7e10 _dispatch_main_queue_drain + 888 (queue.c:7794)
16 libdispatch.dylib 0x1dbeb7a88 _dispatch_main_queue_callback_4CF$VARIANT$armv81 + 36 (queue.c:7954)
17 CoreFoundation 0x1d51b99ac CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 12 (CFRunLoop.c:1780)
18 CoreFoundation 0x1d519d648 __CFRunLoopRun + 2080 (CFRunLoop.c:3147)
19 CoreFoundation 0x1d51a1d20 CFRunLoopRunSpecific + 584 (CFRunLoop.c:3418)
20 GraphicsServices 0x20d26d998 GSEventRunModal + 160 (GSEvent.c:2196)
21 UIKitCore 0x1d743480c -[UIApplication _run] + 868 (UIApplication.m:3782)
22 UIKitCore 0x1d7434484 UIApplicationMain + 312 (UIApplication.m:5372)
23 Runner 0x10097c614 main + 64 (AppDelegate.swift:6)
24 dyld 0x1f2958344 start + 1860 (dyldMain.cpp:1165)

Getter not found: 'detached'

when I run the project complier throw this error . any help is appreciated
native_device_orientation.dart:149:30: Error: Getter not found: 'detached'.
case AppLifecycleState.detached:

Clarification on UI orientation versus device orientation

Greetings,

I'm trying to detect the orientation of the device while the UI is locked in portrait mode via SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp,]); If the phone is turned to the landscape left position, I expected this to be reflected by NativeDeviceOrientationReader.orientation, but it instead shows orientation still as portraitUp. When I don't lock the preferred orientation, I get the expected result of landscapeLeft. I'm assuming this means that the plugin is determining the UI orientation rather than the physical orientation of the device. Is this the expected behavior? If so, maybe it would be worth clarifying this is the documentation. Also if so, would like to know if you have any plans to support actual device orientation when the UI is locked in a specific orientation, or if you would accept a PR that does support it.

If this isn't the expected behavior, then maybe I'm doing something wrong, or maybe something got broken.

Thanks in advance!

Landscape Left/Right are Reversed

The landscape left and landscape right orientations reported by this plugin are reversed when compared to Apple's definition. This wouldn't be a big deal except I'm trying to use this plugin with another plug that has them correct and it is causing a conflict. See images below. I'm happy to try to do a PR if you don't have the time to resolve. Thanks!

auto_orientation

iphone_orientations

Unexpected ; inside the java code

A line should be remove it doesn't make sense

 @Override
    public void startOrientationListener() {
        if (orientationEventListener != null) {
            callback.receive(lastOrientation);
            return;
        }

        new OrientationEventListener() //this line should be remove it doesn't make sense
        orientationEventListener = new OrientationEventListener(context, rate.nativeValue) {
            @Override
            public void onOrientationChanged(int angle) {
                NativeOrientation newOrientation = calculateSensorOrientation(angle);

                if (!newOrientation.equals(lastOrientation)) {
                    lastOrientation = newOrientation;
                    callback.receive(newOrientation);
                }
            }
        };
        if (orientationEventListener.canDetectOrientation()) {
            orientationEventListener.enable();
        }
    }

MissingPluginException on iOS simulator

When I call this :
nativeOrientation = (await NativeDeviceOrientationCommunicator().orientation(useSensor: true)).index;

I receive this :

Unhandled Exception: MissingPluginException(No implementation found for method getOrientation on channel com.github.rmtmckenzie/flutter_native_device_orientation/orientation)
#0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:175:7)
<asynchronous suspension>
#1      NativeDeviceOrientationCommunicator.orientation (package:native_device_orientation/native_device_orientation.dart:42:25)
<asynchronous suspension>

Response landscapeRight when the device is landscapeLeft

When I have a device on landscape left and I run the NativeDeviceOrientationReader twice, beacause I have two pages where I evaluate the orientation, the second page recive landscapeRight from the plugin always.

When I debugin the plugin I saw that the second time the If statment on 161 line response true, and get the orientation from OrientationBuilder and recive Orientation.landscape soo the plugin response NativeDeviceOrientation.landscapeRight.

qr_mobile_vision cannot build

Undefined symbols for architecture i386:
  "_FlutterMethodNotImplemented", referenced from:
      -[NativeDeviceOrientationPlugin handleMethodCall:result:] in NativeDeviceOrientationPlugin.o
  "_OBJC_CLASS_$_FlutterEventChannel", referenced from:
      objc-class-ref in NativeDeviceOrientationPlugin.o
  "_OBJC_CLASS_$_FlutterMethodChannel", referenced from:
      objc-class-ref in NativeDeviceOrientationPlugin.o
ld: symbol(s) not found for architecture i386

image

NativeDeviceOrientation 1.1.4 uses unchecked or unsafe operations

When building the apk of my app, this warning appears in the console.

Note: /Users/manudicri/.pub-cache/hosted/pub.dev/native_device_orientation-1.1.4/android/src/main/java/com/github/rmtmckenzie/native_device_orientation/NativeDeviceOrientationPlugin.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

That's basically it.

My flutter doctor -v:

[✓] Flutter (Channel stable, 3.7.7, on macOS 13.4 22F66 darwin-arm64, locale it-IT)
    • Flutter version 3.7.7 on channel stable at /Users/manudicri/Development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 2ad6cd72c0 (6 months ago), 2023-03-08 09:41:59 -0800
    • Engine revision 1837b5be5f
    • Dart version 2.19.4
    • DevTools version 2.20.1

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
    • Android SDK at /Users/manudicri/Library/Android/sdk
    • Platform android-33, build-tools 33.0.1
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14E222b
    • CocoaPods version 1.12.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)

[✓] VS Code (version 1.81.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (3 available)
    • iPhone 14 Pro (mobile) • 688E3477-BEF0-451B-836F-806FC8B9351D • ios            •
      com.apple.CoreSimulator.SimRuntime.iOS-16-4 (simulator)
    • macOS (desktop)        • macos                                • darwin-arm64   • macOS 13.4 22F66 darwin-arm64
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 116.0.5845.179

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.