【问题标题】:How to make landscape to only one screen in Flutter?如何在 Flutter 中将横向设置为只有一个屏幕?
【发布时间】:2021-08-27 12:50:18
【问题描述】:

我的应用程序的主屏幕是横向的,并且有背景音乐。所以在 initstate 中,我将屏幕实现为风景,带有音乐

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

    _assetsAudioPlayer = AssetsAudioPlayer();
    AssetsAudioPlayer.newPlayer().open(
      Audio("assets/audio/bgm.mp3"),
      autoStart: true,
      showNotification: true,
    );
    _assetsAudioPlayer!.playOrPause();
  }

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

所有这些都应该只包含在主屏幕本身中,我不希望它传递到任何其他屏幕。但是音乐和方向被传递到下一个屏幕。我怎样才能将其仅包含在主屏幕上。?

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    你能检查一下 dispose 函数被调用了吗?可能会调用 deactive 函数而不是 dispose。

    如果问题是这样,您可以在停用功能中执行您的逻辑,例如:

      @override
      void deactivate() {
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.landscapeRight,
          DeviceOrientation.landscapeLeft,
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
        ]);
        _assetsAudioPlayer = null;
        super.deactivate();
      }
    

    为什么调用 deactivate 方法而不是 dispose 函数:

    调用 deactivate 但不处理的典型情况是,当 使用 GlobalKey 在小部件树中移动小部件。

    【讨论】:

    • 我试过停用。它仍然显示相同的问题。但是当尝试使用 Navigator.pushReplacementName 时,方向会变回纵向。但是音乐一直在播放而不会失去活力
    • 哦,因为你设置了错误的audioplayer null。在此行之后 _assetsAudioPlayer = AssetsAudioPlayer();您使用 AssetsAudioPlayer 的另一个实例而不是 _assetsAudioPlayer.newPlayer().open 开始播放音乐
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2020-04-02
    • 2019-02-21
    • 2012-11-05
    • 2018-06-03
    相关资源
    最近更新 更多