In this example, we are going to show you the best way to set Orientation mode in Flutter App. There are two orientations, i.e Landscape mode and Portrait mode. See the example below and learn how to set Orientation or switch Landscape mode to Portrait mode or vice versa.
import 'package:flutter/services.dart';
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitDown,
DeviceOrientation.portraitUp,
]);
//in Statefull Screen
@override
void initState() {
//set initial orentation to langscape
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
super.initState();
}
//----- OR --- in stateless screen
@override
Widget build(BuildContext context) {
//set initial orentation to langscape
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
return Scaffold();
}
To Change Orientation after Widget Build, use OrientationBuilder()
widget like below:
OrientationBuilder(
builder: (context, orientation) {
return Container(
child: Center(
child: ElevatedButton(
child: Text("Switch Orentation"),
onPressed: (){
if(MediaQuery.of(context).orientation == Orientation.portrait){
//if Orientation is portrait then set to landscape mode
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}else{
//if Orientation is landscape then set to portrait
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitDown,
DeviceOrientation.portraitUp,
]);
}
},
)
),
)
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget{
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
//set initial Orientation to landscape
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Test App",
home: Scaffold(
appBar: AppBar(title:Text("Switch Orientation Mode")),
body: OrientationBuilder(
builder: (context, orientation) {
return Container(
child: Center(
child: ElevatedButton(
child: Text("Switch Orientation"),
onPressed: (){
if(MediaQuery.of(context).orientation == Orientation.portrait){
//if Orientation is portrait then set to landscape mode
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}else{
//if Orientation is landscape then set to portrait
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitDown,
DeviceOrientation.portraitUp,
]);
}
},
)
),
);
}),
)
);
}
}
In this way, you can set Landscape or Portrait Orientation mode in Flutter App.
Please Wait...
No any Comments on this Article