How to detect orientation change in layout in Flutter?
How to find out Orientation is portrait or landscape in Flutter
if(portrait){
return ListView.builder()
}else{
return GridView.count()
}
Solution 1:
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.
new OrientationBuilder(
builder: (context, orientation) {
return new GridView.count(
// Create a grid with 2 columns in portrait mode, or 3 columns in
// landscape mode.
crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
);
},
);
you can find the complete example here: https://flutter.io/cookbook/design/orientation/
Solution 2:
You can use MediaQuery
to check orientation:
var isPortrait = MediaQuery.of(context).orientation == Orientation.portrait
Solution 3:
it's quite easy
if (MediaQuery.of(context).orientation == Orientation.portrait){
// is portrait
}else{
// is landscape
}
Solution 4:
@override
Widget build(BuildContext context) {
return Scaffold(
body: OrientationBuilder(builder: (_, orientation) {
if (orientation == Orientation.portrait)
return _buildPortraitLayout(); // if orientation is portrait, show your portrait layout
else
return _buildLandscapeLayout(); // else show the landscape one
}),
);
}
Solution 5:
OrientationBuilder(
builder: (context, orientation) {
return orientation == Orientation.portrait
? SafeArea(
child: Scaffold(
body: PortraitMode(context)
)
)
: LandscapeMode(context);
}
);