【问题标题】:Flutter responsive design: Dynamically change Column to Row if the screen is largerFlutter 响应式设计:如果屏幕更大,动态将 Column 更改为 Row
【发布时间】:2019-10-05 17:46:21
【问题描述】:

如果设备的屏幕宽度超过某个阈值,如何将 Column 小部件动态更改为 Row 小部件?

当用户在平板电脑或横向模式下使用应用程序时,布局应该不同,以优化可用宽度的使用。

在 CSS flexbox 中,就像将类从 flex-row 更改为 flex-column 一样简单,但在 Flutter 中,使用了小部件。

【问题讨论】:

    标签: flutter responsive-design flutter-layout


    【解决方案1】:

    RowColumn 共享一个名为 Flex 的共同父级,该父级采用轴方向。只需更改direction 的值,您就可以将Flex 更改为一行或一列。

    要获取屏幕宽度,您可以使用MediaQuery.of(context).size.width

    您的小部件应如下所示:

    @override
    Widget build(BuildContext context) {
      bool isScreenWide = MediaQuery.of(context).size.width >= kMinWidthOfLargeScreen;
    
      return Scaffold(
        body: Flex(
          direction: isScreenWide ? Axis.horizontal : Axis.vertical,
          children: <Widget>[
            ...
          ],
        )
      );
    }
    

    【讨论】:

      【解决方案2】:

      要根据设备方向进行更改,您可以:

      Orientation orientation = MediaQuery.of(context).orientation;
      
      return orientation == Orientation.portrait
      ? Column(children: <Widget>[])
      : Row(children: <Widget>[]);
      

      我写了一个助手来做这个(列到行)。

      import 'package:flutter/material.dart';
      
      class OrientationSwitcher extends StatelessWidget {
        final List<Widget> children;
      
        const OrientationSwitcher({Key key, this.children}) : super(key: key);
      
        @override
        Widget build(BuildContext context) {
          Orientation orientation = MediaQuery.of(context).orientation;
          return orientation == Orientation.portrait
          ? Column(children: children)
          : Row(children: children);
        }
      }
      

      然后使用它...

        Widget build(BuildContext context) {
          return OrientationSwitcher(
            children: <Widget>[
                 // place children here like its a column or row.
              ]
          )
        }
      

      您也可以使用 Flex() 或任何其他小部件来执行此操作。

      此外,除了方向之外,还有更多可用选项,请务必查看 Flutter 文档中的 MediaQuery.of(context) 实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-27
        • 2015-05-21
        相关资源
        最近更新 更多