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.
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.
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.
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'); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With