Last Updated on 2021-10-18 by Clay
In the process of developing an App, we may need to maintain the vertical or horizontal screen orientation of user's device to different needs; or, when the App can switch between different functions automatically rotation.
Of course we can implement these operations in Flutter. In below, I will simply record how to manipulate the direction of the screen.
Initial setting & button setting
We can set the fixed screen orientation during the App startup phase, it can also used to set only vertical or horizontal layout.
It's a simple example as follows:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// Main
void main() {
SystemChrome.setPreferredOrientations([
// Orientations
// DeviceOrientation.landscapeLeft,
// DeviceOrientation.landscapeRight,
DeviceOrientation.portraitDown,
DeviceOrientation.portraitUp,
]);
runApp(MyApp());
}
// MyApp
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
// HomePage
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
// _HomePageState
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: 200,
height: 100,
color: Colors.red,
),
RaisedButton(
child: Text("Portrait"),
onPressed: () {
setState(() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
]);
});
})
],
);
}
}
Output:
Change single page
If you just need to set the single page, you can set the initial orientation or change orientation function in the initState()
and dispose()
of the page.
@override
void initState() {
super.initState();
// Init
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
}
@override
void dispose() {
// Change
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
super.dispose();
}
References
- https://mightytechno.com/screen-orientation-in-flutter/
- https://wst24365888.github.io/flutter-orientation/