在Flutter中聆听设备方向的变化

问题描述 投票:2回答:3

我正在寻找一种倾听手机方向变化的方法,如果手机是风景,则意图隐藏某些内容。

我的布局目前仅按照预期以纵向显示,但如果将设备旋转到横向,我希望我的应用程序执行某些操作,同时将布局保留为纵向。

我尝试过使用OrientationBuilder,但只有在布局更改为Landscape时才有效。

我也尝试过使用MediaQuery.of(context).orientation,但是一旦设备旋转它继续返回肖像,再次只使用布局方向。

flutter
3个回答
2
投票

您可以收听屏幕尺寸更改,但MediaQuery.of(...)应该也能正常工作,并且当方向发生变化时应该会导致窗口小部件重建

https://stephenmann.io/post/listening-to-device-rotations-in-flutter/

import 'dart:ui';
import 'package:flutter/material.dart';

class WidthHeight extends StatefulWidget {
  WidthHeight({ Key key }) : super(key: key);

  @override
  WidthHeightState createState() => new WidthHeightState();
}

class WidthHeightState extends State
                       with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  double width = 0.0;
  double height = 0.0;

  @override void didChangeMetrics() {
    setState(() {
      width = window.physicalSize.width;
      height = window.physicalSize.height;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Text('Width: $width, Height $height');
  }
}

0
投票

您可以使用可见性包装窗口小部件并将opacity参数设置为getOpacityForOrientation(),并在屏幕中添加以下功能:

double getOpacityForOrientation() {
    if (MediaQuery.of(context).orientation == Orientation.landscape) {
      return 0;
    } else {
      return 1;
    }
}

当方向改变时,小部件将重建,不透明度将改变并隐藏/显示


0
投票

OrientationBuilderMediaQuery.of(context).orientation都应该能够完成工作。但是你说设备的方向永远不会改变,这让我觉得你没有在你的设备中启用自动旋转。

你能从快速设置中启用自动旋转并尝试一下吗?

© www.soinside.com 2019 - 2024. All rights reserved.