Flutter测试中带三元表达式的按钮点击不执行函数问题
Flutter按钮测试异常问题求助
我在Flutter按钮测试中遇到了一个异常场景,找不到相关文档或同类问题说明,特来寻求解析。
原始按钮代码(带三元表达式)
FilledButton( onPressed: state.valid && !state.loading ? () async { // debugger(); await context.read<SignInCubit>().signIn(); }: null, child: const Text('Sign In'))
这段代码在模拟器中运行完全正常:表单为空时按钮初始禁用,填写完成后自动启用,点击登录时按钮会再次禁用。
测试代码
testGoldens('should disable button when signing in', (WidgetTester tester) async { // 准备工作 ... await tester.enterText( find.widgetWithText(TextFormField, 'E-mail'), 'valid@gmail.com'); await tester.enterText( find.widgetWithText(TextFormField, 'Password'), 'validpassword'); when(mockAuthService.signIn( email: anyNamed('email'), password: anyNamed('password'))) .thenAnswer((realInvocation) async { await Future.delayed(const Duration(seconds: 3)); return Future.value(User.empty()); }); // 执行操作 await tester.tap(find.widgetWithText(FilledButton, "Sign In")); await tester.pumpAndSettle(const Duration(seconds: 2)); // 验证结果 await screenMatchesGolden(tester, tester.testDescription); verify(mockAuthService.signIn( email: anyNamed('email'), password: anyNamed('password'))) .called(1); expect( tester .widget<FilledButton>( find.widgetWithText(FilledButton, "Sign In")) .enabled, isFalse);
我原本期望这段测试能调用模拟的认证服务,但实际并未执行,甚至连async函数内的调试断点都没触发。
修改后的按钮代码(直接绑定异步函数)
FilledButton( onPressed: () async { // debugger await context.read<SignInCubit>().signIn(); }, child: const Text('Sign In'))
修改后,模拟服务被成功调用,调试断点也能正常触发。
我刚接触Dart和Flutter,想请教:为什么后者的onPressed异步函数能正常执行,而带三元表达式的前者却不行?
内容的提问来源于stack exchange,提问作者treble_maker
相关产品推荐
相关产品推荐

