Simple Realization Method of Flutter Prohibiting Horizontal Screen of Mobile Phone

  • 2021-12-13 09:38:02
  • OfStack

In some specific App, we don't want App to rotate when the mobile phone is horizontally screened, such as WeChat and enterprise WeChat.

The code can be set as follows:


import 'package:flutter/services.dart';
void main() async => {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations(
    [
      DeviceOrientation.portraitUp,   //  Vertical screen  Portrait  Mode 
      DeviceOrientation.portraitDown, 
      // DeviceOrientation.landscapeLeft, //  Horizontal screen  Landscape  Mode 
      // DeviceOrientation.landscapeRight,
    ],
  );
  runApp(MainApp());
};

In the main function, set it as above, and you can disable the horizontal screen mode globally.

However, in the enterprise WeChat, I found that the horizontal screen mode is not completely disabled. If I open a webpage inside the enterprise WeChat, I can use it horizontally in this scenario. That is, in the scene of WebView, I can cross the screen, but I can't cross the screen under other interfaces. How do you set this up?


  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }
  @override
  void dispose() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    super.dispose();
  }

Like this, set it to initState and dispose of one StatefulWidget. For example, in my code, I specially encapsulated WebView with a page called WebPage. After this setting, when the user enters the webpage, he can horizontally screen, but after returning, he will forcibly restore the vertical screen.

Reference: http://kmanong.top/kmn/qxw/form/article? id=2735 & cate=93

Reference: https://stackoverflow.com/questions/49418332/flutter-how-to-prevent-device-orientation-changes-and-and-force-portrait

Summarize


Related articles: