蓝色天空.知识 · 实践 · 创造
我的收藏
Flutter 教程目录 25章
Flutter / LEARN BY DOING

Flutter 布局基础

系统掌握 Flutter 线性布局(Row/Column/Flex)、主轴与交叉轴对齐几何公式、Expanded/Flexible 弹性比例分配、Stack/Positioned 层叠定位、EdgeInsets 边距以及 Scaffold 页面脚手架。

学完这一章,你能够

  • 系统掌握 Flutter 线性布局(Row/Column/Flex)、主轴与交叉轴对齐几何公式、Expanded/Flexible 弹性比例分配、Stack/Positioned 层叠定位、EdgeInsets 边距以及 Scaffold 页面脚手架。

布局组件体系与 Row/Column 线性排布

Flutter 布局遵循“约束向下传递、尺寸向上回报、父级决定位置”的盒模型原则,核心布局组件包括水平排布的 `Row`、垂直排布的 `Column`、二者共同基类 `Flex`、层叠排布的 `Stack`,以及适合滚动集合的 `ListView` 与 `GridView`。

`Row` 沿水平主轴排列子节点,通过 `mainAxisAlignment` 控制主轴剩余空间分配:支持 `start`(默认靠左)、`center`(居中)、`end`(靠右)、`spaceBetween`(两端贴边且中间等距)、`spaceEvenly`(两端与项间完全等距)以及 `spaceAround`(项间间距为两端间距的 2 倍)。本站离线布局几何引擎在 300px 容器中排列三个 40px 图标,精确核对了全部 6 种模式的像素 x 坐标(例如 `spaceEvenly` 为 `[45.0, 130.0, 215.0]`,`spaceAround` 为 `[30.0, 130.0, 230.0]`)。

`Column` 沿垂直主轴排列子节点,其水平方向为交叉轴,可通过 `crossAxisAlignment` 控制子节点在交叉轴上的对齐方式(`start`、`center`、`end` 与强制填满交叉轴宽度的 `stretch`)。本站离线验证了 200px 交叉轴内 40px 子项的 4 种位置与拉伸尺寸。

Expanded/Flexible 弹性分配与 Stack 层叠定位

在 `Row` 或 `Column` 中,当希望某些子项按权重瓜分剩余空间时,可使用 `Expanded`(`FlexFit.tight`,强制填满所分份额)或 `Flexible`(默认 `FlexFit.loose`,允许小于所分份额)。本站离线数学核验确认:400px 宽度的 `Row` 放置 100px 与 50px 固定块后,中间 `Expanded` 精确获得 250px;三个 `Expanded` 按 `flex` 1:2:1 划分时分别获得 `100px`、`200px` 与 `100px`。

`Stack` 将子组件按书写顺序自底向上叠放,常用于图片浮层、角标与遮罩;搭配 `Positioned(left/right/top/bottom)` 可相对 `Stack` 四边精确定位子元素(例如 300×200 容器中距右上各 10px 的 24px 关闭图标坐标为 `(266, 10)`)。

Padding/Margin 边距控制与 Scaffold 页面脚手架

元素内外留白通过 `EdgeInsets` 描述:`EdgeInsets.all(16)` 统一设置四边,`EdgeInsets.only(left, right, top, bottom)` 单独指定各边,`EdgeInsets.symmetric(horizontal, vertical)` 成对设置水平与垂直边距;纯内边距可直接用轻量的 `Padding`,需同时设置外边距、内边距与圆角背景时可结合 `Container`。

`Scaffold` 提供了符合 Material Design 规范的标准页面骨架,内置顶部 `appBar`(支持标题、背景色、阴影与右侧 `actions` 图标按钮)、主体 `body`、悬浮操作按钮 `floatingActionButton` 以及底部导航栏 `bottomNavigationBar` 四大核心插槽。

Flutter 常用布局 Widget 概览

