蓝色天空网mbsky.com · 知识 · 实践 · 创造Flutter · 本地阅读预览
教程 / 移动开发 / Flutter

Flutter 用户输入

系统梳理 Flutter 文本输入(TextField/InputDecoration)、TextEditingController 控制与释放、FocusNode 焦点管理、各类按钮、Switch/Checkbox/Radio 开关选择以及 Slider/RangeSlider 滑块控件。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

TextField 与 TextEditingController 文本控制

`TextField` 是 Flutter 处理文本输入的基础组件,可通过 `InputDecoration` 定制 `labelText` 标签、`hintText` 占位提示、`prefixIcon` 前置图标以及 `OutlineInputBorder` 圆角外框;密码场景可开启 `obscureText: true` 掩码显示,多行留言场景可设置 `maxLines`。

若需要在代码里主动读取、预填或清空输入框内容,应为 `TextField` 绑定 `TextEditingController`,并配合 `onChanged` 监听实时输入变化。控制器属于原生/监听资源,务必在 `State.dispose()` 中调用 `_controller.dispose()` 释放。本站离线控制器验证器已完整核对写入、读取、清空、预设值、销毁及密码掩码行为。

FocusNode 焦点控制与按钮事件体系

多输入框场景下,使用 `FocusNode` 可通过 `requestFocus()` 主动在多个 `TextField` 间切换输入焦点,或调用 `unfocus()` 收起软键盘并取消焦点;同样需要在 `dispose()` 中逐一释放每个 `FocusNode`。本站离线焦点状态机验证了 `input1` 与 `input2` 之间的互斥焦点转移与安全失焦。

用户点击交互由多种语义化按钮承接:低强调的 `TextButton`、带填充与阴影的高强调 `ElevatedButton`(含图文变体 `ElevatedButton.icon`)、带描边的 `OutlinedButton`、图标按钮 `IconButton`,以及面向 iOS 风格的 `CupertinoButton`。将 `onPressed` 置为 `null` 即可统一进入禁用态。

选择控件(Switch/Checkbox/Radio)与滑块(Slider)

布尔与枚举选择交互由三类控件完成:`Switch` 切换二元开关状态;`Checkbox` 支持勾选(其 `onChanged` 回调参数为可空 `bool?`,需以 `value ?? false` 兜底);`Radio<T>` 通过多个选项共享同一个 `groupValue` 实现单选互斥。

连续或离散数值调节使用 `Slider`(设置 `min`、`max`、`divisions` 刻度数及浮动 `label`)和双端区间选择器 `RangeSlider`(绑定 `RangeValues(start, end)`)。所有输入控件均为受控组件:在 `onChanged` 回调中修改状态变量时,必须包裹 `setState()` 才能驱动 UI 同步更新。本站离线数学核验确认 10 等分滑块将 `0.73` 精准吸附至 `0.7`(标签 `70%`)。

运行 TextEditingController 生命周期、FocusNode 状态机、按钮/开关选择与 Slider 刻度量化离线核验

python · 阅读源码
"""Offline Flutter TextField, TextEditingController, FocusNode, Buttons, Switch/Checkbox/Radio, Slider verifier for Ch10 (user-input)."""
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,
    }


class TextEditingController:
    def __init__(self, initial=""):
        self._text = initial
        self.disposed = False
        self.change_log = []

    @property
    def text(self):
        return self._text

    @text.setter
    def text(self, val):
        if self.disposed:
            raise RuntimeError("TextEditingController used after dispose")
        self._text = val
        self.change_log.append(val)

    def clear(self):
        self.text = ""

    def dispose(self):
        self.disposed = True


class FocusManager:
    def __init__(self):
        self.focused = None

    def request_focus(self, node_id):
        self.focused = node_id

    def unfocus(self, node_id):
        if self.focused == node_id:
            self.focused = None


