Listening to Device Rotations in Flutter

Apr 9, 2018 11:11 · 164 words · 1 minute read Dart Flutter

It took me a while to figure out how to listen for device rotation changes in Flutter, so I thought I’d write a quick post to help out anyone else with the same problem.

Flutter provides a singleton instance of a class called WidgetBinding that allows listening to various widget events. One of those events is “didChangeMetrics,” which gets fired whenever a metric changes. Device width and height are included in those metrics, and those values change when the device rotates.

Example code:

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');
  }
}

Happy coding!

Tweet Share

Looking for graphic design help?

I partner with designers at Handshake Studios to provide graphic design feedback to freelancers and early-stage startups.

Sign up at DesignSavior.com!

Subscribe to my newsletter to receive updates about new posts.

* indicates required