如何仅针对 Flutter 中的某些类防止设备旋转?

Ale*_*eFe 3 orientation screen-orientation dart flutter flutter-layout

我正在开发一个 Flutter 应用程序,我只需要在某些类中防止设备旋转,同时在其他类中保持它的工作。我现在如何在应用程序中全局禁用旋转,但如何仅在某些类中禁用它?

Gui*_*oux 5

你可以尝试在你的小部件中使用这样的东西:

// to lock in landscape view
@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();
}
Run Code Online (Sandbox Code Playgroud)

使用initState()and的事实dispose()意味着您必须使用 aStatefulWidget如果已经不是这种情况。