返回

Flutter布局详解:构建灵活界面的艺术

IOS

前言

对于约束布局深入探索,可以从布局原理 -> 布局约束 -> 打破布局去探索。

布局原理

感兴趣可以看这篇 传送门

StatelessWidget 和 StatefulWidget 是 组合类 的。

  1. StatelessWidget:不变的部件,没有状态。

  2. StatefulWidget:带有状态的部件。

布局约束

  1. LayoutBuilder:构建时可以访问其父 Widget 的约束。
  LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints) {
      // 访问父部件的约束
      return Container(
        width: constraints.maxWidth,
        height: constraints.maxHeight,
      );
    },
  ),
  1. ConstrainedBox:控制其子部件大小。
  ConstrainedBox(
    constraints: BoxConstraints(
      maxWidth: 100.0,
      maxHeight: 100.0,
    ),
    child: Container(
      width: double.infinity,
      height: double.infinity,
    ),
  ),
  1. Align:对齐子部件。
  Align(
    alignment: Alignment.center,
    child: Container(
      width: 100.0,
      height: 100.0,
    ),
  ),

打破布局

  1. Stack:堆叠部件。
  Stack(
    children: [
      Container(
        width: 100.0,
        height: 100.0,
        color: Colors.red,
      ),
      Container(
        width: 50.0,
        height: 50.0,
        color: Colors.green,
      ),
    ],
  ),
  1. Positioned:定位部件。
  Positioned(
    top: 10.0,
    left: 10.0,
    child: Container(
      width: 100.0,
      height: 100.0,
      color: Colors.red,
    ),
  ),
  1. Transform:变换部件。
  Transform.rotate(
    angle: 45.0,
    child: Container(
      width: 100.0,
      height: 100.0,
      color: Colors.red,
    ),
  ),

总结

Flutter 的布局系统非常灵活,提供了多种方式来构建复杂的界面。通过了解布局原理、约束布局和打破布局,可以掌握构建灵活界面的艺术。