Skip to content

[Flutter] Decide Whether The Screen Maintains A Vertical Or Horizontal

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:

https://clay-atlas.com/wp-content/uploads/2021/03/Screen-Recording-2021-03-27-at-2.27.14-PM.mov


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


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version