如何在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
相关产品推荐
相关产品推荐

