Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listening For Device Orientation Changes In Flutter

Tags:

flutter

I am looking for a way of listening for changes to the phones orientation, with the intent to hide something if the phone is Landscape.

My Layout is currently only displayed in portrait, as intended, but I want my app to do something if the device is rotated to Landscape, while keeping the layout in Portrait.

I have tried using a OrientationBuilder, but this only works if the layout changes to Landscape.

I have also tried using MediaQuery.of(context).orientation, but it continues to return portrait once the device is rotated, again only using the layouts orientation.

like image 673
Matthew Weilding Avatar asked Mar 04 '19 15:03

Matthew Weilding


People also ask

How do you handle orientation changes in flutter?

This widget is already a part of the MaterialApp and WidgetsApp widget so you probably don't need to include it. If you want your widget to take advantage of the device orientation, you can use the MediaQuery. of static member to access a MediaQueryData , which contains the device orientation.

How do I find the device orientation in flutter?

In order to determine the Orientation of the screen, we can use the OrientationBuilder Widget. The OrientationBuilder will determine the current Orientation and rebuild when the Orientation changes.


1 Answers

You can listen to screen size changes, but MediaQuery.of(...) should work as well and should cause rebuilds of your widget when orientation changes

https://stephenmann.io/post/listening-to-device-rotations-in-flutter/

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

class WidthHeight extends StatefulWidget {
  WidthHeight({ Key key }) : super(key: key);

  @override
  WidthHeightState createState() => new WidthHeightState();
}

class WidthHeightState extends State
                       with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  double width = 0.0;
  double height = 0.0;

  @override void didChangeMetrics() {
    setState(() {
      width = window.physicalSize.width;
      height = window.physicalSize.height;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Text('Width: $width, Height $height');
  }
}
like image 191
Günter Zöchbauer Avatar answered Sep 23 '22 18:09

Günter Zöchbauer