Skip to content

WidgetTester.sendKeyEvent(LogicalKeyboardKey.enter) does not trigger TextField.onSubmitted #116752

Closed

Description

@Jordan-Nelson

Steps to Reproduce

  1. Execute the first test below under code sample, and observe that it fails
  2. Execute the second test below under code sample, and observe that it passes

Expected results:
WidgetTester.sendKeyEvent(LogicalKeyboardKey.enter) would call the onSubmit callback in a TextField

Actual results:
WidgetTester.sendKeyEvent(LogicalKeyboardKey.enter) can interact with buttons, but not form fields.

Code sample
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('Can submit form field via LogicalKeyboardKey', (tester) async {
    bool wasSubmitted = false;
    final app = MaterialApp(
      home: Material(
        child: Center(
          child: TextField(
            onSubmitted: ((value) => wasSubmitted = true),
          ),
        ),
      ),
    );
    await tester.pumpWidget(app);

    // Set initial focus to window.
    await tester.tapAt(const Offset(0, 0));

    // Move focus to first focusable widget via keyboard (TextField).
    await tester.sendKeyEvent(LogicalKeyboardKey.tab);

    // Press enter to submit
    await tester.sendKeyEvent(LogicalKeyboardKey.enter);

    expect(wasSubmitted, true); // <- THIS FAILS
  });

  testWidgets('Can submit button via LogicalKeyboardKey', (tester) async {
    bool wasSubmitted = false;
    final app = MaterialApp(
      home: Material(
        child: Center(
          child: ElevatedButton(
            onPressed: (() => wasSubmitted = true),
            child: const Text('Submit'),
          ),
        ),
      ),
    );
    await tester.pumpWidget(app);

    // Set initial focus to window.
    await tester.tapAt(const Offset(0, 0));

    // Move focus to first focusable widget via keyboard (ElevatedButton).
    await tester.sendKeyEvent(LogicalKeyboardKey.tab);

    // Press enter to submit
    await tester.sendKeyEvent(LogicalKeyboardKey.enter);

    expect(wasSubmitted, true); // <- THIS PASSES
  });
}
[✓] Flutter (Channel stable, 3.3.8, on macOS 12.6.1 21G217 darwin-x64, locale en-US)
    • Flutter version 3.3.8 on channel stable at /Users/nejrd/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 52b3dc25f6 (4 weeks ago), 2022-11-09 12:09:26 +0800
    • Engine revision 857bd6b74c
    • Dart version 2.18.4
    • DevTools version 2.15.0

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/nejrd/Library/Android/sdk
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

