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