【问题标题】:Programmatically change orientation以编程方式改变方向
【发布时间】:2020-12-21 06:39:21
【问题描述】:

Flutter 有一个名为 setPreferredOrientations() 的内置方法。据我了解,此函数锁定了参数中设置的方向。相反,我只想更改方向,但不锁定它。我的用例如下:

  • 用户可以在全屏模式下查看图像
  • 许多用户在系统设置中关闭设备轮换
  • 为了避免必须启用和禁用设备旋转以将图像旋转到横向,我想要一个“旋转”按钮来为用户旋转布局(并允许他们将其旋转回来),而不是而不是需要物理旋转他们的设备。

对此有什么想法吗?谢谢!

【问题讨论】:

    标签: flutter


    【解决方案1】:

    我认为 Apurv Jha 的回答应该有效。我也认为它是从这里偷来的:Flutter: How to set and lock screen orientation on-demand。

    您是否尝试过:您可能想在不同的地方使用来自initState 的代码。例如,在小部件的onPressed 或onTap 参数中。然后创建一个状态,指示设备是否旋转。它可能是一个简单的布尔值或某种方式来在按下按钮时让设备旋转。然后根据状态将方向设置为不同于状态的方向并更新状态。

    【讨论】:

    • 方向被锁定的原因是它在initState 上运行。如果您不在那里运行它,方向将照常遵循用户的设置。但是请确保整个事情都包装在具有正确范围的 StatefulWidget 中。您可能只想在 StatefulWidget 中包含图像查看器。
    • 啊有趣,不知道这会影响事情。我试试看,谢谢!
    【解决方案2】:

    首先导入服务包:

    导入package:flutter/services.dart;

    这将使您可以访问SystemChrome 类,"Controls specific aspects of the operating system's graphical interface and how it interacts with the application."

    当您加载 Widget 时,请执行以下操作:

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

    然后当我离开页面时,像这样恢复正常:

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

    【讨论】:

    • 这不是我想要的,它在进入时将方向锁定为横向。我希望它以纵向(或横向,取决于用户的默认旋转)开始,并在需要时选择旋转,但不锁定方向。
    【解决方案3】:

    您可以使用 bool 变量标志,而不是更改 dispose 方法中的 setPreferredOrientations() 参数。

    每当用户单击旋转按钮时,检查变量是否默认值为 true,然后将变量设置为 false,并将方向设置为横向,如果其值不等于默认值,则将方向更改为纵向。

    if(flag == true)
        SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
    else
        SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeRight,
        DeviceOrientation.landscapeLeft,
      ]);
    

    并在 dispose 方法中将参数设置为默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多