布局 Widget核心用途
Row沿水平方向线性排列多个子 Widget。
Column沿垂直方向线性排列多个子 Widget。
Stack沿 Z 轴层叠排列子 Widget,支持 Positioned 绝对定位。
FlexRow 与 Column 的抽象基类,通过 direction 动态切换横纵轴。
GridView二维规则网格滚动布局。
ListView一维单向可滚动列表布局。

MainAxisAlignment 主轴对齐取值对照

枚举值空间分布规则
MainAxisAlignment.start紧贴主轴起点排列(Row 默认靠左,Column 默认靠上)。
MainAxisAlignment.center整体居中排列,两端留白相等。
MainAxisAlignment.end紧贴主轴终点排列(Row 靠右,Column 靠下)。
MainAxisAlignment.spaceBetween首尾元素贴边,剩余空白均匀分配在相邻子项之间。
MainAxisAlignment.spaceEvenly两端空白与所有相邻子项间距完全相等。
MainAxisAlignment.spaceAround相邻子项间距相等,且为两端边缘空白的 2 倍。

CrossAxisAlignment 交叉轴对齐取值对照

枚举值交叉轴对齐效果
CrossAxisAlignment.start沿交叉轴起点对齐(Row 靠上,Column 靠左)。
CrossAxisAlignment.center沿交叉轴居中对齐(默认行为)。
CrossAxisAlignment.end沿交叉轴终点对齐(Row 靠下,Column 靠右)。
CrossAxisAlignment.stretch强制拉伸子组件以填满父容器交叉轴可用空间。

运行 Row/Column 对齐几何、Expanded 弹性分配、Stack Positioned 与 EdgeInsets 离线核验

含完整源码 · 155 行
展开查看收起
python
"""Offline Flutter BoxConstraints, Row/Column/Flex/Expanded/Stack/Padding/Scaffold verifier for Ch07 (layout)."""
import json

VERSION = "CPython 3.12.14 offline Flutter/Dart architecture & runtime verifier (Flutter SDK absent)"


def check(name, summary, expected, actual):
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def layout_row(container_width, item_widths, alignment):
    total_items = sum(item_widths)
    free = container_width - total_items
    n = len(item_widths)
    positions = []
    if alignment == "start":
        x, gap = 0.0, 0.0
    elif alignment == "center":
        x, gap = free / 2.0, 0.0
    elif alignment == "end":
        x, gap = free, 0.0
    elif alignment == "spaceBetween":
        x, gap = 0.0, (free / (n - 1) if n > 1 else 0.0)
    elif alignment == "spaceEvenly":
        gap = free / (n + 1)
        x = gap
    elif alignment == "spaceAround":
        gap = free / n
        x = gap / 2.0
    else:
        raise ValueError(alignment)
    for w in item_widths:
        positions.append(round(x, 2))
        x += w + gap
    return positions


def layout_cross_axis(container_height, child_height, alignment):
    if alignment == "start":
        return {"y": 0.0, "height": child_height}
    if alignment == "center":
        return {"y": round((container_height - child_height) / 2.0, 2), "height": child_height}
    if alignment == "end":
        return {"y": round(container_height - child_height, 2), "height": child_height}
    if alignment == "stretch":
        return {"y": 0.0, "height": container_height}
    raise ValueError(alignment)


def layout_flex_expanded(container_width, children):
    # children: list of {"fixed": w} or {"flex": f}
    fixed_total = sum(c["fixed"] for c in children if "fixed" in c)
    flex_total = sum(c["flex"] for c in children if "flex" in c)
    remaining = max(0.0, container_width - fixed_total)
    widths = []
    for c in children:
        if "fixed" in c:
            widths.append(float(c["fixed"]))
        else:
            widths.append(round(remaining * c["flex"] / flex_total, 2))
    return widths


