Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 497
Gautham Avatar asked Apr 05 '18 03:04

Gautham


2 Answers

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!');
  }
}
like image 158
Jonah Williams Avatar answered Oct 03 '22 14:10

Jonah Williams


This will help you to force the Flutter application to remain in Portrait (vertical) mode even if the user is rotating the SmartPhone

    void main(){
  ///
  /// Force the layout to Portrait mode
  /// 
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);

  runApp(new MyApp());
}
like image 31
Raj008 Avatar answered Oct 03 '22 16:10

Raj008