Matt Takao
Matt Takao

Reputation: 3006

flutter: identify orientation when the screen is locked

Trying to google this yields thousands of unrelated articles, such as setting or locking a specific orientation.

My question is, while the orientation for the phone is locked in say, portrait mode, but the screen is turned sideways, is there way to detect this shift and adjust widgets on the screen in response?

Something like

if (MediaQuery.of(context).orientation == Orientation.portrait) {
      return Text('text', style: TextStyle(fontSize: 200));
    } else {
      return Text('flipped text', style: TextStyle(fontSize: 200));
    }

does not work. Same thing with OrientationBuilder - these seem to rely on what mode the phone thinks it's in.

I see there is the sensors package and I'm sure I could get it to work eventually, but it kinda feels like killing a mosquito with a bazooka. I'm hoping there's something simple I've missed when trying to google this issue.

Upvotes: 2

Views: 820

Answers (2)

Matt Takao
Matt Takao

Reputation: 3006

Ok so it wasn't that difficult using the sensors package after all. Just had to use the 2nd coordinate of the accelerometer values and compare whether it was greater than ~4 (I assume this is m/s^2, as the resting value was ~9).

So the added code is something like:

class _SampleScreenState extends State<SampleScreen> {
  //...
  List<double> _accelerometerValues;
  List<StreamSubscription<dynamic>> _streamSubscriptions =
      <StreamSubscription<dynamic>>[];

  //...

  void initState() {
    //...

    _streamSubscriptions
        .add(accelerometerEvents.listen((AccelerometerEvent event) {
      setState(() {
        _accelerometerValues = <double>[event.x, event.y, event.z];
      });
    }));
  }

  //...

  sampleWidget() {
    if (_accelerometerValues[1] > 4) {
      return Text('portrait');
    } else {
      return Text('landscape');
    }
  }

  //...

I will probably add some hysteresis to this to make it cleaner, but it's a working solution.

Upvotes: 6

Jordan Kotiadis
Jordan Kotiadis

Reputation: 566

Add this line to set your screen to landcape SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]); in initState or SystemChrome.setPreferredOrientations([DeviceOrientation.portaitUp]); for the portrait mode.

Note: It might not work for iOS deviuce if youy don't add in the Info.plist these lines

<array>
<string>UIInterfaceOrientationPortrait</string>
</array>

Upvotes: 0

Related Questions