def main():
    cases = []

    # Case 1: Row MainAxisAlignment 6 modes math on 300px container with three 40px icons
    modes = ["start", "center", "end", "spaceBetween", "spaceEvenly", "spaceAround"]
    row_results = {m: layout_row(300.0, [40.0, 40.0, 40.0], m) for m in modes}
    cases.append(
        check(
            "row_main_axis_alignment_math",
            "Verify exact horizontal x-coordinates for all 6 MainAxisAlignment modes on 300px Row with 3x40px children",
            {
                "start": [0.0, 40.0, 80.0],
                "center": [90.0, 130.0, 170.0],
                "end": [180.0, 220.0, 260.0],
                "spaceBetween": [0.0, 130.0, 260.0],
                "spaceEvenly": [45.0, 130.0, 215.0],
                "spaceAround": [30.0, 130.0, 230.0],
            },
            row_results,
        )
    )

    # Case 2: Column CrossAxisAlignment 4 modes math
    cross_modes = ["start", "center", "end", "stretch"]
    cross_results = {m: layout_cross_axis(200.0, 40.0, m) for m in cross_modes}
    cases.append(
        check(
            "column_cross_axis_alignment_math",
            "Verify CrossAxisAlignment start/center/end/stretch geometry on 200px container with 40px child",
            {
                "start": {"y": 0.0, "height": 40.0},
                "center": {"y": 80.0, "height": 40.0},
                "end": {"y": 160.0, "height": 40.0},
                "stretch": {"y": 0.0, "height": 200.0},
            },
            cross_results,
        )
    )

    # Case 3: Expanded fixed+adaptive and 1:2:1 flex ratio distribution
    fixed_plus_expanded = layout_flex_expanded(400.0, [{"fixed": 100}, {"flex": 1}, {"fixed": 50}])
    ratio_1_2_1 = layout_flex_expanded(400.0, [{"flex": 1}, {"flex": 2}, {"flex": 1}])
    cases.append(
        check(
            "expanded_flex_space_allocation",
            "Verify Flex/Expanded layout distributes remaining 250px and 1:2:1 ratios (100/200/100) on 400px Row",
            {"fixed_plus_expanded": [100.0, 250.0, 50.0], "ratio_1_2_1": [100.0, 200.0, 100.0]},
            {"fixed_plus_expanded": fixed_plus_expanded, "ratio_1_2_1": ratio_1_2_1},
        )
    )

    # Case 4: Stack Positioned coordinates, EdgeInsets box model & Scaffold slot structure
    stack_w, stack_h = 300, 200
    top_right_icon = {"x": stack_w - 10 - 24, "y": 10}
    bottom_left_text = {"x": 10, "y": stack_h - 10 - 20}
    # EdgeInsets.only(left=10, right=20, top=5, bottom=5) + symmetric(h=16, v=8)
    only_insets = {"horizontal": 10 + 20, "vertical": 5 + 5}
    sym_insets = {"horizontal": 16 * 2, "vertical": 8 * 2}
    scaffold_slots = ["appBar", "body", "floatingActionButton", "bottomNavigationBar"]
    cases.append(
        check(
            "stack_padding_and_scaffold_layout",
            "Verify Stack Positioned offsets, EdgeInsets total spacing, and Material Scaffold 4-slot skeleton",
            {
                "top_right_icon": {"x": 266, "y": 10},
                "bottom_left_text": {"x": 10, "y": 170},
                "only_insets": {"horizontal": 30, "vertical": 10},
                "sym_insets": {"horizontal": 32, "vertical": 16},
                "scaffold_slot_count": 4,
            },
            {
                "top_right_icon": top_right_icon,
                "bottom_left_text": bottom_left_text,
                "only_insets": only_insets,
                "sym_insets": sym_insets,
                "scaffold_slot_count": len(scaffold_slots),
            },
        )
    )

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证 6 种 MainAxisAlignment 坐标、4 种 CrossAxisAlignment 尺寸、1:2:1 Expanded 分配及 Stack/EdgeInsets/Scaffold 布局数学。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1988.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Flutter

课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a1988.zip

下载课程关联工程包:Flutter

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1999.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`spaceEvenly` 让两端边缘空白与元素之间空白完全相等;`spaceAround` 给每个元素两侧分配同等半宽留白,因此相邻元素之间的间距是首尾边缘空白的 2 倍。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习