Flutter: How to set and lock screen orientation on-demand

后端 未结 6 1383
南方客
南方客 2020-11-28 22:45

On one of my flutter pages, I need the screen to set to landscape mode and lock it so it can\'t rotate into portrait mode, but only on the one page. So need a way to enable

6条回答
  •  -上瘾入骨i
    2020-11-28 23:16

    First import the services package:

    import 'package:flutter/services.dart';

    This will give you access to the SystemChrome class, which "Controls specific aspects of the operating system's graphical interface and how it interacts with the application."

    When you load the Widget, do something like this:

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

    then when I leave the page, put it back to normal like this:

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

提交回复
热议问题