Flutter:如何设置屏幕旋转监听器

时间:2019-08-10 09:10:04

标签: flutter dart

有没有办法监听屏幕方向-屏幕旋转的时间,而不是屏幕完全旋转的时间(在这种情况下,OrientationBuilder会完成工作)。


代码

class _MyPageState extends State<MyPage> {
  static Widget _portrait = Column(
    children: <Widget>[
      Container(height: 240, color: Colors.blue),
      Container(height: 240, color: Colors.red),
    ],
  );

  Widget _landscape = Center(child: FlutterLogo(size: 200));
  Widget _child = _portrait;

  Widget build(BuildContext context) {
    return Scaffold(
      body: OrientationBuilder(builder: (_, orientation) {
        if (orientation == Orientation.portrait)
          _child = _portrait;
        else
          _child = _landscape;

        return AnimatedSwitcher(
          duration: Duration(seconds: 2),
          child: _child,
        );
      }),
    );
  }
}

输出:

enter image description here


问题

如您所见,当屏幕从纵向旋转到横向时,出现溢出错误,这是由于AnimatedSwitcher引起的,如果我在seconds: 0中使用duration,则不会出现错误。有什么方法可以监听屏幕旋转变化,以便可以将seconds设置为0?或任何其他允许我使用AnimatedSwitcher而不会引起溢出问题的解决方案。


注意:

我不是在寻找解决方法,例如,使用Wrap而不是Column,使用AnimatedSwitcher等的需求是什么。我正在开发的应用要求它保持原样是的,我只是创建了一个易于复制的repo以反映我的代码。谢谢

1 个答案:

答案 0 :(得分:0)

将正文内容包装到SingleChildScrollView

class _MyPageState extends State<MyPage> {
  static Widget _portrait = Column(
    children: <Widget>[
      Container(height: 240, color: Colors.blue),
      Container(height: 240, color: Colors.red),
    ],
  );

  Widget _landscape = Center(child: FlutterLogo(size: 200));
  Widget _child = _portrait;

  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView (
        child: OrientationBuilder(builder: (_, orientation) {
          if (orientation == Orientation.portrait)
            _child = _portrait;
          else
            _child = _landscape;

          return AnimatedSwitcher(
            duration: Duration(seconds: 2),
            child: _child,
          );
        }),
      ),
    );
  }
}