key_event_manager.0_test.dart 2.52 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_api_samples/widgets/hardware_keyboard/key_event_manager.0.dart'
    as example;
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('App tracks lifecycle states', (WidgetTester tester) async {
    Future<String> getCapturedKey() async {
      final Widget textWidget = tester.firstWidget(
          find.textContaining('is not handled by shortcuts.'));
      expect(textWidget, isA<Text>());
      return (textWidget as Text).data!.split(' ').first;
    }

    await tester.pumpWidget(
      const MaterialApp(
        home: Scaffold(
          body: Center(
            child: example.FallbackDemo(),
          )
        ),
      ),
    );

    // Focus on the first text field.
    await tester.tap(find.byType(TextField).first);

    // Press Q, which is taken as a text input, unhandled by the keyboard system.
    await tester.sendKeyEvent(LogicalKeyboardKey.keyQ);
    await tester.pump();
    expect(await getCapturedKey(), 'Q');

    // Press Ctrl-A, which is taken as a text short cut, handled by the keyboard system.
    await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
    await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
    await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
    expect(await getCapturedKey(), 'Q');

    // Press A, which is taken as a text input, handled by the keyboard system.
    await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
    await tester.pump();
    expect(await getCapturedKey(), 'A');

    // Focus on the second text field.
    await tester.tap(find.byType(TextField).last);

    // Press Q, which is taken as a stub shortcut, handled by the keyboard system.
    await tester.sendKeyEvent(LogicalKeyboardKey.keyQ);
    await tester.pump();
    expect(await getCapturedKey(), 'A');

    // Press B, which is taken as a text input, unhandled by the keyboard system.
    await tester.sendKeyEvent(LogicalKeyboardKey.keyB);
    await tester.pump();
    expect(await getCapturedKey(), 'B');

    // Press Ctrl-A, which is taken as a text short cut, handled by the keyboard system.
    await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
    await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
    await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
    expect(await getCapturedKey(), 'B');
  });
}