Activity

  1. darshankawar commented on Dec 9, 2022

    @darshankawar
    Member

    Thanks for the report. Using code sample provided, seeing same behavior, ie, first test fails and other passes:

    
    ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
    The following TestFailure was thrown running a test:
    Expected: <true>
      Actual: <false>
    
    When the exception was thrown, this was the stack:
    #4      main.<anonymous closure> (file:///Users/dhs/Documents/NCFlutter/test_app/test/widget_test.dart:35:5)
    <asynchronous suspension>
    <asynchronous suspension>
    (elided one frame from package:stack_trace)
    
    This was caught by the test expectation on the following line:
      file:///Users/dhs/Documents/NCFlutter/test_app/test/widget_test.dart line 35
    The test description was:
      Can submit form field via LogicalKeyboardKey
    ════════════════════════════════════════════════════════════════════════════════════════════════════
    
    
    stable, master flutter doctor -v
    [✓] Flutter (Channel stable, 3.3.9, on macOS 12.2.1 21D62 darwin-x64, locale
        en-GB)
        • Flutter version 3.3.9 on channel stable at
          /Users/dhs/documents/fluttersdk/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision b8f7f1f986 (12 days ago), 2022-11-23 06:43:51 +0900
        • Engine revision 8f2221fbef
        • Dart version 2.18.5
        • DevTools version 2.15.0
    
    [!] Xcode - develop for iOS and macOS (Xcode 12.3)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        ! Flutter recommends a minimum Xcode version of 13.
          Download the latest version or update via the Mac App Store.
        • CocoaPods version 1.11.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] VS Code (version 1.62.0)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.21.0
    
    [✓] Connected device (5 available)
        • SM G975F (mobile)       • RZ8M802WY0X • android-arm64   • Android 11 (API 30)
        • Darshan's iphone (mobile)  • 21150b119064aecc249dfcfe05e259197461ce23 •
          ios            • iOS 14.4.1 18D61
        • iPhone 12 Pro Max (mobile) • A5473606-0213-4FD8-BA16-553433949729     •
          ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-3 (simulator)
        • macOS (desktop)            • macos                                    •
          darwin-x64     • Mac OS X 10.15.4 19E2269 darwin-x64
        • Chrome (web)               • chrome                                   •
          web-javascript • Google Chrome 98.0.4758.80
    
    [✓] HTTP Host Availability
        • All required HTTP hosts are available
    
    ! Doctor found issues in 1 category.
    
    [!] Flutter (Channel master, 3.7.0-4.0.pre.48, on macOS 12.2.1 21D62 darwin-x64,
        locale en-GB)
        • Flutter version 3.7.0-4.0.pre.48 on channel master at
          /Users/dhs/documents/fluttersdk/flutter
        ! Warning: `flutter` on your path resolves to
          /Users/dhs/Documents/Fluttersdk/flutter/bin/flutter, which is not inside
          your current Flutter SDK checkout at
          /Users/dhs/documents/fluttersdk/flutter. Consider adding
          /Users/dhs/documents/fluttersdk/flutter/bin to the front of your path.
        ! Warning: `dart` on your path resolves to
          /Users/dhs/Documents/Fluttersdk/flutter/bin/dart, which is not inside your
          current Flutter SDK checkout at /Users/dhs/documents/fluttersdk/flutter.
          Consider adding /Users/dhs/documents/fluttersdk/flutter/bin to the front
          of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision eefbe85c8b (19 minutes ago), 2022-12-08 22:32:07 -0600
        • Engine revision 8d83b98c55
        • Dart version 3.0.0 (build 3.0.0-0.0.dev)
        • DevTools version 2.20.0
        • If those were intentional, you can disregard the above warnings; however
          it is recommended to use "git" directly to perform update checks and
          upgrades.
    
    
    [!] Xcode - develop for iOS and macOS (Xcode 12.3)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        ! Flutter recommends a minimum Xcode version of 13.
          Download the latest version or update via the Mac App Store.
        • CocoaPods version 1.11.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] VS Code (version 1.62.0)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.21.0
    
    [✓] Connected device (5 available)
        • SM G975F (mobile)       • RZ8M802WY0X • android-arm64   • Android 11 (API 30)
        • Darshan's iphone (mobile)  • 21150b119064aecc249dfcfe05e259197461ce23 •
          ios            • iOS 14.4.1 18D61
        • iPhone 12 Pro Max (mobile) • A5473606-0213-4FD8-BA16-553433949729     •
          ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-3 (simulator)
        • macOS (desktop)            • macos                                    •
          darwin-x64     • Mac OS X 10.15.4 19E2269 darwin-x64
        • Chrome (web)               • chrome                                   •
          web-javascript • Google Chrome 98.0.4758.80
    
    [✓] HTTP Host Availability
        • All required HTTP hosts are available
    
    ! Doctor found issues in 1 category.
    
    
    
    
  2. added
    a: tests"flutter test", flutter_test, or one of our tests
    frameworkflutter/packages/flutter repository. See also f: labels.
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    a: text inputEntering text in a text field or keyboard related problems
    and removed
    in triagePresently being triaged by the triage team
    on Dec 9, 2022
  3. goderbauer commented on Dec 13, 2022

    @goderbauer
    Member
  4. added
    P2Important issues not at the top of the work list
    on Dec 13, 2022
  5. TahaTesser commented on Dec 14, 2022

    @TahaTesser
    Contributor

    I believe the key events for text inputs are handled by the framework.
    The correct way to trigger onSubmitted is by sending an input action.

      testWidgets('Can submit form field via LogicalKeyboardKey', (WidgetTester tester) async {
        bool wasSubmitted = false;
        final Widget app = MaterialApp(
          home: Material(
            child: Center(
              child: TextField(
                onSubmitted: (value) {
                  wasSubmitted = true;
                  print('onSubmitted: $value');
                },
              ),
            ),
          ),
        );
        await tester.pumpWidget(app);
    
        // Set initial focus to window.
        await tester.tapAt(Offset.zero);
    
        // Move focus to first focusable widget via keyboard (TextField).
        await tester.sendKeyEvent(LogicalKeyboardKey.tab);
        await tester.pumpAndSettle();
    
        // Send done action to submit form field.
        await tester.testTextInput.receiveAction(TextInputAction.done);
        await tester.pumpAndSettle();
    
        expect(wasSubmitted, true); // <- THIS PASSES
      });
    }
  6. justinmc commented on Dec 22, 2022

    @justinmc
    Contributor

    @TahaTesser is right. I think the real problem here is that the docs don't explain this very well. I've opened a PR that adds a small section about testing to the onSubmitted docs: #117550

  7. added
    r: fixedIssue is closed as already fixed in a newer version
    on Dec 22, 2022
  8. github-actions commented on Mar 4, 2023

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  9. locked as resolved and limited conversation to collaborators on Mar 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work lista: tests"flutter test", flutter_test, or one of our testsa: text inputEntering text in a text field or keyboard related problemsd: api docsIssues with https://api.flutter.dev/found in release: 3.3Found to occur in 3.3found in release: 3.7Found to occur in 3.7frameworkflutter/packages/flutter repository. See also f: labels.has reproducible stepsThe issue has been confirmed reproducible and is ready to work onr: fixedIssue is closed as already fixed in a newer version

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions