flutterdartorientation

How does Flutter handle orientation change


Is orientation change handling is as simple as widget's build is rerun with the updated dimensions in Flutter?

I ask because in Android, the whole Activity is rebuilt, which is why all the information is sent via intents.

Any gotchas to keep in mind while designing widgets so they will handle orientation changes or other changes that result in UI to change?


Solution

  • Basically - yes! Now, more specifically the MediaQuery widget listens for orientation/size/layout changes and rebuilds it's children. 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. For example, a simple widget which displays different text in portrait and landscape (needs to be the child of MaterialApp, WidgetsApp, or MediaQuery).

    class MyWidget extends StatelessWidget {
      Widget build(BuildContext context) {
        final mediaQueryData = MediaQuery.of(context);
        if (mediaQueryData.orientation == Orientation.landscape) {
          return const Text('landscape');
        }
        return const Text('portrait!');
      }
    }