You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter Widget测试中验证TextFormField的obscureText属性值

Flutter Widget测试获取TextFormField的obscureText属性解决方法

报错原因

TextFormField 是 FormField 的子类,仅负责表单域的状态管理、校验等能力,本身没有公开 obscureText getter,所有输入相关的参数都会透传给内部实际渲染的 TextField 组件,因此直接从 TextFormField 实例读取该属性会触发未定义getter的报错。

解决方式

通过 find.descendant 限定范围,查找目标 TextFormField 下的子级 TextField 组件,直接读取该组件的 obscureText 属性即可完成断言。

修改后完整测试代码

testWidgets(
  'show and hide password fields',
  (WidgetTester tester) async {
    await tester.pumpWidget(
      materialWrapper(
        child: emailSignUpScreen,
      ),
    );
    final Finder passwordTextFormField = find.byKey(
      const Key('passwordTextFormField'),
    );
    // 限定查找范围为目标TextFormField的子组件
    final Finder textFieldInForm = find.descendant(
      of: passwordTextFormField,
      matching: find.byType(TextField),
    );
    final TextField input = tester.widget<TextField>(textFieldInForm);
    expect(input.obscureText, true);
  },
);

内容的提问来源于stack exchange,提问作者Luke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:39:00