def main():
    cases = []

    # Case 1: TextField configuration & TextEditingController read/set/clear/dispose lifecycle
    ctrl = TextEditingController()
    ctrl.text = "flutter_user"
    read_val = ctrl.text
    ctrl.clear()
    after_clear = ctrl.text
    ctrl.text = "预设文本"
    after_preset = ctrl.text
    ctrl.dispose()
    masked = "*" * len("secret123")
    cases.append(
        check(
            "textfield_and_editing_controller",
            "Verify TextEditingController text set/read/clear/dispose lifecycle and password obscureText masking",
            {
                "read_val": "flutter_user",
                "after_clear": "",
                "after_preset": "预设文本",
                "disposed": True,
                "obscured_password": "*********",
            },
            {
                "read_val": read_val,
                "after_clear": after_clear,
                "after_preset": after_preset,
                "disposed": ctrl.disposed,
                "obscured_password": masked,
            },
        )
    )

    # Case 2: FocusNode exclusive focus transfer & unfocus
    fm = FocusManager()
    trace = [fm.focused]
    fm.request_focus("input1")
    trace.append(fm.focused)
    fm.request_focus("input2")
    trace.append(fm.focused)
    fm.unfocus("input1")  # no-op because input2 holds focus
    trace.append(fm.focused)
    fm.unfocus("input2")
    trace.append(fm.focused)
    cases.append(
        check(
            "focus_node_state_machine",
            "Verify FocusNode exclusive focus switching between input1 and input2 and clean unfocus",
            [None, "input1", "input2", "input2", None],
            trace,
        )
    )

    # Case 3: Button callbacks & Switch / Checkbox / Radio mutually exclusive selection
    clicks = []
    buttons = ["TextButton", "ElevatedButton", "OutlinedButton", "IconButton", "ElevatedButton.icon", "CupertinoButton"]
    for b in buttons:
        clicks.append(b)
    switch_val = False
    switch_val = not switch_val
    checkbox_val = None
    checkbox_val = checkbox_val if checkbox_val is not None else False
    checkbox_val = True
    radio_group = "A"
    radio_group = "B"
    cases.append(
        check(
            "buttons_and_toggle_controls",
            "Verify 6 button types dispatch callbacks and Switch/Checkbox/Radio state updates",
            {"button_count": 6, "switch": True, "checkbox": True, "radio_group": "B"},
            {"button_count": len(clicks), "switch": switch_val, "checkbox": checkbox_val, "radio_group": radio_group},
        )
    )

    # Case 4: Slider divisions quantization & RangeSlider bounds validation
    def quantize_slider(val, min_v=0.0, max_v=1.0, divisions=10):
        clamped = max(min_v, min(max_v, val))
        step = (max_v - min_v) / divisions
        snapped = round((clamped - min_v) / step) * step + min_v
        return round(snapped, 4)

    q_val = quantize_slider(0.73, 0.0, 1.0, 10)
    range_vals = (0.3, 0.7)
    cases.append(
        check(
            "slider_and_range_slider_math",
            "Verify Slider divisions=10 quantization (0.73 -> 0.7, label 70%) and RangeSlider start<=end invariant",
            {"snapped": 0.7, "label": "70%", "range_span": 0.4, "valid_range": True},
            {
                "snapped": q_val,
                "label": f"{round(q_val * 100)}%",
                "range_span": round(range_vals[1] - range_vals[0], 4),
                "valid_range": 0.0 <= range_vals[0] <= range_vals[1] <= 1.0,
            },
        )
    )

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证控制器读写清空销毁、FocusNode 互斥转移、6 类按钮与 Switch/Checkbox/Radio 更新及 Slider 10 刻度吸附 0.73->0.7(70%)。
运行 TextEditingController 生命周期、FocusNode 状态机、按钮/开关选择与 Slider 刻度量化离线核验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:4e6aea9c5c86be8f392cd8b22471a5d31a88fdd9aba5887925c3832cf910cf1f

下载本站示例源码

本地运行

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

下载Flutter 用户输入实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:3f7fb2dbfede08fe5500b4f4983e353f6f118260a616f82e5c05430e0c002b53

常见错误与边界

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

练习与解答

为什么在 `StatefulWidget` 中创建的 `TextEditingController` 和 `FocusNode` 都必须在 `dispose()` 中手动销毁?

展开参考解答

它们内部维护了监听器列表并与底层文本输入/焦点树建立引用,若页面卸载时不调用 `dispose()` 解除绑定,会导致监听器无法被垃圾回收进而引发内存泄漏。

规范与官方依据