text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// 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/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; @immutable class _MockKey { const _MockKey({required this.hashCode, required this.payload}); @override final int hashCode; final String payload; @override bool operator ==(Object other) { return other is _MockKey && other.payload == payload; } } void main() { test('PersistentHashMap - Simple Test', () { final List<PersistentHashMap<String, int>> maps = <PersistentHashMap<String, int>>[]; maps.add(const PersistentHashMap<String, int>.empty()); for (int i = 0; i < 50; i++) { maps.add(maps.last.put('key:$i', i)); } for (int i = 1; i < maps.length; i++) { final PersistentHashMap<String, int> m = maps[i]; for (int j = 0; j < i; j++) { expect(m['key:$j'], equals(j)); } } }); test('PersistentHashMap - hash collisions', () { const _MockKey key1 = _MockKey(hashCode: 1, payload: 'key:1'); const _MockKey key2 = _MockKey(hashCode: 0 | (1 << 5), payload: 'key:2'); const _MockKey key3 = _MockKey(hashCode: 1, payload: 'key:3'); const _MockKey key4 = _MockKey(hashCode: 1 | (1 << 5), payload: 'key:4'); final PersistentHashMap<_MockKey, String> map = const PersistentHashMap<_MockKey, String>.empty() .put(key1, 'a') .put(key2, 'b') .put(key3, 'c'); expect(map[key1], equals('a')); expect(map[key2], equals('b')); expect(map[key3], equals('c')); final PersistentHashMap<_MockKey, String> map2 = map.put(key4, 'd'); expect(map2[key4], equals('d')); final PersistentHashMap<_MockKey, String> map3 = map2 .put(key1, 'updated(a)') .put(key2, 'updated(b)') .put(key3, 'updated(c)') .put(key4, 'updated(d)'); expect(map3[key1], equals('updated(a)')); expect(map3[key2], equals('updated(b)')); expect(map3[key3], equals('updated(c)')); expect(map3[key4], equals('updated(d)')); }); test('PersistentHashMap - inflation of nodes', () { final List<PersistentHashMap<_MockKey, int>> maps = <PersistentHashMap<_MockKey, int>>[]; maps.add(const PersistentHashMap<_MockKey, int>.empty()); for (int i = 0; i < 32 * 32; i++) { maps.add(maps.last.put(_MockKey(hashCode: i, payload: '$i'), i)); } for (int i = 1; i < maps.length; i++) { final PersistentHashMap<_MockKey, int> m = maps[i]; for (int j = 0; j < i; j++) { expect(m[_MockKey(hashCode: j, payload: '$j')], equals(j)); } } }); }
flutter/packages/flutter/test/foundation/persistent_hash_map_test.dart/0
{ "file_path": "flutter/packages/flutter/test/foundation/persistent_hash_map_test.dart", "repo_id": "flutter", "token_count": 1164 }
654
// 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 'dart:ui' as ui; import 'package:clock/clock.dart'; import 'package:fake_async/fake_async.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_test/flutter_test.dart'; typedef HandleEventCallback = void Function(PointerEvent event); class TestResampleEventFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding { HandleEventCallback? callback; FrameCallback? postFrameCallback; Duration? frameTime; @override void handleEvent(PointerEvent event, HitTestEntry entry) { super.handleEvent(event, entry); if (callback != null) { callback?.call(event); } } @override Duration get currentSystemFrameTimeStamp { assert(frameTime != null); return frameTime!; } @override int addPostFrameCallback(FrameCallback callback, {String debugLabel = 'callback'}) { postFrameCallback = callback; return 0; } @override SamplingClock? get debugSamplingClock => TestSamplingClock(); } class TestSamplingClock implements SamplingClock { @override DateTime now() => clock.now(); @override Stopwatch stopwatch() => clock.stopwatch(); // flutter_ignore: stopwatch (see analyze.dart) // Ignore context: FakeAsync controls clock.stopwatch(), this is safe in tests. } typedef ResampleEventTest = void Function(FakeAsync async); void testResampleEvent(String description, ResampleEventTest callback) { test(description, () { fakeAsync((FakeAsync async) { callback(async); }, initialTime: DateTime.utc(2015)); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/87067 // Fake clock is not working with the web platform. } void main() { final TestResampleEventFlutterBinding binding = TestResampleEventFlutterBinding(); testResampleEvent('Pointer event resampling', (FakeAsync async) { Duration currentTime() => Duration(milliseconds: clock.now().millisecondsSinceEpoch); final Duration epoch = currentTime(); final ui.PointerDataPacket packet = ui.PointerDataPacket( data: <ui.PointerData>[ ui.PointerData( change: ui.PointerChange.add, timeStamp: epoch, ), ui.PointerData( change: ui.PointerChange.down, timeStamp: epoch + const Duration(milliseconds: 10), ), ui.PointerData( change: ui.PointerChange.move, physicalX: 10.0, timeStamp: epoch + const Duration(milliseconds: 20), ), ui.PointerData( change: ui.PointerChange.move, physicalX: 20.0, timeStamp: epoch + const Duration(milliseconds: 30), ), ui.PointerData( change: ui.PointerChange.move, physicalX: 30.0, timeStamp: epoch + const Duration(milliseconds: 40), ), ui.PointerData( change: ui.PointerChange.move, physicalX: 40.0, timeStamp: epoch + const Duration(milliseconds: 50), ), ui.PointerData( change: ui.PointerChange.move, physicalX: 50.0, timeStamp: epoch + const Duration(milliseconds: 60), ), ui.PointerData( change: ui.PointerChange.up, physicalX: 50.0, timeStamp: epoch + const Duration(milliseconds: 70), ), ui.PointerData( change: ui.PointerChange.remove, physicalX: 50.0, timeStamp: epoch + const Duration(milliseconds: 70), ), ], ); const Duration samplingOffset = Duration(milliseconds: -5); const Duration frameInterval = Duration(microseconds: 16667); GestureBinding.instance.resamplingEnabled = true; GestureBinding.instance.samplingOffset = samplingOffset; final List<PointerEvent> events = <PointerEvent>[]; binding.callback = events.add; GestureBinding.instance.platformDispatcher.onPointerDataPacket?.call(packet); // No pointer events should have been dispatched yet. expect(events.length, 0); // Frame callback should have been requested. FrameCallback? callback = binding.postFrameCallback; binding.postFrameCallback = null; expect(callback, isNotNull); binding.frameTime = epoch + const Duration(milliseconds: 15); callback!(Duration.zero); // One pointer event should have been dispatched. expect(events.length, 1); expect(events[0], isA<PointerDownEvent>()); expect(events[0].timeStamp, binding.frameTime! + samplingOffset); expect(events[0].position, Offset(0.0 / _devicePixelRatio, 0.0)); // Second frame callback should have been requested. callback = binding.postFrameCallback; binding.postFrameCallback = null; expect(callback, isNotNull); final Duration frameTime = epoch + const Duration(milliseconds: 25); binding.frameTime = frameTime; callback!(Duration.zero); // Second pointer event should have been dispatched. expect(events.length, 2); expect(events[1], isA<PointerMoveEvent>()); expect(events[1].timeStamp, binding.frameTime! + samplingOffset); expect(events[1].position, Offset(10.0 / _devicePixelRatio, 0.0)); expect(events[1].delta, Offset(10.0 / _devicePixelRatio, 0.0)); // Verify that resampling continues without a frame callback. async.elapse(frameInterval * 1.5); // Third pointer event should have been dispatched. expect(events.length, 3); expect(events[2], isA<PointerMoveEvent>()); expect(events[2].timeStamp, frameTime + frameInterval + samplingOffset); async.elapse(frameInterval); // Remaining pointer events should have been dispatched. expect(events.length, 5); expect(events[3], isA<PointerMoveEvent>()); expect(events[3].timeStamp, frameTime + frameInterval * 2 + samplingOffset); expect(events[4], isA<PointerUpEvent>()); expect(events[4].timeStamp, frameTime + frameInterval * 2 + samplingOffset); async.elapse(frameInterval); // No more pointer events should have been dispatched. expect(events.length, 5); GestureBinding.instance.resamplingEnabled = false; }); } double get _devicePixelRatio => GestureBinding.instance.platformDispatcher.implicitView!.devicePixelRatio;
flutter/packages/flutter/test/gestures/gesture_binding_resample_event_test.dart/0
{ "file_path": "flutter/packages/flutter/test/gestures/gesture_binding_resample_event_test.dart", "repo_id": "flutter", "token_count": 2417 }
655
// 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/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter_test/flutter_test.dart'; import 'gesture_tester.dart'; // Anything longer than [kDoubleTapTimeout] will reset the serial tap count. final Duration kSerialTapDelay = kDoubleTapTimeout ~/ 2; void main() { TestWidgetsFlutterBinding.ensureInitialized(); late List<String> events; late SerialTapGestureRecognizer serial; setUp(() { events = <String>[]; serial = SerialTapGestureRecognizer() ..onSerialTapDown = (SerialTapDownDetails details) { events.add('down#${details.count}'); } ..onSerialTapCancel = (SerialTapCancelDetails details) { events.add('cancel#${details.count}'); } ..onSerialTapUp = (SerialTapUpDetails details) { events.add('up#${details.count}'); }; addTearDown(serial.dispose); }); // Down/up pair 1: normal tap sequence const PointerDownEvent down1 = PointerDownEvent( pointer: 1, position: Offset(10.0, 10.0), ); const PointerCancelEvent cancel1 = PointerCancelEvent( pointer: 1, ); const PointerUpEvent up1 = PointerUpEvent( pointer: 1, position: Offset(11.0, 9.0), ); // Down/up pair 2: normal tap sequence close to pair 1 const PointerDownEvent down2 = PointerDownEvent( pointer: 2, position: Offset(12.0, 12.0), ); const PointerUpEvent up2 = PointerUpEvent( pointer: 2, position: Offset(13.0, 11.0), ); // Down/up pair 3: normal tap sequence close to pair 1 const PointerDownEvent down3 = PointerDownEvent( pointer: 3, position: Offset(12.0, 12.0), ); const PointerUpEvent up3 = PointerUpEvent( pointer: 3, position: Offset(13.0, 11.0), ); // Down/up pair 4: normal tap sequence far away from pair 1 const PointerDownEvent down4 = PointerDownEvent( pointer: 4, position: Offset(130.0, 130.0), ); const PointerUpEvent up4 = PointerUpEvent( pointer: 4, position: Offset(131.0, 129.0), ); // Down/move/up sequence 5: intervening motion const PointerDownEvent down5 = PointerDownEvent( pointer: 5, position: Offset(10.0, 10.0), ); const PointerMoveEvent move5 = PointerMoveEvent( pointer: 5, position: Offset(25.0, 25.0), ); const PointerUpEvent up5 = PointerUpEvent( pointer: 5, position: Offset(25.0, 25.0), ); // Down/up pair 7: normal tap sequence close to pair 1 but on secondary button const PointerDownEvent down6 = PointerDownEvent( pointer: 6, position: Offset(10.0, 10.0), buttons: kSecondaryMouseButton, ); const PointerUpEvent up6 = PointerUpEvent( pointer: 6, position: Offset(11.0, 9.0), ); testGesture('Recognizes serial taps', (GestureTester tester) { serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); events.clear(); tester.async.elapse(kSerialTapDelay); serial.addPointer(down2); tester.closeArena(2); tester.route(down2); tester.route(up2); GestureBinding.instance.gestureArena.sweep(2); expect(events, <String>['down#2', 'up#2']); events.clear(); tester.async.elapse(kSerialTapDelay); serial.addPointer(down3); tester.closeArena(3); tester.route(down3); tester.route(up3); GestureBinding.instance.gestureArena.sweep(3); expect(events, <String>['down#3', 'up#3']); }); // Because tap gesture will hold off on declaring victory. testGesture('Wins over tap gesture below it in the tree', (GestureTester tester) { bool recognizedSingleTap = false; bool canceledSingleTap = false; final TapGestureRecognizer singleTap = TapGestureRecognizer() ..onTap = () { recognizedSingleTap = true; } ..onTapCancel = () { canceledSingleTap = true; }; addTearDown(singleTap.dispose); singleTap.addPointer(down1); serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.async.elapse(kPressTimeout); // To register the possible single tap. tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); expect(recognizedSingleTap, isFalse); expect(canceledSingleTap, isTrue); }); testGesture('Wins over tap gesture above it in the tree', (GestureTester tester) { bool recognizedSingleTap = false; bool canceledSingleTap = false; final TapGestureRecognizer singleTap = TapGestureRecognizer() ..onTap = () { recognizedSingleTap = true; } ..onTapCancel = () { canceledSingleTap = true; }; addTearDown(singleTap.dispose); serial.addPointer(down1); singleTap.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.async.elapse(kPressTimeout); // To register the possible single tap. tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); expect(recognizedSingleTap, isFalse); expect(canceledSingleTap, isTrue); }); testGesture('Loses to release gesture below it in the tree', (GestureTester tester) { bool recognizedRelease = false; final ReleaseGestureRecognizer release = ReleaseGestureRecognizer() ..onRelease = () { recognizedRelease = true; }; release.addPointer(down1); serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'cancel#1']); expect(recognizedRelease, isTrue); }); testGesture('Wins over release gesture above it in the tree', (GestureTester tester) { bool recognizedRelease = false; final ReleaseGestureRecognizer release = ReleaseGestureRecognizer() ..onRelease = () { recognizedRelease = true; }; serial.addPointer(down1); release.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); expect(recognizedRelease, isFalse); }); testGesture('Fires cancel if competing recognizer declares victory', (GestureTester tester) { final WinningGestureRecognizer winner = WinningGestureRecognizer(); winner.addPointer(down1); serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'cancel#1']); }); testGesture('Wins over double-tap recognizer below it in the tree', (GestureTester tester) { bool recognizedDoubleTap = false; final DoubleTapGestureRecognizer doubleTap = DoubleTapGestureRecognizer() ..onDoubleTap = () { recognizedDoubleTap = true; }; addTearDown(doubleTap.dispose); doubleTap.addPointer(down1); serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); expect(recognizedDoubleTap, isFalse); events.clear(); tester.async.elapse(kSerialTapDelay); doubleTap.addPointer(down2); serial.addPointer(down2); tester.closeArena(2); tester.route(down2); tester.route(up2); GestureBinding.instance.gestureArena.sweep(2); expect(events, <String>['down#2', 'up#2']); expect(recognizedDoubleTap, isFalse); events.clear(); tester.async.elapse(kSerialTapDelay); serial.addPointer(down3); tester.closeArena(3); tester.route(down3); tester.route(up3); GestureBinding.instance.gestureArena.sweep(3); expect(events, <String>['down#3', 'up#3']); }); testGesture('Wins over double-tap recognizer above it in the tree', (GestureTester tester) { bool recognizedDoubleTap = false; final DoubleTapGestureRecognizer doubleTap = DoubleTapGestureRecognizer() ..onDoubleTap = () { recognizedDoubleTap = true; }; addTearDown(doubleTap.dispose); serial.addPointer(down1); doubleTap.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); expect(recognizedDoubleTap, isFalse); events.clear(); tester.async.elapse(kSerialTapDelay); serial.addPointer(down2); doubleTap.addPointer(down2); tester.closeArena(2); tester.route(down2); tester.route(up2); GestureBinding.instance.gestureArena.sweep(2); expect(events, <String>['down#2', 'up#2']); expect(recognizedDoubleTap, isFalse); events.clear(); tester.async.elapse(kSerialTapDelay); serial.addPointer(down3); doubleTap.addPointer(down3); tester.closeArena(3); tester.route(down3); tester.route(up3); GestureBinding.instance.gestureArena.sweep(3); expect(events, <String>['down#3', 'up#3']); }); testGesture('Fires cancel and resets for PointerCancelEvent', (GestureTester tester) { serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(cancel1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'cancel#1']); events.clear(); tester.async.elapse(const Duration(milliseconds: 100)); serial.addPointer(down2); tester.closeArena(2); tester.route(down2); tester.route(up2); GestureBinding.instance.gestureArena.sweep(2); expect(events, <String>['down#1', 'up#1']); }); testGesture('Fires cancel and resets when pointer dragged past slop tolerance', (GestureTester tester) { serial.addPointer(down5); tester.closeArena(5); tester.route(down5); tester.route(move5); tester.route(up5); GestureBinding.instance.gestureArena.sweep(5); expect(events, <String>['down#1', 'cancel#1']); events.clear(); tester.async.elapse(const Duration(milliseconds: 1000)); serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); }); testGesture('Resets if times out in between taps', (GestureTester tester) { serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); events.clear(); tester.async.elapse(const Duration(milliseconds: 1000)); serial.addPointer(down2); tester.closeArena(2); tester.route(down2); tester.route(up2); GestureBinding.instance.gestureArena.sweep(2); expect(events, <String>['down#1', 'up#1']); }); testGesture('Resets if taps are far apart', (GestureTester tester) { serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); events.clear(); tester.async.elapse(const Duration(milliseconds: 100)); serial.addPointer(down4); tester.closeArena(4); tester.route(down4); tester.route(up4); GestureBinding.instance.gestureArena.sweep(4); expect(events, <String>['down#1', 'up#1']); }); testGesture('Serial taps with different buttons will start a new tap sequence', (GestureTester tester) { serial.addPointer(down1); tester.closeArena(1); tester.route(down1); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>['down#1', 'up#1']); events.clear(); tester.async.elapse(const Duration(milliseconds: 1000)); serial.addPointer(down6); tester.closeArena(6); tester.route(down6); tester.route(up6); GestureBinding.instance.gestureArena.sweep(6); expect(events, <String>['down#1', 'up#1']); }); testGesture('Interleaving taps cancel first sequence and start second sequence', (GestureTester tester) { serial.addPointer(down1); tester.closeArena(1); tester.route(down1); serial.addPointer(down2); tester.closeArena(2); tester.route(down2); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); tester.route(up2); GestureBinding.instance.gestureArena.sweep(2); expect(events, <String>['down#1', 'cancel#1', 'down#1', 'up#1']); }); testGesture('Is no-op if no callbacks are specified', (GestureTester tester) { serial = SerialTapGestureRecognizer(); addTearDown(serial.dispose); serial.addPointer(down1); tester.closeArena(1); tester.route(down1); expect(serial.isTrackingPointer, isFalse); tester.route(up1); GestureBinding.instance.gestureArena.sweep(1); expect(events, <String>[]); }); testGesture('Works for non-primary button', (GestureTester tester) { serial.addPointer(down6); tester.closeArena(6); tester.route(down6); tester.route(up6); GestureBinding.instance.gestureArena.sweep(6); expect(events, <String>['down#1', 'up#1']); }); } class WinningGestureRecognizer extends PrimaryPointerGestureRecognizer { @override String get debugDescription => 'winner'; @override void handlePrimaryPointer(PointerEvent event) { resolve(GestureDisposition.accepted); } } class ReleaseGestureRecognizer extends PrimaryPointerGestureRecognizer { VoidCallback? onRelease; @override String get debugDescription => 'release'; @override void handlePrimaryPointer(PointerEvent event) { if (event is PointerUpEvent) { resolve(GestureDisposition.accepted); if (onRelease != null) { onRelease!(); } } } }
flutter/packages/flutter/test/gestures/serial_tap_test.dart/0
{ "file_path": "flutter/packages/flutter/test/gestures/serial_tap_test.dart", "repo_id": "flutter", "token_count": 5647 }
656
// 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('ActionIconThemeData copyWith, ==, hashCode basics', () { expect(const ActionIconThemeData(), const ActionIconThemeData().copyWith()); expect(const ActionIconThemeData().hashCode, const ActionIconThemeData().copyWith().hashCode); }); testWidgets('ActionIconThemeData copyWith overrides all properties', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/126762. Widget originalButtonBuilder(BuildContext context) { return const SizedBox(); } Widget newButtonBuilder(BuildContext context) { return const Icon(Icons.add); } // Create a ActionIconThemeData with all properties set. final ActionIconThemeData original = ActionIconThemeData( backButtonIconBuilder: originalButtonBuilder, closeButtonIconBuilder: originalButtonBuilder, drawerButtonIconBuilder: originalButtonBuilder, endDrawerButtonIconBuilder: originalButtonBuilder, ); // Check if the all properties are copied. final ActionIconThemeData copy = original.copyWith(); expect(copy.backButtonIconBuilder, originalButtonBuilder); expect(copy.closeButtonIconBuilder, originalButtonBuilder); expect(copy.drawerButtonIconBuilder, originalButtonBuilder); expect(copy.endDrawerButtonIconBuilder, originalButtonBuilder); // Check if the properties are overridden. final ActionIconThemeData overridden = original.copyWith( backButtonIconBuilder: newButtonBuilder, closeButtonIconBuilder: newButtonBuilder, drawerButtonIconBuilder: newButtonBuilder, endDrawerButtonIconBuilder: newButtonBuilder, ); expect(overridden.backButtonIconBuilder, newButtonBuilder); expect(overridden.closeButtonIconBuilder, newButtonBuilder); expect(overridden.drawerButtonIconBuilder, newButtonBuilder); expect(overridden.endDrawerButtonIconBuilder, newButtonBuilder); }); test('ActionIconThemeData defaults', () { const ActionIconThemeData themeData = ActionIconThemeData(); expect(themeData.backButtonIconBuilder, null); expect(themeData.closeButtonIconBuilder, null); expect(themeData.drawerButtonIconBuilder, null); expect(themeData.endDrawerButtonIconBuilder, null); }); testWidgets('Default ActionIconThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const ActionIconThemeData().debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[]); }); testWidgets('ActionIconThemeData implements debugFillProperties', (WidgetTester tester) async { Widget actionButtonIconBuilder(BuildContext context) { return const Icon(IconData(0)); } final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); ActionIconThemeData( backButtonIconBuilder: actionButtonIconBuilder, closeButtonIconBuilder: actionButtonIconBuilder, drawerButtonIconBuilder: actionButtonIconBuilder, endDrawerButtonIconBuilder: actionButtonIconBuilder, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); final Matcher containsBuilderCallback = contains('Closure: (BuildContext) =>'); expect(description, <dynamic>[ allOf(startsWith('backButtonIconBuilder:'), containsBuilderCallback), allOf(startsWith('closeButtonIconBuilder:'), containsBuilderCallback), allOf(startsWith('drawerButtonIconBuilder:'), containsBuilderCallback), allOf(startsWith('endDrawerButtonIconBuilder:'), containsBuilderCallback), ]); }); testWidgets('Action buttons use ThemeData action icon theme', (WidgetTester tester) async { const Color green = Color(0xff00ff00); const IconData icon = IconData(0); Widget buildSampleIcon(BuildContext context) { return const Icon( icon, size: 20, color: green, ); } final ActionIconThemeData actionIconTheme = ActionIconThemeData( backButtonIconBuilder: buildSampleIcon, closeButtonIconBuilder: buildSampleIcon, drawerButtonIconBuilder: buildSampleIcon, endDrawerButtonIconBuilder: buildSampleIcon, ); await tester.pumpWidget( MaterialApp( theme: ThemeData.light(useMaterial3: true).copyWith( actionIconTheme: actionIconTheme, ), home: const Material( child: Column( children: <Widget>[ BackButton(), CloseButton(), DrawerButton(), EndDrawerButton(), ], ), ), ), ); final Icon backButtonIcon = tester.widget(find.descendant(of: find.byType(BackButton), matching: find.byType(Icon))); final Icon closeButtonIcon = tester.widget(find.descendant(of: find.byType(CloseButton), matching: find.byType(Icon))); final Icon drawerButtonIcon = tester.widget(find.descendant(of: find.byType(DrawerButton), matching: find.byType(Icon))); final Icon endDrawerButtonIcon = tester.widget(find.descendant(of: find.byType(EndDrawerButton), matching: find.byType(Icon))); expect(backButtonIcon.icon == icon, isTrue); expect(closeButtonIcon.icon == icon, isTrue); expect(drawerButtonIcon.icon == icon, isTrue); expect(endDrawerButtonIcon.icon == icon, isTrue); final RichText backButtonIconText = tester.widget(find.descendant(of: find.byType(BackButton), matching: find.byType(RichText))); final RichText closeButtonIconText = tester.widget(find.descendant(of: find.byType(CloseButton), matching: find.byType(RichText))); final RichText drawerButtonIconText = tester.widget(find.descendant(of: find.byType(DrawerButton), matching: find.byType(RichText))); final RichText endDrawerButtonIconText = tester.widget(find.descendant(of: find.byType(EndDrawerButton), matching: find.byType(RichText))); expect(backButtonIconText.text.style!.color, green); expect(closeButtonIconText.text.style!.color, green); expect(drawerButtonIconText.text.style!.color, green); expect(endDrawerButtonIconText.text.style!.color, green); }); // This test is essentially the same as 'Action buttons use ThemeData action icon theme'. In // this case the theme is introduced with the ActionIconTheme widget instead of // ThemeData.actionIconTheme. testWidgets('Action buttons use ActionIconTheme', (WidgetTester tester) async { const Color green = Color(0xff00ff00); const IconData icon = IconData(0); Widget buildSampleIcon(BuildContext context) { return const Icon( icon, size: 20, color: green, ); } final ActionIconThemeData actionIconTheme = ActionIconThemeData( backButtonIconBuilder: buildSampleIcon, closeButtonIconBuilder: buildSampleIcon, drawerButtonIconBuilder: buildSampleIcon, endDrawerButtonIconBuilder: buildSampleIcon, ); await tester.pumpWidget( MaterialApp( home: ActionIconTheme( data: actionIconTheme, child: const Material( child: Column( children: <Widget>[ BackButton(), CloseButton(), DrawerButton(), EndDrawerButton(), ], ), ), ), ), ); final Icon backButtonIcon = tester.widget(find.descendant(of: find.byType(BackButton), matching: find.byType(Icon))); final Icon closeButtonIcon = tester.widget(find.descendant(of: find.byType(CloseButton), matching: find.byType(Icon))); final Icon drawerButtonIcon = tester.widget(find.descendant(of: find.byType(DrawerButton), matching: find.byType(Icon))); final Icon endDrawerButtonIcon = tester.widget(find.descendant(of: find.byType(EndDrawerButton), matching: find.byType(Icon))); expect(backButtonIcon.icon == icon, isTrue); expect(closeButtonIcon.icon == icon, isTrue); expect(drawerButtonIcon.icon == icon, isTrue); expect(endDrawerButtonIcon.icon == icon, isTrue); final RichText backButtonIconText = tester.widget(find.descendant(of: find.byType(BackButton), matching: find.byType(RichText))); final RichText closeButtonIconText = tester.widget(find.descendant(of: find.byType(CloseButton), matching: find.byType(RichText))); final RichText drawerButtonIconText = tester.widget(find.descendant(of: find.byType(DrawerButton), matching: find.byType(RichText))); final RichText endDrawerButtonIconText = tester.widget(find.descendant(of: find.byType(EndDrawerButton), matching: find.byType(RichText))); expect(backButtonIconText.text.style!.color, green); expect(closeButtonIconText.text.style!.color, green); expect(drawerButtonIconText.text.style!.color, green); expect(endDrawerButtonIconText.text.style!.color, green); }); }
flutter/packages/flutter/test/material/action_icons_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/action_icons_theme_test.dart", "repo_id": "flutter", "token_count": 3254 }
657
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Material3 - Shadow effect is not doubled', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/123064 debugDisableShadows = false; const double elevation = 1; const Color shadowColor = Colors.black; await tester.pumpWidget( MaterialApp( theme: ThemeData.light(useMaterial3: true), home: const Scaffold( bottomNavigationBar: BottomAppBar( elevation: elevation, shadowColor: shadowColor, ), ), ), ); final Finder finder = find.byType(BottomAppBar); expect(finder, paints..shadow(color: shadowColor, elevation: elevation)); expect(finder, paintsExactlyCountTimes(#drawShadow, 1)); debugDisableShadows = true; }); testWidgets('Material3 - Only one layer with `color` is painted', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/122667 const Color bottomAppBarColor = Colors.black45; await tester.pumpWidget( MaterialApp( theme: ThemeData.light(useMaterial3: true), home: const Scaffold( bottomNavigationBar: BottomAppBar( color: bottomAppBarColor, // Avoid getting a surface tint color, to keep the color check below simple elevation: 0, ), ), ), ); // There should be just one color layer, and with the specified color. final Finder finder = find.descendant( of: find.byType(BottomAppBar), matching: find.byWidgetPredicate((Widget widget) { // A color layer is probably a [PhysicalShape] or [PhysicalModel], // either used directly or backing a [Material] (one without // [MaterialType.transparency]). return widget is PhysicalShape || widget is PhysicalModel; }), ); final Widget widget = tester.widgetList(finder).single; if (widget is PhysicalShape) { expect(widget.color, bottomAppBarColor); } else if (widget is PhysicalModel) { expect(widget.color, bottomAppBarColor); } else { // Should be unreachable: compare with the finder. assert(false); } }); testWidgets('No overlap with floating action button', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), bottomNavigationBar: ShapeListener( BottomAppBar( child: SizedBox(height: 100.0), ), ), ), ), ); final ShapeListenerState shapeListenerState = tester.state(find.byType(ShapeListener)); final RenderBox renderBox = tester.renderObject(find.byType(BottomAppBar)); final Path expectedPath = Path() ..addRect(Offset.zero & renderBox.size); final Path actualPath = shapeListenerState.cache.value; expect( actualPath, coversSameAreaAs( expectedPath, areaToCompare: (Offset.zero & renderBox.size).inflate(5.0), ), ); }); testWidgets('Material2 - Custom shape', (WidgetTester tester) async { final Key key = UniqueKey(); Future<void> pump(FloatingActionButtonLocation location) async { await tester.pumpWidget( SizedBox( width: 200, height: 200, child: RepaintBoundary( key: key, child: MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, ), floatingActionButtonLocation: location, bottomNavigationBar: const BottomAppBar( shape: AutomaticNotchedShape( BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(50.0))), ContinuousRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(30.0))), ), notchMargin: 10.0, color: Colors.green, child: SizedBox(height: 100.0), ), ), ), ), ), ); } await pump(FloatingActionButtonLocation.endDocked); await expectLater( find.byKey(key), matchesGoldenFile('m2_bottom_app_bar.custom_shape.1.png'), ); await pump(FloatingActionButtonLocation.centerDocked); await tester.pumpAndSettle(); await expectLater( find.byKey(key), matchesGoldenFile('m2_bottom_app_bar.custom_shape.2.png'), ); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/44572 testWidgets('Material3 - Custom shape', (WidgetTester tester) async { final Key key = UniqueKey(); Future<void> pump(FloatingActionButtonLocation location) async { await tester.pumpWidget( SizedBox( width: 200, height: 200, child: RepaintBoundary( key: key, child: MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, ), floatingActionButtonLocation: location, bottomNavigationBar: const BottomAppBar( shape: AutomaticNotchedShape( BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(50.0))), ContinuousRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(30.0))), ), notchMargin: 10.0, color: Colors.green, child: SizedBox(height: 100.0), ), ), ), ), ), ); } await pump(FloatingActionButtonLocation.endDocked); await expectLater( find.byKey(key), matchesGoldenFile('m3_bottom_app_bar.custom_shape.1.png'), ); await pump(FloatingActionButtonLocation.centerDocked); await tester.pumpAndSettle(); await expectLater( find.byKey(key), matchesGoldenFile('m3_bottom_app_bar.custom_shape.2.png'), ); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/44572 testWidgets('Custom Padding', (WidgetTester tester) async { const EdgeInsets customPadding = EdgeInsets.all(10); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light()), home: Builder( builder: (BuildContext context) { return const Scaffold( body: Align( alignment: Alignment.bottomCenter, child: BottomAppBar( padding: customPadding, child: ColoredBox( color: Colors.green, child: SizedBox(width: 300, height: 60), ), ), ), ); }, ), ), ); final BottomAppBar bottomAppBar = tester.widget(find.byType(BottomAppBar)); expect(bottomAppBar.padding, customPadding); final Rect babRect = tester.getRect(find.byType(BottomAppBar)); final Rect childRect = tester.getRect(find.byType(ColoredBox)); expect(childRect, const Rect.fromLTRB(250, 530, 550, 590)); expect(babRect, const Rect.fromLTRB(240, 520, 560, 600)); }); testWidgets('Material2 - Color defaults to Theme.bottomAppBarColor', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Builder( builder: (BuildContext context) { return Theme( data: Theme.of(context).copyWith(bottomAppBarTheme: const BottomAppBarTheme(color: Color(0xffffff00))), child: const Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), bottomNavigationBar: BottomAppBar(), ), ); }, ), ), ); final PhysicalShape physicalShape = tester.widget(find.byType(PhysicalShape).at(0)); expect(physicalShape.color, const Color(0xffffff00)); }); testWidgets('Material2 - Color overrides theme color', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Builder( builder: (BuildContext context) { return Theme( data: Theme.of(context).copyWith(bottomAppBarTheme: const BottomAppBarTheme(color: Color(0xffffff00))), child: const Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), bottomNavigationBar: BottomAppBar( color: Color(0xff0000ff), ), ), ); }, ), ), ); final PhysicalShape physicalShape = tester.widget(find.byType(PhysicalShape).at(0)); final Material material = tester.widget(find.byType(Material).at(1)); expect(physicalShape.color, const Color(0xff0000ff)); expect(material.color, null); /* no value in Material 2. */ }); testWidgets('Material3 - Color overrides theme color', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData.light(useMaterial3: true).copyWith( bottomAppBarTheme: const BottomAppBarTheme(color: Color(0xffffff00)), ), home: Builder( builder: (BuildContext context) { return const Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), bottomNavigationBar: BottomAppBar( color: Color(0xff0000ff), surfaceTintColor: Colors.transparent, ), ); }, ), ), ); final PhysicalShape physicalShape = tester.widget( find.descendant(of: find.byType(BottomAppBar), matching: find.byType(PhysicalShape))); expect(physicalShape.color, const Color(0xff0000ff)); }); testWidgets('Material3 - Shadow color is transparent', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true, ), home: const Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), bottomNavigationBar: BottomAppBar( color: Color(0xff0000ff), ), ), ) ); final PhysicalShape physicalShape = tester.widget( find.descendant(of: find.byType(BottomAppBar), matching: find.byType(PhysicalShape))); expect(physicalShape.shadowColor, Colors.transparent); }); testWidgets('Material2 - Dark theme applies an elevation overlay color', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData.from(useMaterial3: false, colorScheme: const ColorScheme.dark()), home: Scaffold( bottomNavigationBar: BottomAppBar( color: const ColorScheme.dark().surface, ), ), ), ); final PhysicalShape physicalShape = tester.widget(find.byType(PhysicalShape).at(0)); // For the default dark theme the overlay color for elevation 8 is 0xFF2D2D2D expect(physicalShape.color, const Color(0xFF2D2D2D)); }); testWidgets('Material3 - Dark theme applies an elevation overlay color', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.dark(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(useMaterial3: true, colorScheme: colorScheme), home: Scaffold( bottomNavigationBar: BottomAppBar( color: colorScheme.surfaceContainer, ), ), ), ); final PhysicalShape physicalShape = tester.widget(find.byType(PhysicalShape).at(0)); const double elevation = 3.0; // Default for M3. final Color overlayColor = ElevationOverlay.applySurfaceTint(colorScheme.surfaceContainer, colorScheme.surfaceTint, elevation); expect(physicalShape.color, isNot(overlayColor)); expect(physicalShape.color, colorScheme.surfaceContainer); }); // This is a regression test for a bug we had where toggling the notch on/off // would crash, as the shouldReclip method of ShapeBorderClipper or // _BottomAppBarClipper would try an illegal downcast. testWidgets('toggle shape to null', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( bottomNavigationBar: BottomAppBar( shape: RectangularNotch(), ), ), ), ); await tester.pumpWidget( const MaterialApp( home: Scaffold( bottomNavigationBar: BottomAppBar(), ), ), ); await tester.pumpWidget( const MaterialApp( home: Scaffold( bottomNavigationBar: BottomAppBar( shape: RectangularNotch(), ), ), ), ); }); testWidgets('no notch when notch param is null', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( bottomNavigationBar: ShapeListener(BottomAppBar()), floatingActionButton: FloatingActionButton( onPressed: null, child: Icon(Icons.add), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, ), ), ); final ShapeListenerState shapeListenerState = tester.state(find.byType(ShapeListener)); final RenderBox renderBox = tester.renderObject(find.byType(BottomAppBar)); final Path expectedPath = Path() ..addRect(Offset.zero & renderBox.size); final Path actualPath = shapeListenerState.cache.value; expect( actualPath, coversSameAreaAs( expectedPath, areaToCompare: (Offset.zero & renderBox.size).inflate(5.0), ), ); }); testWidgets('notch no margin', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( bottomNavigationBar: ShapeListener( BottomAppBar( shape: RectangularNotch(), notchMargin: 0.0, child: SizedBox(height: 100.0), ), ), floatingActionButton: FloatingActionButton( onPressed: null, child: Icon(Icons.add), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, ), ), ); final ShapeListenerState shapeListenerState = tester.state(find.byType(ShapeListener)); final RenderBox babBox = tester.renderObject(find.byType(BottomAppBar)); final Size babSize = babBox.size; final RenderBox fabBox = tester.renderObject(find.byType(FloatingActionButton)); final Size fabSize = fabBox.size; final double fabLeft = (babSize.width / 2.0) - (fabSize.width / 2.0); final double fabRight = fabLeft + fabSize.width; final double fabBottom = fabSize.height / 2.0; final Path expectedPath = Path() ..moveTo(0.0, 0.0) ..lineTo(fabLeft, 0.0) ..lineTo(fabLeft, fabBottom) ..lineTo(fabRight, fabBottom) ..lineTo(fabRight, 0.0) ..lineTo(babSize.width, 0.0) ..lineTo(babSize.width, babSize.height) ..lineTo(0.0, babSize.height) ..close(); final Path actualPath = shapeListenerState.cache.value; expect( actualPath, coversSameAreaAs( expectedPath, areaToCompare: (Offset.zero & babSize).inflate(5.0), ), ); }); testWidgets('notch with margin', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( bottomNavigationBar: ShapeListener( BottomAppBar( shape: RectangularNotch(), notchMargin: 6.0, child: SizedBox(height: 100.0), ), ), floatingActionButton: FloatingActionButton( onPressed: null, child: Icon(Icons.add), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, ), ), ); final ShapeListenerState shapeListenerState = tester.state(find.byType(ShapeListener)); final RenderBox babBox = tester.renderObject(find.byType(BottomAppBar)); final Size babSize = babBox.size; final RenderBox fabBox = tester.renderObject(find.byType(FloatingActionButton)); final Size fabSize = fabBox.size; final double fabLeft = (babSize.width / 2.0) - (fabSize.width / 2.0) - 6.0; final double fabRight = fabLeft + fabSize.width + 6.0; final double fabBottom = 6.0 + fabSize.height / 2.0; final Path expectedPath = Path() ..moveTo(0.0, 0.0) ..lineTo(fabLeft, 0.0) ..lineTo(fabLeft, fabBottom) ..lineTo(fabRight, fabBottom) ..lineTo(fabRight, 0.0) ..lineTo(babSize.width, 0.0) ..lineTo(babSize.width, babSize.height) ..lineTo(0.0, babSize.height) ..close(); final Path actualPath = shapeListenerState.cache.value; expect( actualPath, coversSameAreaAs( expectedPath, areaToCompare: (Offset.zero & babSize).inflate(5.0), ), ); }); testWidgets('Material2 - Observes safe area', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: const MediaQuery( data: MediaQueryData( padding: EdgeInsets.all(50.0), ), child: Scaffold( bottomNavigationBar: BottomAppBar( child: Center( child: Text('safe'), ), ), ), ), ), ); expect( tester.getBottomLeft(find.widgetWithText(Center, 'safe')), const Offset(50.0, 550.0), ); }); testWidgets('Material3 - Observes safe area', (WidgetTester tester) async { const double safeAreaPadding = 50.0; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: const MediaQuery( data: MediaQueryData( padding: EdgeInsets.all(safeAreaPadding), ), child: Scaffold( bottomNavigationBar: BottomAppBar( child: Center( child: Text('safe'), ), ), ), ), ), ); const double appBarVerticalPadding = 12.0; const double appBarHorizontalPadding = 16.0; expect( tester.getBottomLeft(find.widgetWithText(Center, 'safe')), const Offset( safeAreaPadding + appBarHorizontalPadding, 600 - safeAreaPadding - appBarVerticalPadding, ), ); }); testWidgets('clipBehavior is propagated', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( bottomNavigationBar: BottomAppBar( shape: RectangularNotch(), notchMargin: 0.0, child: SizedBox(height: 100.0), ), ), ), ); PhysicalShape physicalShape = tester.widget(find.byType(PhysicalShape)); expect(physicalShape.clipBehavior, Clip.none); await tester.pumpWidget( const MaterialApp( home: Scaffold( bottomNavigationBar: BottomAppBar( shape: RectangularNotch(), notchMargin: 0.0, clipBehavior: Clip.antiAliasWithSaveLayer, child: SizedBox(height: 100.0), ), ), ), ); physicalShape = tester.widget(find.byType(PhysicalShape)); expect(physicalShape.clipBehavior, Clip.antiAliasWithSaveLayer); }); testWidgets('Material2 - BottomAppBar with shape when Scaffold.bottomNavigationBar == null', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/80878 final ThemeData theme = ThemeData(useMaterial3: false); await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: FloatingActionButton( backgroundColor: Colors.green, child: const Icon(Icons.home), onPressed: () {}, ), body: Stack( children: <Widget>[ Container( color: Colors.amber, ), Container( alignment: Alignment.bottomCenter, child: BottomAppBar( color: Colors.green, shape: const CircularNotchedRectangle(), child: Container(height: 50), ), ), ], ), ), ), ); expect(tester.getRect(find.byType(FloatingActionButton)), const Rect.fromLTRB(372, 528, 428, 584)); expect(tester.getSize(find.byType(BottomAppBar)), const Size(800, 50)); }); testWidgets('Material3 - BottomAppBar with shape when Scaffold.bottomNavigationBar == null', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/80878 final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: FloatingActionButton( backgroundColor: Colors.green, child: const Icon(Icons.home), onPressed: () {}, ), body: Stack( children: <Widget>[ Container( color: Colors.amber, ), Container( alignment: Alignment.bottomCenter, child: BottomAppBar( color: Colors.green, shape: const CircularNotchedRectangle(), child: Container(height: 50), ), ), ], ), ), ), ); expect(tester.getRect(find.byType(FloatingActionButton)), const Rect.fromLTRB(372, 528, 428, 584)); expect(tester.getSize(find.byType(BottomAppBar)), const Size(800, 80)); }); testWidgets('notch with margin and top padding, home safe area', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/90024 await tester.pumpWidget( const MediaQuery( data: MediaQueryData( padding: EdgeInsets.only(top: 128), ), child: MaterialApp( useInheritedMediaQuery: true, home: SafeArea( child: Scaffold( bottomNavigationBar: ShapeListener( BottomAppBar( shape: RectangularNotch(), notchMargin: 6.0, child: SizedBox(height: 100.0), ), ), floatingActionButton: FloatingActionButton( onPressed: null, child: Icon(Icons.add), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, ), ), ), ), ); final ShapeListenerState shapeListenerState = tester.state(find.byType(ShapeListener)); final RenderBox babBox = tester.renderObject(find.byType(BottomAppBar)); final Size babSize = babBox.size; final RenderBox fabBox = tester.renderObject(find.byType(FloatingActionButton)); final Size fabSize = fabBox.size; final double fabLeft = (babSize.width / 2.0) - (fabSize.width / 2.0) - 6.0; final double fabRight = fabLeft + fabSize.width + 6.0; final double fabBottom = 6.0 + fabSize.height / 2.0; final Path expectedPath = Path() ..moveTo(0.0, 0.0) ..lineTo(fabLeft, 0.0) ..lineTo(fabLeft, fabBottom) ..lineTo(fabRight, fabBottom) ..lineTo(fabRight, 0.0) ..lineTo(babSize.width, 0.0) ..lineTo(babSize.width, babSize.height) ..lineTo(0.0, babSize.height) ..close(); final Path actualPath = shapeListenerState.cache.value; expect( actualPath, coversSameAreaAs( expectedPath, areaToCompare: (Offset.zero & babSize).inflate(5.0), ), ); }); testWidgets('BottomAppBar does not apply custom clipper without FAB', (WidgetTester tester) async { Widget buildWidget({Widget? fab}) { return MaterialApp( home: Scaffold( floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: fab, bottomNavigationBar: BottomAppBar( color: Colors.green, shape: const CircularNotchedRectangle(), child: Container(height: 50), ), ), ); } await tester.pumpWidget(buildWidget(fab: FloatingActionButton(onPressed: () { }))); PhysicalShape physicalShape = tester.widget(find.byType(PhysicalShape).at(0)); expect(physicalShape.clipper.toString(), '_BottomAppBarClipper'); await tester.pumpWidget(buildWidget()); physicalShape = tester.widget(find.byType(PhysicalShape).at(0)); expect(physicalShape.clipper.toString(), 'ShapeBorderClipper'); }); testWidgets('Material3 - BottomAppBar adds bottom padding to height', (WidgetTester tester) async { const double bottomPadding = 35.0; await tester.pumpWidget( MediaQuery( data: const MediaQueryData( padding: EdgeInsets.only(bottom: bottomPadding), viewPadding: EdgeInsets.only(bottom: bottomPadding), ), child: MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( floatingActionButtonLocation: FloatingActionButtonLocation.endContained, floatingActionButton: FloatingActionButton(onPressed: () { }), bottomNavigationBar: BottomAppBar( child: IconButton( icon: const Icon(Icons.search), onPressed: () {}, ), ), ), ), ) ); final Rect bottomAppBar = tester.getRect(find.byType(BottomAppBar)); final Rect iconButton = tester.getRect(find.widgetWithIcon(IconButton, Icons.search)); final Rect fab = tester.getRect(find.byType(FloatingActionButton)); // The height of the bottom app bar should be its height(default is 80.0) + bottom safe area height. expect(bottomAppBar.height, 80.0 + bottomPadding); // The vertical position of the icon button and fab should be center of the area excluding the bottom padding. final double barCenter = bottomAppBar.topLeft.dy + (bottomAppBar.height - bottomPadding) / 2; expect(iconButton.center.dy, barCenter); expect(fab.center.dy, barCenter); }); } // The bottom app bar clip path computation is only available at paint time. // In order to examine the notch path we implement this caching painter which // at paint time looks for a descendant PhysicalShape and caches the // clip path it is using. class ClipCachePainter extends CustomPainter { ClipCachePainter(this.context); late Path value; BuildContext context; @override void paint(Canvas canvas, Size size) { final RenderPhysicalShape physicalShape = findPhysicalShapeChild(context)!; value = physicalShape.clipper!.getClip(size); } RenderPhysicalShape? findPhysicalShapeChild(BuildContext context) { RenderPhysicalShape? result; context.visitChildElements((Element e) { final RenderObject renderObject = e.findRenderObject()!; if (renderObject.runtimeType == RenderPhysicalShape) { assert(result == null); result = renderObject as RenderPhysicalShape; } else { result = findPhysicalShapeChild(e); } }); return result; } @override bool shouldRepaint(ClipCachePainter oldDelegate) { return true; } } class ShapeListener extends StatefulWidget { const ShapeListener(this.child, { super.key }); final Widget child; @override State createState() => ShapeListenerState(); } class ShapeListenerState extends State<ShapeListener> { @override Widget build(BuildContext context) { return CustomPaint( painter: cache, child: widget.child, ); } late ClipCachePainter cache; @override void didChangeDependencies() { super.didChangeDependencies(); cache = ClipCachePainter(context); } } class RectangularNotch extends NotchedShape { const RectangularNotch(); @override Path getOuterPath(Rect host, Rect? guest) { if (guest == null) { return Path()..addRect(host); } return Path() ..moveTo(host.left, host.top) ..lineTo(guest.left, host.top) ..lineTo(guest.left, guest.bottom) ..lineTo(guest.right, guest.bottom) ..lineTo(guest.right, host.top) ..lineTo(host.right, host.top) ..lineTo(host.right, host.bottom) ..lineTo(host.left, host.bottom) ..close(); } }
flutter/packages/flutter/test/material/bottom_app_bar_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/bottom_app_bar_test.dart", "repo_id": "flutter", "token_count": 12880 }
658
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; import 'feedback_tester.dart'; Finder findRenderChipElement() { return find.byElementPredicate((Element e) => '${e.renderObject.runtimeType}' == '_RenderChip'); } RenderBox getMaterialBox(WidgetTester tester) { return tester.firstRenderObject<RenderBox>( find.descendant( of: find.byType(RawChip), matching: find.byType(CustomPaint), ), ); } Material getMaterial(WidgetTester tester) { return tester.widget<Material>( find.descendant( of: find.byType(RawChip), matching: find.byType(Material), ), ); } IconThemeData getIconData(WidgetTester tester) { final IconTheme iconTheme = tester.firstWidget( find.descendant( of: find.byType(RawChip), matching: find.byType(IconTheme), ), ); return iconTheme.data; } DefaultTextStyle getLabelStyle(WidgetTester tester, String labelText) { return tester.widget( find.ancestor( of: find.text(labelText), matching: find.byType(DefaultTextStyle), ).first, ); } dynamic getRenderChip(WidgetTester tester) { if (!tester.any(findRenderChipElement())) { return null; } final Element element = tester.element(findRenderChipElement().first); return element.renderObject; } // ignore: avoid_dynamic_calls double getSelectProgress(WidgetTester tester) => getRenderChip(tester)?.checkmarkAnimation?.value as double; // ignore: avoid_dynamic_calls double getAvatarDrawerProgress(WidgetTester tester) => getRenderChip(tester)?.avatarDrawerAnimation?.value as double; // ignore: avoid_dynamic_calls double getDeleteDrawerProgress(WidgetTester tester) => getRenderChip(tester)?.deleteDrawerAnimation?.value as double; /// Adds the basic requirements for a Chip. Widget wrapForChip({ required Widget child, TextDirection textDirection = TextDirection.ltr, TextScaler textScaler = TextScaler.noScaling, ThemeData? theme, }) { return MaterialApp( theme: theme, home: Directionality( textDirection: textDirection, child: MediaQuery( data: MediaQueryData(textScaler: textScaler), child: Material(child: child), ), ), ); } /// Tests that a [Chip] that has its size constrained by its parent is /// further constraining the size of its child, the label widget. /// Optionally, adding an avatar or delete icon to the chip should not /// cause the chip or label to exceed its constrained height. Future<void> testConstrainedLabel( WidgetTester tester, { CircleAvatar? avatar, VoidCallback? onDeleted, }) async { const double labelWidth = 100.0; const double labelHeight = 50.0; const double chipParentWidth = 75.0; const double chipParentHeight = 25.0; final Key labelKey = UniqueKey(); await tester.pumpWidget( wrapForChip( child: Center( child: SizedBox( width: chipParentWidth, height: chipParentHeight, child: Chip( avatar: avatar, label: SizedBox( key: labelKey, width: labelWidth, height: labelHeight, ), onDeleted: onDeleted, ), ), ), ), ); final Size labelSize = tester.getSize(find.byKey(labelKey)); expect(labelSize.width, lessThan(chipParentWidth)); expect(labelSize.height, lessThanOrEqualTo(chipParentHeight)); final Size chipSize = tester.getSize(find.byType(Chip)); expect(chipSize.width, chipParentWidth); expect(chipSize.height, chipParentHeight); } void doNothing() {} Widget chipWithOptionalDeleteButton({ Key? deleteButtonKey, Key? labelKey, required bool deletable, TextDirection textDirection = TextDirection.ltr, String? chipTooltip, String? deleteButtonTooltipMessage, double? size, VoidCallback? onPressed = doNothing, ThemeData? themeData, }) { return wrapForChip( textDirection: textDirection, theme: themeData, child: Wrap( children: <Widget>[ RawChip( tooltip: chipTooltip, onPressed: onPressed, onDeleted: deletable ? doNothing : null, deleteIcon: Icon( key: deleteButtonKey, size: size, Icons.close, ), deleteButtonTooltipMessage: deleteButtonTooltipMessage, label: Text( deletable ? 'Chip with Delete Button' : 'Chip without Delete Button', key: labelKey, ), ), ], ), ); } bool offsetsAreClose(Offset a, Offset b) => (a - b).distance < 1.0; bool radiiAreClose(double a, double b) => (a - b).abs() < 1.0; // Ripple pattern matches if there exists at least one ripple // with the [expectedCenter] and [expectedRadius]. // This ensures the existence of a ripple. PaintPattern ripplePattern(Offset expectedCenter, double expectedRadius) { return paints ..something((Symbol method, List<dynamic> arguments) { if (method != #drawCircle) { return false; } final Offset center = arguments[0] as Offset; final double radius = arguments[1] as double; return offsetsAreClose(center, expectedCenter) && radiiAreClose(radius, expectedRadius); } ); } // Unique ripple pattern matches if there does not exist ripples // other than ones with the [expectedCenter] and [expectedRadius]. // This ensures the nonexistence of two different ripples. PaintPattern uniqueRipplePattern(Offset expectedCenter, double expectedRadius) { return paints ..everything((Symbol method, List<dynamic> arguments) { if (method != #drawCircle) { return true; } final Offset center = arguments[0] as Offset; final double radius = arguments[1] as double; if (offsetsAreClose(center, expectedCenter) && radiiAreClose(radius, expectedRadius)) { return true; } throw ''' Expected: center == $expectedCenter, radius == $expectedRadius Found: center == $center radius == $radius'''; } ); } // Finds any container of a tooltip. Finder findTooltipContainer(String tooltipText) { return find.ancestor( of: find.text(tooltipText), matching: find.byType(Container), ); } void main() { testWidgets('M2 Chip defaults', (WidgetTester tester) async { late TextTheme textTheme; Widget buildFrame(Brightness brightness) { return MaterialApp( theme: ThemeData(brightness: brightness, useMaterial3: false), home: Scaffold( body: Center( child: Builder( builder: (BuildContext context) { textTheme = Theme.of(context).textTheme; return Chip( avatar: const CircleAvatar(child: Text('A')), label: const Text('Chip A'), onDeleted: () { }, ); }, ), ), ), ); } await tester.pumpWidget(buildFrame(Brightness.light)); expect(getMaterialBox(tester), paints..rrect()..circle(color: const Color(0xff1976d2))); expect(tester.getSize(find.byType(Chip)), const Size(156.0, 48.0)); expect(getMaterial(tester).color, null); expect(getMaterial(tester).elevation, 0); expect(getMaterial(tester).shape, const StadiumBorder()); expect(getIconData(tester).color?.value, 0xffffffff); expect(getIconData(tester).opacity, null); expect(getIconData(tester).size, null); TextStyle labelStyle = getLabelStyle(tester, 'Chip A').style; expect(labelStyle.color?.value, 0xde000000); expect(labelStyle.fontFamily, textTheme.bodyLarge?.fontFamily); expect(labelStyle.fontFamilyFallback, textTheme.bodyLarge?.fontFamilyFallback); expect(labelStyle.fontFeatures, textTheme.bodyLarge?.fontFeatures); expect(labelStyle.fontSize, textTheme.bodyLarge?.fontSize); expect(labelStyle.fontStyle, textTheme.bodyLarge?.fontStyle); expect(labelStyle.fontWeight, textTheme.bodyLarge?.fontWeight); expect(labelStyle.height, textTheme.bodyLarge?.height); expect(labelStyle.inherit, textTheme.bodyLarge?.inherit); expect(labelStyle.leadingDistribution, textTheme.bodyLarge?.leadingDistribution); expect(labelStyle.letterSpacing, textTheme.bodyLarge?.letterSpacing); expect(labelStyle.overflow, textTheme.bodyLarge?.overflow); expect(labelStyle.textBaseline, textTheme.bodyLarge?.textBaseline); expect(labelStyle.wordSpacing, textTheme.bodyLarge?.wordSpacing); await tester.pumpWidget(buildFrame(Brightness.dark)); await tester.pumpAndSettle(); // Theme transition animation expect(getMaterialBox(tester), paints..rrect(color: const Color(0x1fffffff))); expect(tester.getSize(find.byType(Chip)), const Size(156.0, 48.0)); expect(getMaterial(tester).color, null); expect(getMaterial(tester).elevation, 0); expect(getMaterial(tester).shape, const StadiumBorder()); expect(getIconData(tester).color?.value, 0xffffffff); expect(getIconData(tester).opacity, null); expect(getIconData(tester).size, null); labelStyle = getLabelStyle(tester, 'Chip A').style; expect(labelStyle.color?.value, 0xdeffffff); expect(labelStyle.fontFamily, textTheme.bodyLarge?.fontFamily); expect(labelStyle.fontFamilyFallback, textTheme.bodyLarge?.fontFamilyFallback); expect(labelStyle.fontFeatures, textTheme.bodyLarge?.fontFeatures); expect(labelStyle.fontSize, textTheme.bodyLarge?.fontSize); expect(labelStyle.fontStyle, textTheme.bodyLarge?.fontStyle); expect(labelStyle.fontWeight, textTheme.bodyLarge?.fontWeight); expect(labelStyle.height, textTheme.bodyLarge?.height); expect(labelStyle.inherit, textTheme.bodyLarge?.inherit); expect(labelStyle.leadingDistribution, textTheme.bodyLarge?.leadingDistribution); expect(labelStyle.letterSpacing, textTheme.bodyLarge?.letterSpacing); expect(labelStyle.overflow, textTheme.bodyLarge?.overflow); expect(labelStyle.textBaseline, textTheme.bodyLarge?.textBaseline); expect(labelStyle.wordSpacing, textTheme.bodyLarge?.wordSpacing); }); testWidgets('M3 Chip defaults', (WidgetTester tester) async { late TextTheme textTheme; final ThemeData lightTheme = ThemeData.light(); final ThemeData darkTheme = ThemeData.dark(); Widget buildFrame(ThemeData theme) { return MaterialApp( theme: theme, home: Scaffold( body: Center( child: Builder( builder: (BuildContext context) { textTheme = Theme.of(context).textTheme; return Chip( avatar: const CircleAvatar(child: Text('A')), label: const Text('Chip A'), onDeleted: () { }, ); }, ), ), ), ); } await tester.pumpWidget(buildFrame(lightTheme)); expect(getMaterial(tester).color, null); expect(getMaterial(tester).elevation, 0); expect(getMaterial(tester).shape, RoundedRectangleBorder( side: BorderSide(color: lightTheme.colorScheme.outline), borderRadius: BorderRadius.circular(8.0), )); expect(getIconData(tester).color, lightTheme.colorScheme.primary); expect(getIconData(tester).opacity, null); expect(getIconData(tester).size, 18); TextStyle labelStyle = getLabelStyle(tester, 'Chip A').style; expect(labelStyle.color, lightTheme.colorScheme.onSurfaceVariant); expect(labelStyle.fontFamily, textTheme.labelLarge?.fontFamily); expect(labelStyle.fontFamilyFallback, textTheme.labelLarge?.fontFamilyFallback); expect(labelStyle.fontFeatures, textTheme.labelLarge?.fontFeatures); expect(labelStyle.fontSize, textTheme.labelLarge?.fontSize); expect(labelStyle.fontStyle, textTheme.labelLarge?.fontStyle); expect(labelStyle.fontWeight, textTheme.labelLarge?.fontWeight); expect(labelStyle.height, textTheme.labelLarge?.height); expect(labelStyle.inherit, textTheme.labelLarge?.inherit); expect(labelStyle.leadingDistribution, textTheme.labelLarge?.leadingDistribution); expect(labelStyle.letterSpacing, textTheme.labelLarge?.letterSpacing); expect(labelStyle.overflow, textTheme.labelLarge?.overflow); expect(labelStyle.textBaseline, textTheme.labelLarge?.textBaseline); expect(labelStyle.wordSpacing, textTheme.labelLarge?.wordSpacing); await tester.pumpWidget(buildFrame(darkTheme)); await tester.pumpAndSettle(); // Theme transition animation expect(getMaterial(tester).color, null); expect(getMaterial(tester).elevation, 0); expect(getMaterial(tester).shape, RoundedRectangleBorder( side: BorderSide(color: darkTheme.colorScheme.outline), borderRadius: BorderRadius.circular(8.0), )); expect(getIconData(tester).color, darkTheme.colorScheme.primary); expect(getIconData(tester).opacity, null); expect(getIconData(tester).size, 18); labelStyle = getLabelStyle(tester, 'Chip A').style; expect(labelStyle.color, darkTheme.colorScheme.onSurfaceVariant); expect(labelStyle.fontFamily, textTheme.labelLarge?.fontFamily); expect(labelStyle.fontFamilyFallback, textTheme.labelLarge?.fontFamilyFallback); expect(labelStyle.fontFeatures, textTheme.labelLarge?.fontFeatures); expect(labelStyle.fontSize, textTheme.labelLarge?.fontSize); expect(labelStyle.fontStyle, textTheme.labelLarge?.fontStyle); expect(labelStyle.fontWeight, textTheme.labelLarge?.fontWeight); expect(labelStyle.height, textTheme.labelLarge?.height); expect(labelStyle.inherit, textTheme.labelLarge?.inherit); expect(labelStyle.leadingDistribution, textTheme.labelLarge?.leadingDistribution); expect(labelStyle.letterSpacing, textTheme.labelLarge?.letterSpacing); expect(labelStyle.overflow, textTheme.labelLarge?.overflow); expect(labelStyle.textBaseline, textTheme.labelLarge?.textBaseline); expect(labelStyle.wordSpacing, textTheme.labelLarge?.wordSpacing); }); testWidgets('Chip control test', (WidgetTester tester) async { final FeedbackTester feedback = FeedbackTester(); final List<String> deletedChipLabels = <String>[]; await tester.pumpWidget( wrapForChip( child: Column( children: <Widget>[ Chip( avatar: const CircleAvatar(child: Text('A')), label: const Text('Chip A'), onDeleted: () { deletedChipLabels.add('A'); }, deleteButtonTooltipMessage: 'Delete chip A', ), Chip( avatar: const CircleAvatar(child: Text('B')), label: const Text('Chip B'), onDeleted: () { deletedChipLabels.add('B'); }, deleteButtonTooltipMessage: 'Delete chip B', ), ], ), ), ); expect(tester.widget(find.byTooltip('Delete chip A')), isNotNull); expect(tester.widget(find.byTooltip('Delete chip B')), isNotNull); expect(feedback.clickSoundCount, 0); expect(deletedChipLabels, isEmpty); await tester.tap(find.byTooltip('Delete chip A')); expect(deletedChipLabels, equals(<String>['A'])); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 1); await tester.tap(find.byTooltip('Delete chip B')); expect(deletedChipLabels, equals(<String>['A', 'B'])); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 2); feedback.dispose(); }); testWidgets( 'Chip does not constrain size of label widget if it does not exceed ' 'the available space', (WidgetTester tester) async { const double labelWidth = 50.0; const double labelHeight = 30.0; final Key labelKey = UniqueKey(); await tester.pumpWidget( wrapForChip( child: Center( child: SizedBox( width: 500.0, height: 500.0, child: Column( children: <Widget>[ Chip( label: SizedBox( key: labelKey, width: labelWidth, height: labelHeight, ), ), ], ), ), ), ), ); final Size labelSize = tester.getSize(find.byKey(labelKey)); expect(labelSize.width, labelWidth); expect(labelSize.height, labelHeight); }, ); testWidgets( 'Chip constrains the size of the label widget when it exceeds the ' 'available space', (WidgetTester tester) async { await testConstrainedLabel(tester); }, ); testWidgets( 'Chip constrains the size of the label widget when it exceeds the ' 'available space and the avatar is present', (WidgetTester tester) async { await testConstrainedLabel( tester, avatar: const CircleAvatar(child: Text('A')), ); }, ); testWidgets( 'Chip constrains the size of the label widget when it exceeds the ' 'available space and the delete icon is present', (WidgetTester tester) async { await testConstrainedLabel( tester, onDeleted: () { }, ); }, ); testWidgets( 'Chip constrains the size of the label widget when it exceeds the ' 'available space and both avatar and delete icons are present', (WidgetTester tester) async { await testConstrainedLabel( tester, avatar: const CircleAvatar(child: Text('A')), onDeleted: () { }, ); }, ); testWidgets( 'Chip constrains the avatar, label, and delete icons to the bounds of ' 'the chip when it exceeds the available space', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/11523 Widget chipBuilder (String text, {Widget? avatar, VoidCallback? onDeleted}) { return MaterialApp( home: Scaffold( body: SizedBox( width: 150, child: Column( children: <Widget>[ Chip( avatar: avatar, label: Text(text), onDeleted: onDeleted, ), ], ), ), ), ); } void chipRectContains(Rect chipRect, Rect rect) { expect(chipRect.contains(rect.topLeft), true); expect(chipRect.contains(rect.topRight), true); expect(chipRect.contains(rect.bottomLeft), true); expect(chipRect.contains(rect.bottomRight), true); } Rect chipRect; Rect avatarRect; Rect labelRect; Rect deleteIconRect; const String text = 'Very long text that will be clipped'; await tester.pumpWidget(chipBuilder(text)); chipRect = tester.getRect(find.byType(Chip)); labelRect = tester.getRect(find.text(text)); chipRectContains(chipRect, labelRect); await tester.pumpWidget(chipBuilder( text, avatar: const CircleAvatar(child: Text('A')), )); await tester.pumpAndSettle(); chipRect = tester.getRect(find.byType(Chip)); avatarRect = tester.getRect(find.byType(CircleAvatar)); chipRectContains(chipRect, avatarRect); labelRect = tester.getRect(find.text(text)); chipRectContains(chipRect, labelRect); await tester.pumpWidget(chipBuilder( text, avatar: const CircleAvatar(child: Text('A')), onDeleted: () {}, )); await tester.pumpAndSettle(); chipRect = tester.getRect(find.byType(Chip)); avatarRect = tester.getRect(find.byType(CircleAvatar)); chipRectContains(chipRect, avatarRect); labelRect = tester.getRect(find.text(text)); chipRectContains(chipRect, labelRect); deleteIconRect = tester.getRect(find.byIcon(Icons.cancel)); chipRectContains(chipRect, deleteIconRect); }, ); testWidgets('Material2 - Chip in row works ok', (WidgetTester tester) async { const TextStyle style = TextStyle(fontSize: 10.0); await tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: const Row( children: <Widget>[ Chip(label: Text('Test'), labelStyle: style), ], ), ), ); expect(tester.getSize(find.byType(Text)), const Size(40.0, 10.0)); expect(tester.getSize(find.byType(Chip)), const Size(64.0, 48.0)); await tester.pumpWidget( wrapForChip( child: const Row( children: <Widget>[ Flexible(child: Chip(label: Text('Test'), labelStyle: style)), ], ), ), ); expect(tester.getSize(find.byType(Text)), const Size(40.0, 10.0)); expect(tester.getSize(find.byType(Chip)), const Size(64.0, 48.0)); await tester.pumpWidget( wrapForChip( child: const Row( children: <Widget>[ Expanded(child: Chip(label: Text('Test'), labelStyle: style)), ], ), ), ); expect(tester.getSize(find.byType(Text)), const Size(40.0, 10.0)); expect(tester.getSize(find.byType(Chip)), const Size(800.0, 48.0)); }); testWidgets('Material3 - Chip in row works ok', (WidgetTester tester) async { const TextStyle style = TextStyle(fontSize: 10.0); await tester.pumpWidget( wrapForChip( child: const Row( children: <Widget>[ Chip(label: Text('Test'), labelStyle: style), ], ), ), ); expect(tester.getSize(find.byType(Text)).width, closeTo(40.4, 0.01)); expect(tester.getSize(find.byType(Text)).height, equals(14.0)); expect(tester.getSize(find.byType(Chip)).width, closeTo(74.4, 0.01)); expect(tester.getSize(find.byType(Chip)).height, equals(48.0)); await tester.pumpWidget( wrapForChip( child: const Row( children: <Widget>[ Flexible(child: Chip(label: Text('Test'), labelStyle: style)), ], ), ), ); expect(tester.getSize(find.byType(Text)).width, closeTo(40.4, 0.01)); expect(tester.getSize(find.byType(Text)).height, equals(14.0)); expect(tester.getSize(find.byType(Chip)).width, closeTo(74.4, 0.01)); expect(tester.getSize(find.byType(Chip)).height, equals(48.0)); await tester.pumpWidget( wrapForChip( child: const Row( children: <Widget>[ Expanded(child: Chip(label: Text('Test'), labelStyle: style)), ], ), ), ); expect(tester.getSize(find.byType(Text)).width, closeTo(40.4, 0.01)); expect(tester.getSize(find.byType(Text)).height, equals(14.0)); expect(tester.getSize(find.byType(Chip)), const Size(800.0, 48.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Material2 - Chip responds to materialTapTargetSize', (WidgetTester tester) async { await tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: const Column( children: <Widget>[ Chip( label: Text('X'), materialTapTargetSize: MaterialTapTargetSize.padded, ), Chip( label: Text('X'), materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, ), ], ), ), ); expect(tester.getSize(find.byType(Chip).first), const Size(48.0, 48.0)); expect(tester.getSize(find.byType(Chip).last), const Size(38.0, 32.0)); }); testWidgets('Material3 - Chip responds to materialTapTargetSize', (WidgetTester tester) async { await tester.pumpWidget( wrapForChip( child: const Column( children: <Widget>[ Chip( label: Text('X'), materialTapTargetSize: MaterialTapTargetSize.padded, ), Chip( label: Text('X'), materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, ), ], ), ), ); expect(tester.getSize(find.byType(Chip).first).width, closeTo(48.1, 0.01)); expect(tester.getSize(find.byType(Chip).first).height, equals(48.0)); expect(tester.getSize(find.byType(Chip).last).width, closeTo(48.1, 0.01)); expect(tester.getSize(find.byType(Chip).last).height, equals(38.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Delete button tap target is the right proportion of the chip', (WidgetTester tester) async { final UniqueKey deleteKey = UniqueKey(); bool calledDelete = false; await tester.pumpWidget( wrapForChip( child: Column( children: <Widget>[ Chip( label: const Text('Really Long Label'), deleteIcon: Icon(Icons.delete, key: deleteKey), onDeleted: () { calledDelete = true; }, ), ], ), ), ); // Test correct tap target size. await tester.tapAt(tester.getCenter(find.byKey(deleteKey)) - const Offset(18.0, 0.0)); // Half the width of the delete button + right label padding. await tester.pump(); expect(calledDelete, isTrue); calledDelete = false; // Test incorrect tap target size. await tester.tapAt(tester.getCenter(find.byKey(deleteKey)) - const Offset(19.0, 0.0)); await tester.pump(); expect(calledDelete, isFalse); calledDelete = false; await tester.pumpWidget( wrapForChip( child: Column( children: <Widget>[ Chip( label: const SizedBox(), // Short label deleteIcon: Icon(Icons.cancel, key: deleteKey), onDeleted: () { calledDelete = true; }, ), ], ), ), ); // Chip width is 48 with padding, 40 without padding, so halfway is at 20. Cancel // icon is 24x24, so since 24 > 20 the split location should be halfway across the // chip, which is at 12 + 8 = 20 from the right side. Since the split is just // slightly less than 50%, 8 from the center of the delete button should hit the // chip, not the delete button. await tester.tapAt(tester.getCenter(find.byKey(deleteKey)) - const Offset(7.0, 0.0)); await tester.pump(); expect(calledDelete, isTrue); calledDelete = false; await tester.tapAt(tester.getCenter(find.byKey(deleteKey)) - const Offset(8.0, 0.0)); await tester.pump(); expect(calledDelete, isFalse); }); testWidgets('Chip elements are ordered horizontally for locale', (WidgetTester tester) async { final UniqueKey iconKey = UniqueKey(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); final Widget test = Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Material( child: Chip( deleteIcon: Icon(Icons.delete, key: iconKey), onDeleted: () { }, label: const Text('ABC'), ), ); }, ), ], ); await tester.pumpWidget( wrapForChip( child: test, textDirection: TextDirection.rtl, ), ); await tester.pumpAndSettle(const Duration(milliseconds: 500)); expect(tester.getCenter(find.text('ABC')).dx, greaterThan(tester.getCenter(find.byKey(iconKey)).dx)); await tester.pumpWidget( wrapForChip( child: test, ), ); await tester.pumpAndSettle(const Duration(milliseconds: 500)); expect(tester.getCenter(find.text('ABC')).dx, lessThan(tester.getCenter(find.byKey(iconKey)).dx)); }); testWidgets('Material2 - Chip responds to textScaleFactor', (WidgetTester tester) async { await tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: const Column( children: <Widget>[ Chip( avatar: CircleAvatar(child: Text('A')), label: Text('Chip A'), ), Chip( avatar: CircleAvatar(child: Text('B')), label: Text('Chip B'), ), ], ), ), ); expect( tester.getSize(find.text('Chip A')), const Size(84.0, 14.0), ); expect( tester.getSize(find.text('Chip B')), const Size(84.0, 14.0), ); expect(tester.getSize(find.byType(Chip).first), const Size(132.0, 48.0)); expect(tester.getSize(find.byType(Chip).last), const Size(132.0, 48.0)); await tester.pumpWidget( wrapForChip( textScaler: const TextScaler.linear(3.0), child: const Column( children: <Widget>[ Chip( avatar: CircleAvatar(child: Text('A')), label: Text('Chip A'), ), Chip( avatar: CircleAvatar(child: Text('B')), label: Text('Chip B'), ), ], ), ), ); expect(tester.getSize(find.text('Chip A')), const Size(252.0, 42.0)); expect(tester.getSize(find.text('Chip B')), const Size(252.0, 42.0)); expect(tester.getSize(find.byType(Chip).first), const Size(310.0, 50.0)); expect(tester.getSize(find.byType(Chip).last), const Size(310.0, 50.0)); // Check that individual text scales are taken into account. await tester.pumpWidget( wrapForChip( child: const Column( children: <Widget>[ Chip( avatar: CircleAvatar(child: Text('A')), label: Text('Chip A', textScaleFactor: 3.0), ), Chip( avatar: CircleAvatar(child: Text('B')), label: Text('Chip B'), ), ], ), ), ); expect(tester.getSize(find.text('Chip A')), const Size(252.0, 42.0)); expect(tester.getSize(find.text('Chip B')), const Size(84.0, 14.0)); expect(tester.getSize(find.byType(Chip).first), const Size(318.0, 50.0)); expect(tester.getSize(find.byType(Chip).last), const Size(132.0, 48.0)); }); testWidgets('Material3 - Chip responds to textScaleFactor', (WidgetTester tester) async { await tester.pumpWidget( wrapForChip( child: const Column( children: <Widget>[ Chip( avatar: CircleAvatar(child: Text('A')), label: Text('Chip A'), ), Chip( avatar: CircleAvatar(child: Text('B')), label: Text('Chip B'), ), ], ), ), ); expect(tester.getSize(find.text('Chip A')).width, closeTo(84.5, 0.1)); expect(tester.getSize(find.text('Chip A')).height, equals(20.0)); expect(tester.getSize(find.text('Chip B')).width, closeTo(84.5, 0.1)); expect(tester.getSize(find.text('Chip B')).height, equals(20.0)); await tester.pumpWidget( wrapForChip( textScaler: const TextScaler.linear(3.0), child: const Column( children: <Widget>[ Chip( avatar: CircleAvatar(child: Text('A')), label: Text('Chip A'), ), Chip( avatar: CircleAvatar(child: Text('B')), label: Text('Chip B'), ), ], ), ), ); expect(tester.getSize(find.text('Chip A')).width, closeTo(252.6, 0.1)); expect(tester.getSize(find.text('Chip A')).height, equals(60.0)); expect(tester.getSize(find.text('Chip B')).width, closeTo(252.6, 0.1)); expect(tester.getSize(find.text('Chip B')).height, equals(60.0)); expect(tester.getSize(find.byType(Chip).first).width, closeTo(338.6, 0.1)); expect(tester.getSize(find.byType(Chip).first).height, equals(78.0)); expect(tester.getSize(find.byType(Chip).last).width, closeTo(338.6, 0.1)); expect(tester.getSize(find.byType(Chip).last).height, equals(78.0)); // Check that individual text scales are taken into account. await tester.pumpWidget( wrapForChip( child: const Column( children: <Widget>[ Chip( avatar: CircleAvatar(child: Text('A')), label: Text('Chip A', textScaleFactor: 3.0), ), Chip( avatar: CircleAvatar(child: Text('B')), label: Text('Chip B'), ), ], ), ), ); expect(tester.getSize(find.text('Chip A')).width, closeTo(252.6, 0.01)); expect(tester.getSize(find.text('Chip A')).height, equals(60.0)); expect(tester.getSize(find.text('Chip B')).width, closeTo(84.59, 0.01)); expect(tester.getSize(find.text('Chip B')).height, equals(20.0)); expect(tester.getSize(find.byType(Chip).first).width, closeTo(346.6, 0.01)); expect(tester.getSize(find.byType(Chip).first).height, equals(78.0)); expect(tester.getSize(find.byType(Chip).last).width, closeTo(138.59, 0.01)); expect(tester.getSize(find.byType(Chip).last).height, equals(48.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Material2 - Labels can be non-text widgets', (WidgetTester tester) async { final Key keyA = GlobalKey(); final Key keyB = GlobalKey(); await tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: Column( children: <Widget>[ Chip( avatar: const CircleAvatar(child: Text('A')), label: Text('Chip A', key: keyA), ), Chip( avatar: const CircleAvatar(child: Text('B')), label: SizedBox(key: keyB, width: 10.0, height: 10.0), ), ], ), ), ); expect(tester.getSize(find.byKey(keyA)), const Size(84.0, 14.0)); expect(tester.getSize(find.byKey(keyB)), const Size(10.0, 10.0)); expect(tester.getSize(find.byType(Chip).first), const Size(132.0, 48.0)); expect(tester.getSize(find.byType(Chip).last), const Size(58.0, 48.0)); }); testWidgets('Material3 - Labels can be non-text widgets', (WidgetTester tester) async { final Key keyA = GlobalKey(); final Key keyB = GlobalKey(); await tester.pumpWidget( wrapForChip( child: Column( children: <Widget>[ Chip( avatar: const CircleAvatar(child: Text('A')), label: Text('Chip A', key: keyA), ), Chip( avatar: const CircleAvatar(child: Text('B')), label: SizedBox(key: keyB, width: 10.0, height: 10.0), ), ], ), ), ); expect(tester.getSize(find.byKey(keyA)).width, moreOrLessEquals(84.5, epsilon: 0.1)); expect(tester.getSize(find.byKey(keyA)).height, equals(20.0)); expect(tester.getSize(find.byKey(keyB)), const Size(10.0, 10.0)); expect(tester.getSize(find.byType(Chip).first).width, moreOrLessEquals(138.5, epsilon: 0.1)); expect(tester.getSize(find.byType(Chip).first).height, equals(48.0)); expect(tester.getSize(find.byType(Chip).last), const Size(60.0, 48.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Avatars can be non-circle avatar widgets', (WidgetTester tester) async { final Key keyA = GlobalKey(); await tester.pumpWidget( wrapForChip( child: Column( children: <Widget>[ Chip( avatar: SizedBox(key: keyA, width: 20.0, height: 20.0), label: const Text('Chip A'), ), ], ), ), ); expect(tester.getSize(find.byKey(keyA)), equals(const Size(20.0, 20.0))); }); testWidgets('Delete icons can be non-icon widgets', (WidgetTester tester) async { final Key keyA = GlobalKey(); await tester.pumpWidget( wrapForChip( child: Column( children: <Widget>[ Chip( deleteIcon: SizedBox(key: keyA, width: 20.0, height: 20.0), label: const Text('Chip A'), onDeleted: () { }, ), ], ), ), ); expect(tester.getSize(find.byKey(keyA)), equals(const Size(20.0, 20.0))); }); testWidgets('Chip padding - LTR', (WidgetTester tester) async { final GlobalKey keyA = GlobalKey(); final GlobalKey keyB = GlobalKey(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( wrapForChip( child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Material( child: Center( child: Chip( avatar: Placeholder(key: keyA), label: SizedBox( key: keyB, width: 40.0, height: 40.0, ), onDeleted: () { }, ), ), ); }, ), ], ), ), ); expect(tester.getTopLeft(find.byKey(keyA)), const Offset(332.0, 280.0)); expect(tester.getBottomRight(find.byKey(keyA)), const Offset(372.0, 320.0)); expect(tester.getTopLeft(find.byKey(keyB)), const Offset(380.0, 280.0)); expect(tester.getBottomRight(find.byKey(keyB)), const Offset(420.0, 320.0)); expect(tester.getTopLeft(find.byType(Icon)), const Offset(439.0, 291.0)); expect(tester.getBottomRight(find.byType(Icon)), const Offset(457.0, 309.0)); }); testWidgets('Chip padding - RTL', (WidgetTester tester) async { final GlobalKey keyA = GlobalKey(); final GlobalKey keyB = GlobalKey(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( wrapForChip( textDirection: TextDirection.rtl, child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Material( child: Center( child: Chip( avatar: Placeholder(key: keyA), label: SizedBox( key: keyB, width: 40.0, height: 40.0, ), onDeleted: () { }, ), ), ); }, ), ], ), ), ); expect(tester.getTopLeft(find.byKey(keyA)), const Offset(428.0, 280.0)); expect(tester.getBottomRight(find.byKey(keyA)), const Offset(468.0, 320.0)); expect(tester.getTopLeft(find.byKey(keyB)), const Offset(380.0, 280.0)); expect(tester.getBottomRight(find.byKey(keyB)), const Offset(420.0, 320.0)); expect(tester.getTopLeft(find.byType(Icon)), const Offset(343.0, 291.0)); expect(tester.getBottomRight(find.byType(Icon)), const Offset(361.0, 309.0)); }); testWidgets('Material2 - Avatar drawer works as expected on RawChip', (WidgetTester tester) async { final GlobalKey labelKey = GlobalKey(); Future<void> pushChip({ Widget? avatar }) async { return tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: Wrap( children: <Widget>[ RawChip( avatar: avatar, label: Text('Chip', key: labelKey), shape: const StadiumBorder(), ), ], ), ), ); } // No avatar await pushChip(); expect(tester.getSize(find.byType(RawChip)), equals(const Size(80.0, 48.0))); final GlobalKey avatarKey = GlobalKey(); // Add an avatar await pushChip( avatar: Container( key: avatarKey, color: const Color(0xff000000), width: 40.0, height: 40.0, ), ); // Avatar drawer should start out closed. expect(tester.getSize(find.byType(RawChip)), equals(const Size(80.0, 48.0))); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)), equals(const Offset(-20.0, 12.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(12.0, 17.0))); await tester.pump(const Duration(milliseconds: 20)); // Avatar drawer should start expanding. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(81.2, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-18.8, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(13.2, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(86.7, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-13.3, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(18.6, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(94.7, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-5.3, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(26.7, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(99.5, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-0.5, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(31.5, epsilon: 0.1)); // Wait for being done with animation, and make sure it didn't change // height. await tester.pumpAndSettle(const Duration(milliseconds: 200)); expect(tester.getSize(find.byType(RawChip)), equals(const Size(104.0, 48.0))); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)), equals(const Offset(4.0, 12.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(36.0, 17.0))); // Remove the avatar again await pushChip(); // Avatar drawer should start out open. expect(tester.getSize(find.byType(RawChip)), equals(const Size(104.0, 48.0))); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)), equals(const Offset(4.0, 12.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(36.0, 17.0))); await tester.pump(const Duration(milliseconds: 20)); // Avatar drawer should start contracting. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(102.9, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(2.9, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(34.9, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(98.0, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-2.0, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(30.0, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(84.1, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-15.9, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(16.1, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(80.0, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-20.0, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(12.0, epsilon: 0.1)); // Wait for being done with animation, make sure it didn't change // height, and make sure that the avatar is no longer drawn. await tester.pumpAndSettle(const Duration(milliseconds: 200)); expect(tester.getSize(find.byType(RawChip)), equals(const Size(80.0, 48.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(12.0, 17.0))); expect(find.byKey(avatarKey), findsNothing); }); testWidgets('Material3 - Avatar drawer works as expected on RawChip', (WidgetTester tester) async { final GlobalKey labelKey = GlobalKey(); Future<void> pushChip({ Widget? avatar }) async { return tester.pumpWidget( wrapForChip( child: Wrap( children: <Widget>[ RawChip( avatar: avatar, label: Text('Chip', key: labelKey), shape: const StadiumBorder(), ), ], ), ), ); } // No avatar await pushChip(); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(90.4, epsilon: 0.1)); final GlobalKey avatarKey = GlobalKey(); // Add an avatar await pushChip( avatar: Container( key: avatarKey, color: const Color(0xff000000), width: 40.0, height: 40.0, ), ); // Avatar drawer should start out closed. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(90.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)), equals(const Offset(-11.0, 14.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(17.0, 14.0))); await tester.pump(const Duration(milliseconds: 20)); // Avatar drawer should start expanding. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(91.3, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-10, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(17.9, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(95.9, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-5.4, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(22.5, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(102.6, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(1.2, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(29.2, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(106.6, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(5.2, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(33.2, epsilon: 0.1)); // Wait for being done with animation, and make sure it didn't change // height. await tester.pumpAndSettle(const Duration(milliseconds: 200)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(110.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)), equals(const Offset(9.0, 14.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(37.0, 14.0))); // Remove the avatar again await pushChip(); // Avatar drawer should start out open. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(110.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)), equals(const Offset(9.0, 14.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(37.0, 14.0))); await tester.pump(const Duration(milliseconds: 20)); // Avatar drawer should start contracting. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(109.5, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(8.1, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(36.1, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(105.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(4.0, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(32.0, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(93.7, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-7.6, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(20.3, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(90.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(avatarKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(avatarKey)).dx, moreOrLessEquals(-11.0, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)).dx, moreOrLessEquals(17.0, epsilon: 0.1)); // Wait for being done with animation, make sure it didn't change // height, and make sure that the avatar is no longer drawn. await tester.pumpAndSettle(const Duration(milliseconds: 200)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(90.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(17.0, 14.0))); expect(find.byKey(avatarKey), findsNothing); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Material2 - Delete button drawer works as expected on RawChip', (WidgetTester tester) async { const Key labelKey = Key('label'); const Key deleteButtonKey = Key('delete'); bool wasDeleted = false; Future<void> pushChip({ bool deletable = false }) async { return tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: Wrap( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( onDeleted: deletable ? () { setState(() { wasDeleted = true; }); } : null, deleteIcon: Container(width: 40.0, height: 40.0, color: Colors.blue, key: deleteButtonKey), label: const Text('Chip', key: labelKey), shape: const StadiumBorder(), ); }), ], ), ), ); } // No delete button await pushChip(); expect(tester.getSize(find.byType(RawChip)), equals(const Size(80.0, 48.0))); // Add a delete button await pushChip(deletable: true); // Delete button drawer should start out closed. expect(tester.getSize(find.byType(RawChip)), equals(const Size(80.0, 48.0))); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)), equals(const Offset(52.0, 12.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(12.0, 17.0))); await tester.pump(const Duration(milliseconds: 20)); // Delete button drawer should start expanding. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(81.2, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(53.2, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(12.0, 17.0))); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(86.7, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(58.7, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(94.7, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(66.7, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(99.5, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(71.5, epsilon: 0.1)); // Wait for being done with animation, and make sure it didn't change // height. await tester.pumpAndSettle(const Duration(milliseconds: 200)); expect(tester.getSize(find.byType(RawChip)), equals(const Size(104.0, 48.0))); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)), equals(const Offset(76.0, 12.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(12.0, 17.0))); // Test the tap work for the delete button, but not the rest of the chip. expect(wasDeleted, isFalse); await tester.tap(find.byKey(labelKey)); expect(wasDeleted, isFalse); await tester.tap(find.byKey(deleteButtonKey)); expect(wasDeleted, isTrue); // Remove the delete button again await pushChip(); // Delete button drawer should start out open. expect(tester.getSize(find.byType(RawChip)), equals(const Size(104.0, 48.0))); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)), equals(const Offset(76.0, 12.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(12.0, 17.0))); await tester.pump(const Duration(milliseconds: 20)); // Delete button drawer should start contracting. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(103.8, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(75.8, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(12.0, 17.0))); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(102.9, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(74.9, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(101.0, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(73.0, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(97.5, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(24.0, 24.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(69.5, epsilon: 0.1)); // Wait for being done with animation, make sure it didn't change // height, and make sure that the delete button is no longer drawn. await tester.pumpAndSettle(const Duration(milliseconds: 200)); expect(tester.getSize(find.byType(RawChip)), equals(const Size(80.0, 48.0))); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(12.0, 17.0))); expect(find.byKey(deleteButtonKey), findsNothing); }); testWidgets('Material3 - Delete button drawer works as expected on RawChip', (WidgetTester tester) async { const Key labelKey = Key('label'); const Key deleteButtonKey = Key('delete'); bool wasDeleted = false; Future<void> pushChip({ bool deletable = false }) async { return tester.pumpWidget( wrapForChip( child: Wrap( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( onDeleted: deletable ? () { setState(() { wasDeleted = true; }); } : null, deleteIcon: Container(width: 40.0, height: 40.0, color: Colors.blue, key: deleteButtonKey), label: const Text('Chip', key: labelKey), shape: const StadiumBorder(), ); }), ], ), ), ); } // No delete button await pushChip(); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(90.4, epsilon: 0.01)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); // Add a delete button await pushChip(deletable: true); // Delete button drawer should start out closed. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(90.4, epsilon: 0.01)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft( find.byKey(deleteButtonKey)), offsetMoreOrLessEquals(const Offset(61.4, 14.0), epsilon: 0.01), ); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(17.0, 14.0))); await tester.pump(const Duration(milliseconds: 20)); // Delete button drawer should start expanding. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(91.3, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(62.3, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(17.0, 14.0))); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(95.9, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(66.9, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(102.6, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(73.6, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(106.6, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(77.6, epsilon: 0.1)); // Wait for being done with animation, and make sure it didn't change // height. await tester.pumpAndSettle(const Duration(milliseconds: 200)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(110.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect( tester.getTopLeft(find.byKey(deleteButtonKey)), offsetMoreOrLessEquals(const Offset(81.4, 14.0), epsilon: 0.01), ); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(17.0, 14.0))); // Test the tap work for the delete button, but not the rest of the chip. expect(wasDeleted, isFalse); await tester.tap(find.byKey(labelKey)); expect(wasDeleted, isFalse); await tester.tap(find.byKey(deleteButtonKey)); expect(wasDeleted, isTrue); // Remove the delete button again await pushChip(); // Delete button drawer should start out open. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(110.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect( tester.getTopLeft(find.byKey(deleteButtonKey)), offsetMoreOrLessEquals(const Offset(81.4, 14.0), epsilon: 0.01), ); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(17.0, 14.0))); await tester.pump(const Duration(milliseconds: 20)); // Delete button drawer should start contracting. expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(110.1, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(81.1, epsilon: 0.1)); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(17.0, 14.0))); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(109.4, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(80.4, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(107.9, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(78.9, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 20)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(104.9, epsilon: 0.1)); expect(tester.getSize(find.byKey(deleteButtonKey)), equals(const Size(20.0, 20.0))); expect(tester.getTopLeft(find.byKey(deleteButtonKey)).dx, moreOrLessEquals(75.9, epsilon: 0.1)); // Wait for being done with animation, make sure it didn't change // height, and make sure that the delete button is no longer drawn. await tester.pumpAndSettle(const Duration(milliseconds: 200)); expect(tester.getSize(find.byType(RawChip)).width, moreOrLessEquals(90.4, epsilon: 0.1)); expect(tester.getSize(find.byType(RawChip)).height, equals(48.0)); expect(tester.getTopLeft(find.byKey(labelKey)), equals(const Offset(17.0, 14.0))); expect(find.byKey(deleteButtonKey), findsNothing); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Delete button takes up at most half of the chip', (WidgetTester tester) async { final UniqueKey chipKey = UniqueKey(); bool chipPressed = false; bool deletePressed = false; await tester.pumpWidget( wrapForChip( child: Wrap( children: <Widget>[ RawChip( key: chipKey, onPressed: () { chipPressed = true; }, onDeleted: () { deletePressed = true; }, label: const Text(''), ), ], ), ), ); await tester.tapAt(tester.getCenter(find.byKey(chipKey))); await tester.pump(); expect(chipPressed, isTrue); expect(deletePressed, isFalse); chipPressed = false; await tester.tapAt(tester.getCenter(find.byKey(chipKey)) + const Offset(1.0, 0.0)); await tester.pump(); expect(chipPressed, isFalse); expect(deletePressed, isTrue); }); testWidgets('Material2 - Chip creates centered, unique ripple when label is tapped', (WidgetTester tester) async { final UniqueKey labelKey = UniqueKey(); final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( themeData: ThemeData(useMaterial3: false), labelKey: labelKey, deleteButtonKey: deleteButtonKey, deletable: true, ), ); final RenderBox box = getMaterialBox(tester); // Taps at a location close to the center of the label. final Offset centerOfLabel = tester.getCenter(find.byKey(labelKey)); final Offset tapLocationOfLabel = centerOfLabel + const Offset(-10, -10); final TestGesture gesture = await tester.startGesture(tapLocationOfLabel); await tester.pump(); // Waits for 100 ms. await tester.pump(const Duration(milliseconds: 100)); // There should be one unique, centered ink ripple. expect(box, ripplePattern(const Offset(163.0, 6.0), 20.9)); expect(box, uniqueRipplePattern(const Offset(163.0, 6.0), 20.9)); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for 100 ms again. await tester.pump(const Duration(milliseconds: 100)); // The ripple should grow, with the same center. expect(box, ripplePattern(const Offset(163.0, 6.0), 41.8)); expect(box, uniqueRipplePattern(const Offset(163.0, 6.0), 41.8)); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for a very long time. await tester.pumpAndSettle(); // There should still be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); await gesture.up(); }); testWidgets('Material3 - Chip creates centered, unique sparkle when label is tapped', (WidgetTester tester) async { final UniqueKey labelKey = UniqueKey(); final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( labelKey: labelKey, deleteButtonKey: deleteButtonKey, deletable: true, ), ); // Taps at a location close to the center of the label. final Offset centerOfLabel = tester.getCenter(find.byKey(labelKey)); final Offset tapLocationOfLabel = centerOfLabel + const Offset(-10, -10); final TestGesture gesture = await tester.startGesture(tapLocationOfLabel); await tester.pump(); // Waits for 100 ms. await tester.pump(const Duration(milliseconds: 100)); // There should be one unique, centered ink sparkle. await expectLater(find.byType(RawChip), matchesGoldenFile('chip.label_tapped.ink_sparkle.0.png')); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for 100 ms again. await tester.pump(const Duration(milliseconds: 100)); // The sparkle should grow, with the same center. await expectLater(find.byType(RawChip), matchesGoldenFile('chip.label_tapped.ink_sparkle.1.png')); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for a very long time. await tester.pumpAndSettle(); // There should still be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); await gesture.up(); }); testWidgets('Delete button is focusable', (WidgetTester tester) async { final GlobalKey labelKey = GlobalKey(); final GlobalKey deleteButtonKey = GlobalKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( labelKey: labelKey, deleteButtonKey: deleteButtonKey, deletable: true, ), ); Focus.of(deleteButtonKey.currentContext!).requestFocus(); await tester.pump(); // They shouldn't have the same focus node. expect(Focus.of(deleteButtonKey.currentContext!), isNot(equals(Focus.of(labelKey.currentContext!)))); expect(Focus.of(deleteButtonKey.currentContext!).hasFocus, isTrue); expect(Focus.of(deleteButtonKey.currentContext!).hasPrimaryFocus, isTrue); // Delete button is a child widget of the Chip, so the Chip should have focus if // the delete button does. expect(Focus.of(labelKey.currentContext!).hasFocus, isTrue); expect(Focus.of(labelKey.currentContext!).hasPrimaryFocus, isFalse); Focus.of(labelKey.currentContext!).requestFocus(); await tester.pump(); expect(Focus.of(deleteButtonKey.currentContext!).hasFocus, isFalse); expect(Focus.of(deleteButtonKey.currentContext!).hasPrimaryFocus, isFalse); expect(Focus.of(labelKey.currentContext!).hasFocus, isTrue); expect(Focus.of(labelKey.currentContext!).hasPrimaryFocus, isTrue); }); testWidgets('Material2 - Delete button creates non-centered, unique ripple when tapped', (WidgetTester tester) async { final UniqueKey labelKey = UniqueKey(); final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( themeData: ThemeData(useMaterial3: false), labelKey: labelKey, deleteButtonKey: deleteButtonKey, deletable: true, ), ); final RenderBox box = getMaterialBox(tester); // Taps at a location close to the center of the delete icon. final Offset centerOfDeleteButton = tester.getCenter(find.byKey(deleteButtonKey)); final Offset tapLocationOfDeleteButton = centerOfDeleteButton + const Offset(-10, -10); final TestGesture gesture = await tester.startGesture(tapLocationOfDeleteButton); await tester.pump(); // Waits for 200 ms. await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100)); // There should be one unique ink ripple. expect(box, ripplePattern(const Offset(3.0, 3.0), 1.44)); expect(box, uniqueRipplePattern(const Offset(3.0, 3.0), 1.44)); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for 200 ms again. await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100)); // The ripple should grow, but the center should move, // Towards the center of the delete icon. expect(box, ripplePattern(const Offset(5.0, 5.0), 4.32)); expect(box, uniqueRipplePattern(const Offset(5.0, 5.0), 4.32)); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for a very long time. // This is pressing and holding the delete button. await tester.pumpAndSettle(); // There should be a tooltip. expect(findTooltipContainer('Delete'), findsOneWidget); await gesture.up(); }); testWidgets('Material3 - Delete button creates non-centered, unique sparkle when tapped', (WidgetTester tester) async { final UniqueKey labelKey = UniqueKey(); final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( labelKey: labelKey, deleteButtonKey: deleteButtonKey, deletable: true, size: 18.0, ), ); // Taps at a location close to the center of the delete icon. final Offset centerOfDeleteButton = tester.getCenter(find.byKey(deleteButtonKey)); final Offset tapLocationOfDeleteButton = centerOfDeleteButton + const Offset(-10, -10); final TestGesture gesture = await tester.startGesture(tapLocationOfDeleteButton); await tester.pump(); // Waits for 200 ms. await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100)); // There should be one unique ink sparkle. await expectLater(find.byType(RawChip), matchesGoldenFile('chip.delete_button_tapped.ink_sparkle.0.png')); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for 200 ms again. await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100)); // The sparkle should grow, but the center should move, // towards the center of the delete icon. await expectLater(find.byType(RawChip), matchesGoldenFile('chip.delete_button_tapped.ink_sparkle.1.png')); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for a very long time. // This is pressing and holding the delete button. await tester.pumpAndSettle(); // There should be a tooltip. expect(findTooltipContainer('Delete'), findsOneWidget); await gesture.up(); }); testWidgets('Material2 - Delete button in a chip with null onPressed creates ripple when tapped', (WidgetTester tester) async { final UniqueKey labelKey = UniqueKey(); final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( themeData: ThemeData(useMaterial3: false), labelKey: labelKey, onPressed: null, deleteButtonKey: deleteButtonKey, deletable: true, ), ); final RenderBox box = getMaterialBox(tester); // Taps at a location close to the center of the delete icon. final Offset centerOfDeleteButton = tester.getCenter(find.byKey(deleteButtonKey)); final Offset tapLocationOfDeleteButton = centerOfDeleteButton + const Offset(-10, -10); final TestGesture gesture = await tester.startGesture(tapLocationOfDeleteButton); await tester.pump(); // Waits for 200 ms. await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100)); // There should be one unique ink ripple. expect(box, ripplePattern(const Offset(3.0, 3.0), 1.44)); expect(box, uniqueRipplePattern(const Offset(3.0, 3.0), 1.44)); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for 200 ms again. await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100)); // The ripple should grow, but the center should move, // Towards the center of the delete icon. expect(box, ripplePattern(const Offset(5.0, 5.0), 4.32)); expect(box, uniqueRipplePattern(const Offset(5.0, 5.0), 4.32)); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for a very long time. // This is pressing and holding the delete button. await tester.pumpAndSettle(); // There should be a tooltip. expect(findTooltipContainer('Delete'), findsOneWidget); await gesture.up(); }); testWidgets('Material3 - Delete button in a chip with null onPressed creates sparkle when tapped', (WidgetTester tester) async { final UniqueKey labelKey = UniqueKey(); final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( labelKey: labelKey, onPressed: null, deleteButtonKey: deleteButtonKey, deletable: true, size: 18.0, ), ); // Taps at a location close to the center of the delete icon. final Offset centerOfDeleteButton = tester.getCenter(find.byKey(deleteButtonKey)); final Offset tapLocationOfDeleteButton = centerOfDeleteButton + const Offset(-10, -10); final TestGesture gesture = await tester.startGesture(tapLocationOfDeleteButton); await tester.pump(); // Waits for 200 ms. await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100)); // There should be one unique ink sparkle. await expectLater( find.byType(RawChip), matchesGoldenFile('chip.delete_button_tapped.disabled.ink_sparkle.0.png'), ); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for 200 ms again. await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100)); // The sparkle should grow, but the center should move, // towards the center of the delete icon. await expectLater( find.byType(RawChip), matchesGoldenFile('chip.delete_button_tapped.disabled.ink_sparkle.1.png'), ); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for a very long time. // This is pressing and holding the delete button. await tester.pumpAndSettle(); // There should be a tooltip. expect(findTooltipContainer('Delete'), findsOneWidget); await gesture.up(); }); testWidgets('RTL delete button responds to tap on the left of the chip', (WidgetTester tester) async { // Creates an RTL chip with a delete button. final UniqueKey labelKey = UniqueKey(); final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( labelKey: labelKey, deleteButtonKey: deleteButtonKey, deletable: true, textDirection: TextDirection.rtl, ), ); // Taps at a location close to the center of the delete icon, // Which is on the left side of the chip. final Offset topLeftOfInkWell = tester.getTopLeft(find.byType(InkWell).first); final Offset tapLocation = topLeftOfInkWell + const Offset(8, 8); final TestGesture gesture = await tester.startGesture(tapLocation); await tester.pump(); await tester.pumpAndSettle(); // The existence of a 'Delete' tooltip indicates the delete icon is tapped, // Instead of the label. expect(findTooltipContainer('Delete'), findsOneWidget); await gesture.up(); }); testWidgets('Material2 - Chip without delete button creates correct ripple', (WidgetTester tester) async { // Creates a chip with a delete button. final UniqueKey labelKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( themeData: ThemeData(useMaterial3: false), labelKey: labelKey, deletable: false, ), ); final RenderBox box = getMaterialBox(tester); // Taps at a location close to the bottom-right corner of the chip. final Offset bottomRightOfInkWell = tester.getBottomRight(find.byType(InkWell)); final Offset tapLocation = bottomRightOfInkWell + const Offset(-10, -10); final TestGesture gesture = await tester.startGesture(tapLocation); await tester.pump(); // Waits for 100 ms. await tester.pump(const Duration(milliseconds: 100)); // There should be exactly one ink-creating widget. expect(find.byType(InkWell), findsOneWidget); expect(find.byType(InkResponse), findsNothing); // There should be one unique, centered ink ripple. expect(box, ripplePattern(const Offset(378.0, 22.0), 37.9)); expect(box, uniqueRipplePattern(const Offset(378.0, 22.0), 37.9)); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for 100 ms again. await tester.pump(const Duration(milliseconds: 100)); // The ripple should grow, with the same center. // This indicates that the tap is not on a delete icon. expect(box, ripplePattern(const Offset(378.0, 22.0), 75.8)); expect(box, uniqueRipplePattern(const Offset(378.0, 22.0), 75.8)); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for a very long time. await tester.pumpAndSettle(); // There should still be no tooltip. // This indicates that the tap is not on a delete icon. expect(findTooltipContainer('Delete'), findsNothing); await gesture.up(); }); testWidgets('Material3 - Chip without delete button creates correct sparkle', (WidgetTester tester) async { // Creates a chip with a delete button. final UniqueKey labelKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( labelKey: labelKey, deletable: false, ), ); // Taps at a location close to the bottom-right corner of the chip. final Offset bottomRightOfInkWell = tester.getBottomRight(find.byType(InkWell)); final Offset tapLocation = bottomRightOfInkWell + const Offset(-10, -10); final TestGesture gesture = await tester.startGesture(tapLocation); await tester.pump(); // Waits for 100 ms. await tester.pump(const Duration(milliseconds: 100)); // There should be exactly one ink-creating widget. expect(find.byType(InkWell), findsOneWidget); expect(find.byType(InkResponse), findsNothing); // There should be one unique, centered ink sparkle. await expectLater( find.byType(RawChip), matchesGoldenFile('chip.without_delete_button.ink_sparkle.0.png'), ); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for 100 ms again. await tester.pump(const Duration(milliseconds: 100)); // The sparkle should grow, with the same center. // This indicates that the tap is not on a delete icon. await expectLater( find.byType(RawChip), matchesGoldenFile('chip.without_delete_button.ink_sparkle.1.png'), ); // There should be no tooltip. expect(findTooltipContainer('Delete'), findsNothing); // Waits for a very long time. await tester.pumpAndSettle(); // There should still be no tooltip. // This indicates that the tap is not on a delete icon. expect(findTooltipContainer('Delete'), findsNothing); await gesture.up(); }); testWidgets('Material2 - Selection with avatar works as expected on RawChip', (WidgetTester tester) async { bool selected = false; final UniqueKey labelKey = UniqueKey(); Future<void> pushChip({ Widget? avatar, bool selectable = false }) async { return tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: Wrap( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( avatar: avatar, onSelected: selectable ? (bool value) { setState(() { selected = value; }); } : null, selected: selected, label: Text('Long Chip Label', key: labelKey), shape: const StadiumBorder(), ); }), ], ), ), ); } // With avatar, but not selectable. final UniqueKey avatarKey = UniqueKey(); await pushChip( avatar: SizedBox(width: 40.0, height: 40.0, key: avatarKey), ); expect(tester.getSize(find.byType(RawChip)), equals(const Size(258.0, 48.0))); // Turn on selection. await pushChip( avatar: SizedBox(width: 40.0, height: 40.0, key: avatarKey), selectable: true, ); await tester.pumpAndSettle(); expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); // Simulate a tap on the label to select the chip. await tester.tap(find.byKey(labelKey)); expect(selected, equals(true)); expect(SchedulerBinding.instance.transientCallbackCount, equals(2)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.002, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.54, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(1.0)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pumpAndSettle(); // Simulate another tap on the label to deselect the chip. await tester.tap(find.byKey(labelKey)); expect(selected, equals(false)); expect(SchedulerBinding.instance.transientCallbackCount, equals(2)); await tester.pump(); await tester.pump(const Duration(milliseconds: 20)); expect(getSelectProgress(tester), moreOrLessEquals(0.875, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 20)); expect(getSelectProgress(tester), moreOrLessEquals(0.13, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(0.0)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); }); testWidgets('Material3 - Selection with avatar works as expected on RawChip', (WidgetTester tester) async { bool selected = false; final UniqueKey labelKey = UniqueKey(); Future<void> pushChip({ Widget? avatar, bool selectable = false }) async { return tester.pumpWidget( wrapForChip( child: Wrap( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( avatar: avatar, onSelected: selectable ? (bool value) { setState(() { selected = value; }); } : null, selected: selected, label: Text('Long Chip Label', key: labelKey), shape: const StadiumBorder(), ); }), ], ), ), ); } // With avatar, but not selectable. final UniqueKey avatarKey = UniqueKey(); await pushChip( avatar: SizedBox(width: 40.0, height: 40.0, key: avatarKey), ); expect(tester.getSize(find.byType(RawChip)), equals(const Size(265.5, 48.0))); // Turn on selection. await pushChip( avatar: SizedBox(width: 40.0, height: 40.0, key: avatarKey), selectable: true, ); await tester.pumpAndSettle(); expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); // Simulate a tap on the label to select the chip. await tester.tap(find.byKey(labelKey)); expect(selected, equals(true)); expect(SchedulerBinding.instance.transientCallbackCount, equals(kIsWeb && isCanvasKit ? 3 : 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.002, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.54, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(1.0)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pumpAndSettle(); // Simulate another tap on the label to deselect the chip. await tester.tap(find.byKey(labelKey)); expect(selected, equals(false)); expect(SchedulerBinding.instance.transientCallbackCount, equals(kIsWeb && isCanvasKit ? 3 : 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 20)); expect(getSelectProgress(tester), moreOrLessEquals(0.875, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 20)); expect(getSelectProgress(tester), moreOrLessEquals(0.13, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(0.0)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Material2 - Selection without avatar works as expected on RawChip', (WidgetTester tester) async { bool selected = false; final UniqueKey labelKey = UniqueKey(); Future<void> pushChip({ bool selectable = false }) async { return tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: Wrap( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( onSelected: selectable ? (bool value) { setState(() { selected = value; }); } : null, selected: selected, label: Text('Long Chip Label', key: labelKey), shape: const StadiumBorder(), ); }), ], ), ), ); } // Without avatar, but not selectable. await pushChip(); expect(tester.getSize(find.byType(RawChip)), equals(const Size(234.0, 48.0))); // Turn on selection. await pushChip(selectable: true); await tester.pumpAndSettle(); // Simulate a tap on the label to select the chip. await tester.tap(find.byKey(labelKey)); expect(selected, equals(true)); expect(SchedulerBinding.instance.transientCallbackCount, equals(2)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.002, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), moreOrLessEquals(0.459, epsilon: 0.01)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.54, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), moreOrLessEquals(0.92, epsilon: 0.01)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(1.0)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pumpAndSettle(); // Simulate another tap on the label to deselect the chip. await tester.tap(find.byKey(labelKey)); expect(selected, equals(false)); expect(SchedulerBinding.instance.transientCallbackCount, equals(2)); await tester.pump(); await tester.pump(const Duration(milliseconds: 20)); expect(getSelectProgress(tester), moreOrLessEquals(0.875, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), moreOrLessEquals(0.96, epsilon: 0.01)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 20)); expect(getSelectProgress(tester), moreOrLessEquals(0.13, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), moreOrLessEquals(0.75, epsilon: 0.01)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(0.0)); expect(getAvatarDrawerProgress(tester), equals(0.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); }); testWidgets('Material3 - Selection without avatar works as expected on RawChip', (WidgetTester tester) async { bool selected = false; final UniqueKey labelKey = UniqueKey(); Future<void> pushChip({ bool selectable = false }) async { return tester.pumpWidget( wrapForChip( child: Wrap( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( onSelected: selectable ? (bool value) { setState(() { selected = value; }); } : null, selected: selected, label: Text('Long Chip Label', key: labelKey), shape: const StadiumBorder(), ); }), ], ), ), ); } // Without avatar, but not selectable. await pushChip(); expect(tester.getSize(find.byType(RawChip)), equals(const Size(245.5, 48.0))); // Turn on selection. await pushChip(selectable: true); await tester.pumpAndSettle(); expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); // Simulate a tap on the label to select the chip. await tester.tap(find.byKey(labelKey)); expect(selected, equals(true)); expect(SchedulerBinding.instance.transientCallbackCount, equals(kIsWeb && isCanvasKit ? 3 : 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.002, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), moreOrLessEquals(0.459, epsilon: 0.01)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.54, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), moreOrLessEquals(0.92, epsilon: 0.01)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(1.0)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pumpAndSettle(); // Simulate another tap on the label to deselect the chip. await tester.tap(find.byKey(labelKey)); expect(selected, equals(false)); expect(SchedulerBinding.instance.transientCallbackCount, equals(kIsWeb && isCanvasKit ? 3 : 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 20)); expect(getSelectProgress(tester), moreOrLessEquals(0.875, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), moreOrLessEquals(0.96, epsilon: 0.01)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 20)); expect(getSelectProgress(tester), moreOrLessEquals(0.13, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), moreOrLessEquals(0.75, epsilon: 0.01)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(0.0)); expect(getAvatarDrawerProgress(tester), equals(0.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Material2 - Activation works as expected on RawChip', (WidgetTester tester) async { bool selected = false; final UniqueKey labelKey = UniqueKey(); Future<void> pushChip({ Widget? avatar, bool selectable = false }) async { return tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: Wrap( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( avatar: avatar, onSelected: selectable ? (bool value) { setState(() { selected = value; }); } : null, selected: selected, label: Text('Long Chip Label', key: labelKey), shape: const StadiumBorder(), showCheckmark: false, ); }), ], ), ), ); } final UniqueKey avatarKey = UniqueKey(); await pushChip( avatar: SizedBox(width: 40.0, height: 40.0, key: avatarKey), selectable: true, ); await tester.pumpAndSettle(); await tester.tap(find.byKey(labelKey)); expect(selected, equals(true)); expect(SchedulerBinding.instance.transientCallbackCount, equals(2)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.002, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.54, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(1.0)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pumpAndSettle(); }); testWidgets('Material3 - Activation works as expected on RawChip', (WidgetTester tester) async { bool selected = false; final UniqueKey labelKey = UniqueKey(); Future<void> pushChip({ Widget? avatar, bool selectable = false }) async { return tester.pumpWidget( wrapForChip( child: Wrap( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( avatar: avatar, onSelected: selectable ? (bool value) { setState(() { selected = value; }); } : null, selected: selected, label: Text('Long Chip Label', key: labelKey), shape: const StadiumBorder(), showCheckmark: false, ); }), ], ), ), ); } final UniqueKey avatarKey = UniqueKey(); await pushChip( avatar: SizedBox(width: 40.0, height: 40.0, key: avatarKey), selectable: true, ); await tester.pumpAndSettle(); expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); await tester.tap(find.byKey(labelKey)); expect(selected, equals(true)); expect(SchedulerBinding.instance.transientCallbackCount, equals(kIsWeb && isCanvasKit ? 3 : 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.002, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 50)); expect(getSelectProgress(tester), moreOrLessEquals(0.54, epsilon: 0.01)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pump(const Duration(milliseconds: 100)); expect(getSelectProgress(tester), equals(1.0)); expect(getAvatarDrawerProgress(tester), equals(1.0)); expect(getDeleteDrawerProgress(tester), equals(0.0)); await tester.pumpAndSettle(); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Chip uses ThemeData chip theme if present', (WidgetTester tester) async { final ThemeData theme = ThemeData(chipTheme: const ChipThemeData(backgroundColor: Color(0xffff0000))); Widget buildChip() { return wrapForChip( child: Theme( data: theme, child: InputChip( label: const Text('Label'), onPressed: () {}, ), ), ); } await tester.pumpWidget(buildChip()); final RenderBox materialBox = tester.firstRenderObject<RenderBox>( find.descendant( of: find.byType(RawChip), matching: find.byType(CustomPaint), ), ); expect(materialBox, paints..rrect(color: theme.chipTheme.backgroundColor)); }); testWidgets('Chip merges ChipThemeData label style with the provided label style', (WidgetTester tester) async { // The font family should be preserved even if the chip overrides some label style properties final ThemeData theme = ThemeData( fontFamily: 'MyFont', ); Widget buildChip() { return wrapForChip( child: Theme( data: theme, child: const Chip( label: Text('Label'), labelStyle: TextStyle(fontWeight: FontWeight.w200), ), ), ); } await tester.pumpWidget(buildChip()); final TextStyle labelStyle = getLabelStyle(tester, 'Label').style; expect(labelStyle.inherit, false); expect(labelStyle.fontFamily, 'MyFont'); expect(labelStyle.fontWeight, FontWeight.w200); }); testWidgets('ChipTheme labelStyle with inherit:true', (WidgetTester tester) async { Widget buildChip() { return wrapForChip( child: Theme( data: ThemeData.light().copyWith( chipTheme: const ChipThemeData( labelStyle: TextStyle(height: 4), // inherit: true ), ), child: const Chip(label: Text('Label')), // labelStyle: null ), ); } await tester.pumpWidget(buildChip()); final TextStyle labelStyle = getLabelStyle(tester, 'Label').style; expect(labelStyle.inherit, true); // because chipTheme.labelStyle.merge(null) expect(labelStyle.height, 4); }); testWidgets('Chip does not merge inherit:false label style with the theme label style', (WidgetTester tester) async { Widget buildChip() { return wrapForChip( child: Theme( data: ThemeData(fontFamily: 'MyFont'), child: const DefaultTextStyle( style: TextStyle(height: 8), child: Chip( label: Text('Label'), labelStyle: TextStyle(fontWeight: FontWeight.w200, inherit: false), ), ), ), ); } await tester.pumpWidget(buildChip()); final TextStyle labelStyle = getLabelStyle(tester, 'Label').style; expect(labelStyle.inherit, false); expect(labelStyle.fontFamily, null); expect(labelStyle.height, null); expect(labelStyle.fontWeight, FontWeight.w200); }); testWidgets('Material2 - Chip size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async { final Key key1 = UniqueKey(); await tester.pumpWidget( wrapForChip( child: Theme( data: ThemeData(useMaterial3: false, materialTapTargetSize: MaterialTapTargetSize.padded), child: Center( child: RawChip( key: key1, label: const Text('test'), ), ), ), ), ); expect(tester.getSize(find.byKey(key1)), const Size(80.0, 48.0)); final Key key2 = UniqueKey(); await tester.pumpWidget( wrapForChip( child: Theme( data: ThemeData(useMaterial3: false, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap), child: Center( child: RawChip( key: key2, label: const Text('test'), ), ), ), ), ); expect(tester.getSize(find.byKey(key2)), const Size(80.0, 32.0)); }); testWidgets('Material3 - Chip size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async { final Key key1 = UniqueKey(); await tester.pumpWidget( wrapForChip( child: Theme( data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.padded), child: Center( child: RawChip( key: key1, label: const Text('test'), ), ), ), ), ); expect(tester.getSize(find.byKey(key1)).width, moreOrLessEquals(90.4, epsilon: 0.1)); expect(tester.getSize(find.byKey(key1)).height, equals(48.0)); final Key key2 = UniqueKey(); await tester.pumpWidget( wrapForChip( child: Theme( data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap), child: Center( child: RawChip( key: key2, label: const Text('test'), ), ), ), ), ); expect(tester.getSize(find.byKey(key2)).width, moreOrLessEquals(90.4, epsilon: 0.1)); expect(tester.getSize(find.byKey(key2)).height, equals(38.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Chip uses the right theme colors for the right components', (WidgetTester tester) async { final ThemeData themeData = ThemeData( platform: TargetPlatform.android, primarySwatch: Colors.blue, ); final ChipThemeData defaultChipTheme = ChipThemeData.fromDefaults( brightness: themeData.brightness, secondaryColor: Colors.blue, labelStyle: themeData.textTheme.bodyLarge!, ); bool value = false; Widget buildApp({ ChipThemeData? chipTheme, Widget? avatar, Widget? deleteIcon, bool isSelectable = true, bool isPressable = false, bool isDeletable = true, bool showCheckmark = true, }) { chipTheme ??= defaultChipTheme; return wrapForChip( child: Theme( data: themeData, child: ChipTheme( data: chipTheme, child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( showCheckmark: showCheckmark, onDeleted: isDeletable ? () { } : null, avatar: avatar, deleteIcon: deleteIcon, isEnabled: isSelectable || isPressable, shape: chipTheme?.shape, selected: isSelectable && value, label: Text('$value'), onSelected: isSelectable ? (bool newValue) { setState(() { value = newValue; }); } : null, onPressed: isPressable ? () { setState(() { value = true; }); } : null, ); }), ), ), ); } await tester.pumpWidget(buildApp()); RenderBox materialBox = getMaterialBox(tester); IconThemeData iconData = getIconData(tester); DefaultTextStyle labelStyle = getLabelStyle(tester, 'false'); // Check default theme for enabled widget. expect(materialBox, paints..rrect(color: defaultChipTheme.backgroundColor)); expect(iconData.color, equals(const Color(0xde000000))); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); await tester.tap(find.byType(RawChip)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); expect(materialBox, paints..rrect(color: defaultChipTheme.selectedColor)); await tester.tap(find.byType(RawChip)); await tester.pumpAndSettle(); // Check default theme with disabled widget. await tester.pumpWidget(buildApp(isSelectable: false)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); labelStyle = getLabelStyle(tester, 'false'); expect(materialBox, paints..rrect(color: defaultChipTheme.disabledColor)); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); // Apply a custom theme. const Color customColor1 = Color(0xcafefeed); const Color customColor2 = Color(0xdeadbeef); const Color customColor3 = Color(0xbeefcafe); const Color customColor4 = Color(0xaddedabe); final ChipThemeData customTheme = defaultChipTheme.copyWith( brightness: Brightness.dark, backgroundColor: customColor1, disabledColor: customColor2, selectedColor: customColor3, deleteIconColor: customColor4, ); await tester.pumpWidget(buildApp(chipTheme: customTheme)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); iconData = getIconData(tester); labelStyle = getLabelStyle(tester, 'false'); // Check custom theme for enabled widget. expect(materialBox, paints..rrect(color: customTheme.backgroundColor)); expect(iconData.color, equals(customTheme.deleteIconColor)); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); await tester.tap(find.byType(RawChip)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); expect(materialBox, paints..rrect(color: customTheme.selectedColor)); await tester.tap(find.byType(RawChip)); await tester.pumpAndSettle(); // Check custom theme with disabled widget. await tester.pumpWidget(buildApp( chipTheme: customTheme, isSelectable: false, )); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); labelStyle = getLabelStyle(tester, 'false'); expect(materialBox, paints..rrect(color: customTheme.disabledColor)); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); }); group('Chip semantics', () { testWidgets('label only', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(const MaterialApp( home: Material( child: RawChip( label: Text('test'), ), ), )); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semanticsTester.dispose(); }); testWidgets('delete', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(MaterialApp( home: Material( child: RawChip( label: const Text('test'), onDeleted: () { }, ), ), )); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, ], children: <TestSemantics>[ TestSemantics( tooltip: 'Delete', actions: <SemanticsAction>[SemanticsAction.tap], textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.isButton, SemanticsFlag.isFocusable, ], ), ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semanticsTester.dispose(); }); testWidgets('with onPressed', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(MaterialApp( home: Material( child: RawChip( label: const Text('test'), onPressed: () { }, ), ), )); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics> [ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[SemanticsAction.tap], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semanticsTester.dispose(); }); testWidgets('with onSelected', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); bool selected = false; await tester.pumpWidget(MaterialApp( home: Material( child: RawChip( label: const Text('test'), selected: selected, onSelected: (bool value) { selected = value; }, ), ), )); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[SemanticsAction.tap], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); await tester.tap(find.byType(RawChip)); await tester.pumpWidget(MaterialApp( home: Material( child: RawChip( label: const Text('test'), selected: selected, onSelected: (bool value) { selected = value; }, ), ), )); expect(selected, true); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, SemanticsFlag.isSelected, ], actions: <SemanticsAction>[SemanticsAction.tap], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semanticsTester.dispose(); }); testWidgets('disabled', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(MaterialApp( home: Material( child: RawChip( isEnabled: false, onPressed: () { }, label: const Text('test'), ), ), )); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, ], actions: <SemanticsAction>[], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semanticsTester.dispose(); }); testWidgets('tapEnabled explicitly false', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(const MaterialApp( home: Material( child: RawChip( tapEnabled: false, label: Text('test'), ), ), )); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[], // Must not be a button when tapping is disabled. actions: <SemanticsAction>[], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semanticsTester.dispose(); }); testWidgets('enabled when tapEnabled and canTap', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); // These settings make a Chip which can be tapped, both in general and at this moment. await tester.pumpWidget(MaterialApp( home: Material( child: RawChip( onPressed: () {}, label: const Text('test'), ), ), )); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[SemanticsAction.tap], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semanticsTester.dispose(); }); testWidgets('disabled when tapEnabled but not canTap', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); // These settings make a Chip which _could_ be tapped, but not currently (ensures `canTap == false`). await tester.pumpWidget(const MaterialApp( home: Material( child: RawChip( label: Text('test'), ), ), )); expect( semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'test', textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semanticsTester.dispose(); }); }); testWidgets('can be tapped outside of chip delete icon', (WidgetTester tester) async { bool deleted = false; await tester.pumpWidget( wrapForChip( child: Row( children: <Widget>[ Chip( materialTapTargetSize: MaterialTapTargetSize.padded, shape: const RoundedRectangleBorder(), avatar: const CircleAvatar(child: Text('A')), label: const Text('Chip A'), onDeleted: () { deleted = true; }, deleteIcon: const Icon(Icons.delete), ), ], ), ), ); await tester.tapAt(tester.getTopRight(find.byType(Chip)) - const Offset(2.0, -2.0)); await tester.pumpAndSettle(); expect(deleted, true); }); testWidgets('Chips can be tapped', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: RawChip( label: Text('raw chip'), ), ), ), ); await tester.tap(find.byType(RawChip)); expect(tester.takeException(), null); }); testWidgets('Material2 - Chip elevation and shadow color work correctly', (WidgetTester tester) async { final ThemeData theme = ThemeData( useMaterial3: false, platform: TargetPlatform.android, primarySwatch: Colors.red, ); InputChip inputChip = const InputChip(label: Text('Label')); Widget buildChip() { return wrapForChip( child: Theme( data: theme, child: inputChip, ), ); } await tester.pumpWidget(buildChip()); Material material = getMaterial(tester); expect(material.elevation, 0.0); expect(material.shadowColor, Colors.black); inputChip = const InputChip( label: Text('Label'), elevation: 4.0, shadowColor: Colors.green, selectedShadowColor: Colors.blue, ); await tester.pumpWidget(buildChip()); await tester.pumpAndSettle(); material = getMaterial(tester); expect(material.elevation, 4.0); expect(material.shadowColor, Colors.green); inputChip = const InputChip( label: Text('Label'), selected: true, shadowColor: Colors.green, selectedShadowColor: Colors.blue, ); await tester.pumpWidget(buildChip()); await tester.pumpAndSettle(); material = getMaterial(tester); expect(material.shadowColor, Colors.blue); }); testWidgets('Material3 - Chip elevation and shadow color work correctly', (WidgetTester tester) async { final ThemeData theme = ThemeData(); InputChip inputChip = const InputChip(label: Text('Label')); Widget buildChip() { return wrapForChip( theme: theme, child: inputChip, ); } await tester.pumpWidget(buildChip()); Material material = getMaterial(tester); expect(material.elevation, 0.0); expect(material.shadowColor, Colors.transparent); inputChip = const InputChip( label: Text('Label'), elevation: 4.0, shadowColor: Colors.green, selectedShadowColor: Colors.blue, ); await tester.pumpWidget(buildChip()); await tester.pumpAndSettle(); material = getMaterial(tester); expect(material.elevation, 4.0); expect(material.shadowColor, Colors.green); inputChip = const InputChip( label: Text('Label'), selected: true, shadowColor: Colors.green, selectedShadowColor: Colors.blue, ); await tester.pumpWidget(buildChip()); await tester.pumpAndSettle(); material = getMaterial(tester); expect(material.shadowColor, Colors.blue); }); testWidgets('can be tapped outside of chip body', (WidgetTester tester) async { bool pressed = false; await tester.pumpWidget( wrapForChip( child: Row( children: <Widget>[ InputChip( materialTapTargetSize: MaterialTapTargetSize.padded, shape: const RoundedRectangleBorder(), avatar: const CircleAvatar(child: Text('A')), label: const Text('Chip A'), onPressed: () { pressed = true; }, ), ], ), ), ); await tester.tapAt(tester.getRect(find.byType(InputChip)).topCenter); await tester.pumpAndSettle(); expect(pressed, true); }); testWidgets('is hitTestable', (WidgetTester tester) async { await tester.pumpWidget( wrapForChip( child: InputChip( shape: const RoundedRectangleBorder(), avatar: const CircleAvatar(child: Text('A')), label: const Text('Chip A'), onPressed: () { }, ), ), ); expect(find.byType(InputChip).hitTestable(), findsOneWidget); }); void checkChipMaterialClipBehavior(WidgetTester tester, Clip clipBehavior) { final Iterable<Material> materials = tester.widgetList<Material>(find.byType(Material)); expect(materials.length, 2); expect(materials.last.clipBehavior, clipBehavior); } testWidgets('Chip clipBehavior properly passes through to the Material', (WidgetTester tester) async { const Text label = Text('label'); await tester.pumpWidget(wrapForChip(child: const Chip(label: label))); checkChipMaterialClipBehavior(tester, Clip.none); await tester.pumpWidget(wrapForChip(child: const Chip(label: label, clipBehavior: Clip.antiAlias))); checkChipMaterialClipBehavior(tester, Clip.antiAlias); }); testWidgets('Material2 - selected chip and avatar draw darkened layer within avatar circle', (WidgetTester tester) async { await tester.pumpWidget( wrapForChip( theme: ThemeData(useMaterial3: false), child: const FilterChip( avatar: CircleAvatar(child: Text('t')), label: Text('test'), selected: true, onSelected: null, ), ), ); final RenderBox rawChip = tester.firstRenderObject<RenderBox>( find.descendant( of: find.byType(RawChip), matching: find.byWidgetPredicate((Widget widget) { return widget.runtimeType.toString() == '_ChipRenderWidget'; }), ), ); const Color selectScrimColor = Color(0x60191919); expect(rawChip, paints..path(color: selectScrimColor, includes: <Offset>[ const Offset(10, 10), ], excludes: <Offset>[ const Offset(4, 4), ])); }); testWidgets('Material3 - selected chip and avatar draw darkened layer within avatar circle', (WidgetTester tester) async { await tester.pumpWidget( wrapForChip( child: const FilterChip( avatar: CircleAvatar(child: Text('t')), label: Text('test'), selected: true, onSelected: null, ), ), ); final RenderBox rawChip = tester.firstRenderObject<RenderBox>( find.descendant( of: find.byType(RawChip), matching: find.byWidgetPredicate((Widget widget) { return widget.runtimeType.toString() == '_ChipRenderWidget'; }), ), ); const Color selectScrimColor = Color(0x60191919); expect(rawChip, paints..path(color: selectScrimColor, includes: <Offset>[ const Offset(11, 11), ], excludes: <Offset>[ const Offset(4, 4), ])); }); testWidgets('Chips should use InkWell instead of InkResponse.', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/28646 await tester.pumpWidget( MaterialApp( home: Material( child: ActionChip( onPressed: () { }, label: const Text('action chip'), ), ), ), ); expect(find.byType(InkWell), findsOneWidget); }); testWidgets('Chip uses stateful color for text color in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); const Color selectedColor = Color(0x00000005); const Color disabledColor = Color(0x00000006); Color getTextColor(Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabledColor; } if (states.contains(MaterialState.pressed)) { return pressedColor; } if (states.contains(MaterialState.hovered)) { return hoverColor; } if (states.contains(MaterialState.focused)) { return focusedColor; } if (states.contains(MaterialState.selected)) { return selectedColor; } return defaultColor; } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( home: Scaffold( body: Focus( focusNode: focusNode, child: ChoiceChip( label: const Text('Chip'), selected: selected, onSelected: enabled ? (_) {} : null, labelStyle: TextStyle(color: MaterialStateColor.resolveWith(getTextColor)), ), ), ), ); } Color textColor() { return tester.renderObject<RenderParagraph>(find.text('Chip')).text.style!.color!; } // Default, not disabled. await tester.pumpWidget(chipWidget()); expect(textColor(), equals(defaultColor)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(textColor(), selectedColor); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(textColor(), focusedColor); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(textColor(), hoverColor); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(textColor(), pressedColor); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(textColor(), disabledColor); }); testWidgets('Material2 - Chip uses stateful border side color in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); const Color selectedColor = Color(0x00000005); const Color disabledColor = Color(0x00000006); BorderSide getBorderSide(Set<MaterialState> states) { Color sideColor = defaultColor; if (states.contains(MaterialState.disabled)) { sideColor = disabledColor; } else if (states.contains(MaterialState.pressed)) { sideColor = pressedColor; } else if (states.contains(MaterialState.hovered)) { sideColor = hoverColor; } else if (states.contains(MaterialState.focused)) { sideColor = focusedColor; } else if (states.contains(MaterialState.selected)) { sideColor = selectedColor; } return BorderSide(color: sideColor); } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Focus( focusNode: focusNode, child: ChoiceChip( label: const Text('Chip'), selected: selected, onSelected: enabled ? (_) {} : null, side: _MaterialStateBorderSide(getBorderSide), ), ), ), ); } // Default, not disabled. await tester.pumpWidget(chipWidget()); expect(find.byType(RawChip), paints..rrect()..rrect(color: defaultColor)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(find.byType(RawChip), paints..rrect()..rrect(color: selectedColor)); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: focusedColor)); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: hoverColor)); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: pressedColor)); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: disabledColor)); }); testWidgets('Material3 - Chip uses stateful border side color in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); const Color selectedColor = Color(0x00000005); const Color disabledColor = Color(0x00000006); BorderSide getBorderSide(Set<MaterialState> states) { Color sideColor = defaultColor; if (states.contains(MaterialState.disabled)) { sideColor = disabledColor; } else if (states.contains(MaterialState.pressed)) { sideColor = pressedColor; } else if (states.contains(MaterialState.hovered)) { sideColor = hoverColor; } else if (states.contains(MaterialState.focused)) { sideColor = focusedColor; } else if (states.contains(MaterialState.selected)) { sideColor = selectedColor; } return BorderSide(color: sideColor); } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( home: Scaffold( body: Focus( focusNode: focusNode, child: ChoiceChip( label: const Text('Chip'), selected: selected, onSelected: enabled ? (_) {} : null, side: _MaterialStateBorderSide(getBorderSide), ), ), ), ); } // Default, not disabled. await tester.pumpWidget(chipWidget()); expect(find.byType(RawChip), paints..drrect(color: defaultColor)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(find.byType(RawChip), paints..drrect(color: selectedColor)); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: focusedColor)); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: hoverColor)); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: pressedColor)); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: disabledColor)); }); testWidgets('Material2 - Chip uses stateful border side color from resolveWith', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); const Color selectedColor = Color(0x00000005); const Color disabledColor = Color(0x00000006); BorderSide getBorderSide(Set<MaterialState> states) { Color sideColor = defaultColor; if (states.contains(MaterialState.disabled)) { sideColor = disabledColor; } else if (states.contains(MaterialState.pressed)) { sideColor = pressedColor; } else if (states.contains(MaterialState.hovered)) { sideColor = hoverColor; } else if (states.contains(MaterialState.focused)) { sideColor = focusedColor; } else if (states.contains(MaterialState.selected)) { sideColor = selectedColor; } return BorderSide(color: sideColor); } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Focus( focusNode: focusNode, child: ChoiceChip( label: const Text('Chip'), selected: selected, onSelected: enabled ? (_) {} : null, side: MaterialStateBorderSide.resolveWith(getBorderSide), ), ), ), ); } // Default, not disabled. await tester.pumpWidget(chipWidget()); expect(find.byType(RawChip), paints..rrect()..rrect(color: defaultColor)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(find.byType(RawChip), paints..rrect()..rrect(color: selectedColor)); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: focusedColor)); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: hoverColor)); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: pressedColor)); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: disabledColor)); }); testWidgets('Material3 - Chip uses stateful border side color from resolveWith', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); const Color selectedColor = Color(0x00000005); const Color disabledColor = Color(0x00000006); BorderSide getBorderSide(Set<MaterialState> states) { Color sideColor = defaultColor; if (states.contains(MaterialState.disabled)) { sideColor = disabledColor; } else if (states.contains(MaterialState.pressed)) { sideColor = pressedColor; } else if (states.contains(MaterialState.hovered)) { sideColor = hoverColor; } else if (states.contains(MaterialState.focused)) { sideColor = focusedColor; } else if (states.contains(MaterialState.selected)) { sideColor = selectedColor; } return BorderSide(color: sideColor); } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( home: Scaffold( body: Focus( focusNode: focusNode, child: ChoiceChip( label: const Text('Chip'), selected: selected, onSelected: enabled ? (_) {} : null, side: MaterialStateBorderSide.resolveWith(getBorderSide), ), ), ), ); } // Default, not disabled. await tester.pumpWidget(chipWidget()); expect(find.byType(RawChip), paints..drrect(color: defaultColor)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(find.byType(RawChip), paints..drrect(color: selectedColor)); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: focusedColor)); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: hoverColor)); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: pressedColor)); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: disabledColor)); }); testWidgets('Material2 - Chip uses stateful nullable border side color from resolveWith', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); const Color disabledColor = Color(0x00000006); const Color fallbackThemeColor = Color(0x00000007); const BorderSide defaultBorderSide = BorderSide(color: fallbackThemeColor, width: 10.0); BorderSide? getBorderSide(Set<MaterialState> states) { Color sideColor = defaultColor; if (states.contains(MaterialState.disabled)) { sideColor = disabledColor; } else if (states.contains(MaterialState.pressed)) { sideColor = pressedColor; } else if (states.contains(MaterialState.hovered)) { sideColor = hoverColor; } else if (states.contains(MaterialState.focused)) { sideColor = focusedColor; } else if (states.contains(MaterialState.selected)) { return null; } return BorderSide(color: sideColor); } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Focus( focusNode: focusNode, child: ChipTheme( data: ThemeData.light().chipTheme.copyWith( side: defaultBorderSide, ), child: ChoiceChip( label: const Text('Chip'), selected: selected, onSelected: enabled ? (_) {} : null, side: MaterialStateBorderSide.resolveWith(getBorderSide), ), ), ), ), ); } // Default, not disabled. await tester.pumpWidget(chipWidget()); expect(find.byType(RawChip), paints..rrect()..rrect(color: defaultColor)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); // Because the resolver returns `null` for this value, we should fall back // to the theme. expect(find.byType(RawChip), paints..rrect()..rrect(color: fallbackThemeColor)); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: focusedColor)); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: hoverColor)); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: pressedColor)); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..rrect()..rrect(color: disabledColor)); }); testWidgets('Material3 - Chip uses stateful nullable border side color from resolveWith', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); const Color disabledColor = Color(0x00000006); const Color fallbackThemeColor = Color(0x00000007); const BorderSide defaultBorderSide = BorderSide(color: fallbackThemeColor, width: 10.0); BorderSide? getBorderSide(Set<MaterialState> states) { Color sideColor = defaultColor; if (states.contains(MaterialState.disabled)) { sideColor = disabledColor; } else if (states.contains(MaterialState.pressed)) { sideColor = pressedColor; } else if (states.contains(MaterialState.hovered)) { sideColor = hoverColor; } else if (states.contains(MaterialState.focused)) { sideColor = focusedColor; } else if (states.contains(MaterialState.selected)) { return null; } return BorderSide(color: sideColor); } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( home: Scaffold( body: Focus( focusNode: focusNode, child: ChipTheme( data: ThemeData.light().chipTheme.copyWith( side: defaultBorderSide, ), child: ChoiceChip( label: const Text('Chip'), selected: selected, onSelected: enabled ? (_) {} : null, side: MaterialStateBorderSide.resolveWith(getBorderSide), ), ), ), ), ); } // Default, not disabled. await tester.pumpWidget(chipWidget()); expect(find.byType(RawChip), paints..drrect(color: defaultColor)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); // Because the resolver returns `null` for this value, we should fall back // to the theme expect(find.byType(RawChip), paints..drrect(color: fallbackThemeColor)); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: focusedColor)); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: hoverColor)); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: pressedColor)); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(find.byType(RawChip), paints..drrect(color: disabledColor)); }); testWidgets('Material2 - Chip uses stateful shape in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); OutlinedBorder? getShape(Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return const BeveledRectangleBorder(); } else if (states.contains(MaterialState.pressed)) { return const CircleBorder(); } else if (states.contains(MaterialState.hovered)) { return const ContinuousRectangleBorder(); } else if (states.contains(MaterialState.focused)) { return const RoundedRectangleBorder(); } else if (states.contains(MaterialState.selected)) { return const BeveledRectangleBorder(); } return null; } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Focus( focusNode: focusNode, child: ChoiceChip( selected: selected, label: const Text('Chip'), shape: _MaterialStateOutlinedBorder(getShape), onSelected: enabled ? (_) {} : null, ), ), ), ); } // Default, not disabled. Defers to default shape. await tester.pumpWidget(chipWidget()); expect(getMaterial(tester).shape, isA<StadiumBorder>()); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(getMaterial(tester).shape, isA<BeveledRectangleBorder>()); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(getMaterial(tester).shape, isA<RoundedRectangleBorder>()); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(getMaterial(tester).shape, isA<ContinuousRectangleBorder>()); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(getMaterial(tester).shape, isA<CircleBorder>()); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(getMaterial(tester).shape, isA<BeveledRectangleBorder>()); }); testWidgets('Material3 - Chip uses stateful shape in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); OutlinedBorder? getShape(Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return const BeveledRectangleBorder(); } else if (states.contains(MaterialState.pressed)) { return const CircleBorder(); } else if (states.contains(MaterialState.hovered)) { return const ContinuousRectangleBorder(); } else if (states.contains(MaterialState.focused)) { return const RoundedRectangleBorder(); } else if (states.contains(MaterialState.selected)) { return const BeveledRectangleBorder(); } return null; } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( home: Scaffold( body: Focus( focusNode: focusNode, child: ChoiceChip( selected: selected, label: const Text('Chip'), shape: _MaterialStateOutlinedBorder(getShape), onSelected: enabled ? (_) {} : null, ), ), ), ); } // Default, not disabled. Defers to default shape. await tester.pumpWidget(chipWidget()); expect(getMaterial(tester).shape, isA<RoundedRectangleBorder>()); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(getMaterial(tester).shape, isA<BeveledRectangleBorder>()); // Focused. final FocusNode chipFocusNode = focusNode.children.first; chipFocusNode.requestFocus(); await tester.pumpAndSettle(); expect(getMaterial(tester).shape, isA<RoundedRectangleBorder>()); // Hovered. final Offset center = tester.getCenter(find.byType(ChoiceChip)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(getMaterial(tester).shape, isA<ContinuousRectangleBorder>()); // Pressed. await gesture.down(center); await tester.pumpAndSettle(); expect(getMaterial(tester).shape, isA<CircleBorder>()); // Disabled. await tester.pumpWidget(chipWidget(enabled: false)); await tester.pumpAndSettle(); expect(getMaterial(tester).shape, isA<BeveledRectangleBorder>()); }); testWidgets('Material2 - Chip defers to theme, if shape and side resolves to null', (WidgetTester tester) async { const OutlinedBorder themeShape = StadiumBorder(); const OutlinedBorder selectedShape = RoundedRectangleBorder(); const BorderSide themeBorderSide = BorderSide(color: Color(0x00000001)); const BorderSide selectedBorderSide = BorderSide(color: Color(0x00000002)); OutlinedBorder? getShape(Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return selectedShape; } return null; } BorderSide? getBorderSide(Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return selectedBorderSide; } return null; } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( theme: ThemeData( useMaterial3: false, chipTheme: ThemeData.light().chipTheme.copyWith( shape: themeShape, side: themeBorderSide, ), ), home: Scaffold( body: ChoiceChip( selected: selected, label: const Text('Chip'), shape: _MaterialStateOutlinedBorder(getShape), side: _MaterialStateBorderSide(getBorderSide), onSelected: enabled ? (_) {} : null, ), ), ); } // Default, not disabled. Defer to theme. await tester.pumpWidget(chipWidget()); expect(getMaterial(tester).shape, isA<StadiumBorder>()); expect(find.byType(RawChip), paints..rrect()..rrect(color: themeBorderSide.color)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(getMaterial(tester).shape, isA<RoundedRectangleBorder>()); expect(find.byType(RawChip), paints..rect()..drrect(color: selectedBorderSide.color)); }); testWidgets('Chip defers to theme, if shape and side resolves to null', (WidgetTester tester) async { const OutlinedBorder themeShape = StadiumBorder(); const OutlinedBorder selectedShape = RoundedRectangleBorder(); const BorderSide themeBorderSide = BorderSide(color: Color(0x00000001)); const BorderSide selectedBorderSide = BorderSide(color: Color(0x00000002)); OutlinedBorder? getShape(Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return selectedShape; } return null; } BorderSide? getBorderSide(Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return selectedBorderSide; } return null; } Widget chipWidget({ bool enabled = true, bool selected = false }) { return MaterialApp( theme: ThemeData( chipTheme: ThemeData.light().chipTheme.copyWith( shape: themeShape, side: themeBorderSide, ), ), home: Scaffold( body: ChoiceChip( selected: selected, label: const Text('Chip'), shape: _MaterialStateOutlinedBorder(getShape), side: _MaterialStateBorderSide(getBorderSide), onSelected: enabled ? (_) {} : null, ), ), ); } // Default, not disabled. Defer to theme. await tester.pumpWidget(chipWidget()); expect(getMaterial(tester).shape, isA<StadiumBorder>()); expect(find.byType(RawChip), paints..rrect()..rrect(color: themeBorderSide.color)); // Selected. await tester.pumpWidget(chipWidget(selected: true)); expect(getMaterial(tester).shape, isA<RoundedRectangleBorder>()); expect(find.byType(RawChip), paints..rect()..drrect(color: selectedBorderSide.color)); }); testWidgets('Material2 - Chip responds to density changes', (WidgetTester tester) async { const Key key = Key('test'); const Key textKey = Key('test text'); const Key iconKey = Key('test icon'); const Key avatarKey = Key('test avatar'); Future<void> buildTest(VisualDensity visualDensity) async { return tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: Column( children: <Widget>[ InputChip( visualDensity: visualDensity, key: key, onPressed: () {}, onDeleted: () {}, label: const Text('Test', key: textKey), deleteIcon: const Icon(Icons.delete, key: iconKey), avatar: const Icon(Icons.play_arrow, key: avatarKey), ), ], ), ), ), ), ); } // The Chips only change in size vertically in response to density, so // horizontal changes aren't expected. await buildTest(VisualDensity.standard); Rect box = tester.getRect(find.byKey(key)); Rect textBox = tester.getRect(find.byKey(textKey)); Rect iconBox = tester.getRect(find.byKey(iconKey)); Rect avatarBox = tester.getRect(find.byKey(avatarKey)); expect(box.size, equals(const Size(128, 32.0 + 16.0))); expect(textBox.size, equals(const Size(56, 14))); expect(iconBox.size, equals(const Size(24, 24))); expect(avatarBox.size, equals(const Size(24, 24))); expect(textBox.top, equals(17)); expect(box.bottom - textBox.bottom, equals(17)); expect(textBox.left, equals(372)); expect(box.right - textBox.right, equals(36)); // Try decreasing density (with higher density numbers). await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0)); box = tester.getRect(find.byKey(key)); textBox = tester.getRect(find.byKey(textKey)); iconBox = tester.getRect(find.byKey(iconKey)); avatarBox = tester.getRect(find.byKey(avatarKey)); expect(box.size, equals(const Size(128, 60))); expect(textBox.size, equals(const Size(56, 14))); expect(iconBox.size, equals(const Size(24, 24))); expect(avatarBox.size, equals(const Size(24, 24))); expect(textBox.top, equals(23)); expect(box.bottom - textBox.bottom, equals(23)); expect(textBox.left, equals(372)); expect(box.right - textBox.right, equals(36)); // Try increasing density (with lower density numbers). await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0)); box = tester.getRect(find.byKey(key)); textBox = tester.getRect(find.byKey(textKey)); iconBox = tester.getRect(find.byKey(iconKey)); avatarBox = tester.getRect(find.byKey(avatarKey)); expect(box.size, equals(const Size(128, 36))); expect(textBox.size, equals(const Size(56, 14))); expect(iconBox.size, equals(const Size(24, 24))); expect(avatarBox.size, equals(const Size(24, 24))); expect(textBox.top, equals(11)); expect(box.bottom - textBox.bottom, equals(11)); expect(textBox.left, equals(372)); expect(box.right - textBox.right, equals(36)); // Now test that horizontal and vertical are wired correctly. Negating the // horizontal should have no change over what's above. await buildTest(const VisualDensity(horizontal: 3.0, vertical: -3.0)); await tester.pumpAndSettle(); box = tester.getRect(find.byKey(key)); textBox = tester.getRect(find.byKey(textKey)); iconBox = tester.getRect(find.byKey(iconKey)); avatarBox = tester.getRect(find.byKey(avatarKey)); expect(box.size, equals(const Size(128, 36))); expect(textBox.size, equals(const Size(56, 14))); expect(iconBox.size, equals(const Size(24, 24))); expect(avatarBox.size, equals(const Size(24, 24))); expect(textBox.top, equals(11)); expect(box.bottom - textBox.bottom, equals(11)); expect(textBox.left, equals(372)); expect(box.right - textBox.right, equals(36)); // Make sure the "Comfortable" setting is the spec'd size await buildTest(VisualDensity.comfortable); await tester.pumpAndSettle(); box = tester.getRect(find.byKey(key)); expect(box.size, equals(const Size(128, 28.0 + 16.0))); // Make sure the "Compact" setting is the spec'd size await buildTest(VisualDensity.compact); await tester.pumpAndSettle(); box = tester.getRect(find.byKey(key)); expect(box.size, equals(const Size(128, 24.0 + 16.0))); }); testWidgets('Material3 - Chip responds to density changes', (WidgetTester tester) async { const Key key = Key('test'); const Key textKey = Key('test text'); const Key iconKey = Key('test icon'); const Key avatarKey = Key('test avatar'); Future<void> buildTest(VisualDensity visualDensity) async { return tester.pumpWidget( MaterialApp( home: Material( child: Center( child: Column( children: <Widget>[ InputChip( visualDensity: visualDensity, key: key, onPressed: () {}, onDeleted: () {}, label: const Text('Test', key: textKey), deleteIcon: const Icon(Icons.delete, key: iconKey), avatar: const Icon(Icons.play_arrow, key: avatarKey), ), ], ), ), ), ), ); } // The Chips only change in size vertically in response to density, so // horizontal changes aren't expected. await buildTest(VisualDensity.standard); Rect box = tester.getRect(find.byKey(key)); Rect textBox = tester.getRect(find.byKey(textKey)); Rect iconBox = tester.getRect(find.byKey(iconKey)); Rect avatarBox = tester.getRect(find.byKey(avatarKey)); expect(box.size.width, moreOrLessEquals(130.4, epsilon: 0.1)); expect(box.size.height, equals(32.0 + 16.0)); expect(textBox.size.width, moreOrLessEquals(56.4, epsilon: 0.1)); expect(textBox.size.height, equals(20.0)); expect(iconBox.size, equals(const Size(20, 20))); expect(avatarBox.size, equals(const Size(18, 18))); expect(textBox.top, equals(14)); expect(box.bottom - textBox.bottom, equals(14)); expect(textBox.left, moreOrLessEquals(371.79, epsilon: 0.1)); expect(box.right - textBox.right, equals(37)); // Try decreasing density (with higher density numbers). await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0)); box = tester.getRect(find.byKey(key)); textBox = tester.getRect(find.byKey(textKey)); iconBox = tester.getRect(find.byKey(iconKey)); avatarBox = tester.getRect(find.byKey(avatarKey)); expect(box.size.width, moreOrLessEquals(130.4, epsilon: 0.1)); expect(box.size.height, equals(60)); expect(textBox.size.width, moreOrLessEquals(56.4, epsilon: 0.1)); expect(textBox.size.height, equals(20.0)); expect(iconBox.size, equals(const Size(20, 20))); expect(avatarBox.size, equals(const Size(18, 18))); expect(textBox.top, equals(20)); expect(box.bottom - textBox.bottom, equals(20)); expect(textBox.left, moreOrLessEquals(371.79, epsilon: 0.1)); expect(box.right - textBox.right, equals(37)); // Try increasing density (with lower density numbers). await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0)); box = tester.getRect(find.byKey(key)); textBox = tester.getRect(find.byKey(textKey)); iconBox = tester.getRect(find.byKey(iconKey)); avatarBox = tester.getRect(find.byKey(avatarKey)); expect(box.size.width, moreOrLessEquals(130.4, epsilon: 0.1)); expect(box.size.height, equals(36)); expect(textBox.size.width, moreOrLessEquals(56.4, epsilon: 0.1)); expect(textBox.size.height, equals(20.0)); expect(iconBox.size, equals(const Size(20, 20))); expect(avatarBox.size, equals(const Size(18, 18))); expect(textBox.top, equals(8)); expect(box.bottom - textBox.bottom, equals(8)); expect(textBox.left, moreOrLessEquals(371.79, epsilon: 0.1)); expect(box.right - textBox.right, equals(37)); // Now test that horizontal and vertical are wired correctly. Negating the // horizontal should have no change over what's above. await buildTest(const VisualDensity(horizontal: 3.0, vertical: -3.0)); await tester.pumpAndSettle(); box = tester.getRect(find.byKey(key)); textBox = tester.getRect(find.byKey(textKey)); iconBox = tester.getRect(find.byKey(iconKey)); avatarBox = tester.getRect(find.byKey(avatarKey)); expect(box.size.width, moreOrLessEquals(130.4, epsilon: 0.1)); expect(box.size.height, equals(36)); expect(textBox.size.width, moreOrLessEquals(56.4, epsilon: 0.1)); expect(textBox.size.height, equals(20.0)); expect(iconBox.size, equals(const Size(20, 20))); expect(avatarBox.size, equals(const Size(18, 18))); expect(textBox.top, equals(8)); expect(box.bottom - textBox.bottom, equals(8)); expect(textBox.left, moreOrLessEquals(371.79, epsilon: 0.1)); expect(box.right - textBox.right, equals(37)); // Make sure the "Comfortable" setting is the spec'd size await buildTest(VisualDensity.comfortable); await tester.pumpAndSettle(); box = tester.getRect(find.byKey(key)); expect(box.size.width, moreOrLessEquals(130.4, epsilon: 0.1)); expect(box.size.height, equals(28.0 + 16.0)); // Make sure the "Compact" setting is the spec'd size await buildTest(VisualDensity.compact); await tester.pumpAndSettle(); box = tester.getRect(find.byKey(key)); expect(box.size.width, moreOrLessEquals(130.4, epsilon: 0.1)); expect(box.size.height, equals(24.0 + 16.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Chip delete button tooltip is disabled if deleteButtonTooltipMessage is empty', (WidgetTester tester) async { final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( deleteButtonKey: deleteButtonKey, deletable: true, deleteButtonTooltipMessage: '', ), ); // Hover over the delete icon of the chip final Offset centerOfDeleteButton = tester.getCenter(find.byKey(deleteButtonKey)); final TestGesture hoverGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await hoverGesture.moveTo(centerOfDeleteButton); addTearDown(hoverGesture.removePointer); await tester.pump(); // Wait for some more time while hovering over the delete button await tester.pumpAndSettle(); // There should be no delete button tooltip expect(findTooltipContainer(''), findsNothing); }); testWidgets('Disabling delete button tooltip does not disable chip tooltip', (WidgetTester tester) async { final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( deleteButtonKey: deleteButtonKey, deletable: true, deleteButtonTooltipMessage: '', chipTooltip: 'Chip Tooltip', ), ); // Hover over the delete icon of the chip final Offset centerOfDeleteButton = tester.getCenter(find.byKey(deleteButtonKey)); final TestGesture hoverGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await hoverGesture.moveTo(centerOfDeleteButton); addTearDown(hoverGesture.removePointer); await tester.pump(); // Wait for some more time while hovering over the delete button await tester.pumpAndSettle(); // There should be no delete button tooltip expect(findTooltipContainer(''), findsNothing); // There should be a chip tooltip, however. expect(findTooltipContainer('Chip Tooltip'), findsOneWidget); }); testWidgets('Triggering delete button tooltip does not trigger Chip tooltip', (WidgetTester tester) async { final UniqueKey deleteButtonKey = UniqueKey(); await tester.pumpWidget( chipWithOptionalDeleteButton( deleteButtonKey: deleteButtonKey, deletable: true, chipTooltip: 'Chip Tooltip', ), ); // Hover over the delete icon of the chip final Offset centerOfDeleteButton = tester.getCenter(find.byKey(deleteButtonKey)); final TestGesture hoverGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await hoverGesture.moveTo(centerOfDeleteButton); addTearDown(hoverGesture.removePointer); await tester.pump(); // Wait for some more time while hovering over the delete button await tester.pumpAndSettle(); // There should not be a chip tooltip expect(findTooltipContainer('Chip Tooltip'), findsNothing); // There should be a delete button tooltip expect(findTooltipContainer('Delete'), findsOneWidget); }); testWidgets('intrinsicHeight implementation meets constraints', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/49478. await tester.pumpWidget(wrapForChip( child: const Chip( label: Text('text'), padding: EdgeInsets.symmetric(horizontal: 20), ), )); expect(tester.takeException(), isNull); }); testWidgets('Material2 - Chip background color and shape are drawn on Ink', (WidgetTester tester) async { const Color backgroundColor = Color(0xff00ff00); const OutlinedBorder shape = ContinuousRectangleBorder(); await tester.pumpWidget(wrapForChip( theme: ThemeData(useMaterial3: false), child: const RawChip( label: Text('text'), backgroundColor: backgroundColor, shape: shape, ), )); final Ink ink = tester.widget(find.descendant( of: find.byType(RawChip), matching: find.byType(Ink), )); final ShapeDecoration decoration = ink.decoration! as ShapeDecoration; expect(decoration.color, backgroundColor); expect(decoration.shape, shape); }); testWidgets('Material3 - Chip background color and shape are drawn on Ink', (WidgetTester tester) async { const Color backgroundColor = Color(0xff00ff00); const OutlinedBorder shape = ContinuousRectangleBorder(); final ThemeData theme = ThemeData(); await tester.pumpWidget(wrapForChip( theme: theme, child: const RawChip( label: Text('text'), backgroundColor: backgroundColor, shape: shape, ), )); final Ink ink = tester.widget(find.descendant( of: find.byType(RawChip), matching: find.byType(Ink), )); final ShapeDecoration decoration = ink.decoration! as ShapeDecoration; expect(decoration.color, backgroundColor); expect(decoration.shape, shape.copyWith(side: BorderSide(color: theme.colorScheme.outline))); }); testWidgets('Chip highlight color is drawn on top of the backgroundColor', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'RawChip'); addTearDown(focusNode.dispose); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const Color backgroundColor = Color(0xff00ff00); await tester.pumpWidget(wrapForChip( child: RawChip( label: const Text('text'), backgroundColor: backgroundColor, autofocus: true, focusNode: focusNode, onPressed: () {}, ), )); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( find.byType(Material).last, paints // Background color is drawn first. ..rrect(color: backgroundColor) // Highlight color is drawn on top of the background color. ..rect(color: const Color(0x1f000000)), ); }); testWidgets('RawChip.color resolves material states', (WidgetTester tester) async { const Color disabledSelectedColor = Color(0xffffff00); const Color disabledColor = Color(0xff00ff00); const Color backgroundColor = Color(0xff0000ff); const Color selectedColor = Color(0xffff0000); Widget buildApp({ required bool enabled, required bool selected }) { return wrapForChip( child: RawChip( isEnabled: enabled, selected: selected, color: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled) && states.contains(MaterialState.selected)) { return disabledSelectedColor; } if (states.contains(MaterialState.disabled)) { return disabledColor; } if (states.contains(MaterialState.selected)) { return selectedColor; } return backgroundColor; }), label: const Text('RawChip'), ), ); } // Test enabled chip. await tester.pumpWidget(buildApp(enabled: true, selected: false)); // Enabled chip should have the provided backgroundColor. expect(getMaterialBox(tester), paints..rrect(color: backgroundColor)); // Test disabled chip. await tester.pumpWidget(buildApp(enabled: false, selected: false)); await tester.pumpAndSettle(); // Disabled chip should have the provided disabledColor. expect(getMaterialBox(tester), paints..rrect(color: disabledColor)); // Test enabled & selected chip. await tester.pumpWidget(buildApp(enabled: true, selected: true)); await tester.pumpAndSettle(); // Enabled & selected chip should have the provided selectedColor. expect(getMaterialBox(tester), paints..rrect(color: selectedColor)); // Test disabled & selected chip. await tester.pumpWidget(buildApp(enabled: false, selected: true)); await tester.pumpAndSettle(); // Disabled & selected chip should have the provided disabledSelectedColor. expect(getMaterialBox(tester), paints..rrect(color: disabledSelectedColor)); }); testWidgets('RawChip uses provided state color properties', (WidgetTester tester) async { const Color disabledColor = Color(0xff00ff00); const Color backgroundColor = Color(0xff0000ff); const Color selectedColor = Color(0xffff0000); Widget buildApp({ required bool enabled, required bool selected }) { return wrapForChip( child: RawChip( isEnabled: enabled, selected: selected, disabledColor: disabledColor, backgroundColor: backgroundColor, selectedColor: selectedColor, label: const Text('RawChip'), ), ); } // Test enabled chip. await tester.pumpWidget(buildApp(enabled: true, selected: false)); // Enabled chip should have the provided backgroundColor. expect(getMaterialBox(tester), paints..rrect(color: backgroundColor)); // Test disabled chip. await tester.pumpWidget(buildApp(enabled: false, selected: false)); await tester.pumpAndSettle(); // Disabled chip should have the provided disabledColor. expect(getMaterialBox(tester), paints..rrect(color: disabledColor)); // Test enabled & selected chip. await tester.pumpWidget(buildApp(enabled: true, selected: true)); await tester.pumpAndSettle(); // Enabled & selected chip should have the provided selectedColor. expect(getMaterialBox(tester), paints..rrect(color: selectedColor)); }); testWidgets('Delete button tap target area does not include label', (WidgetTester tester) async { bool calledDelete = false; await tester.pumpWidget( wrapForChip( child: Column( children: <Widget>[ Chip( label: const Text('Chip'), onDeleted: () { calledDelete = true; }, ), ], ), ), ); // Tap on the delete button. await tester.tapAt(tester.getCenter(find.byType(Icon))); await tester.pump(); expect(calledDelete, isTrue); calledDelete = false; final Offset labelCenter = tester.getCenter(find.text('Chip')); // Tap on the label. await tester.tapAt(labelCenter); await tester.pump(); expect(calledDelete, isFalse); // Tap before end of the label. final Size labelSize = tester.getSize(find.text('Chip')); await tester.tapAt(Offset(labelCenter.dx + (labelSize.width / 2) - 1, labelCenter.dy)); await tester.pump(); expect(calledDelete, isFalse); // Tap after end of the label. await tester.tapAt(Offset(labelCenter.dx + (labelSize.width / 2) + 0.01, labelCenter.dy)); await tester.pump(); expect(calledDelete, isTrue); }); // This is a regression test for https://github.com/flutter/flutter/pull/133615. testWidgets('Material3 - Custom shape without provided side uses default side', (WidgetTester tester) async { final ThemeData theme = ThemeData(); await tester.pumpWidget( MaterialApp( theme: theme, home: const Material( child: Center( child: RawChip( // No side provided. shape: StadiumBorder(), label: Text('RawChip'), ), ), ), ), ); // Chip should have the default side. expect( getMaterial(tester).shape, StadiumBorder(side: BorderSide(color: theme.colorScheme.outline)), ); }); testWidgets("Material3 - RawChip.shape's side is used when provided", (WidgetTester tester) async { Widget buildChip({ OutlinedBorder? shape, BorderSide? side }) { return MaterialApp( home: Material( child: Center( child: RawChip( shape: shape, side: side, label: const Text('RawChip'), ), ), ), ); } // Test [RawChip.shape] with a side. await tester.pumpWidget(buildChip( shape: const RoundedRectangleBorder( side: BorderSide(color: Color(0xffff00ff)), borderRadius: BorderRadius.all(Radius.circular(7.0)), )), ); // Chip should have the provided shape and the side from [RawChip.shape]. expect( getMaterial(tester).shape, const RoundedRectangleBorder( side: BorderSide(color: Color(0xffff00ff)), borderRadius: BorderRadius.all(Radius.circular(7.0)), ), ); // Test [RawChip.shape] with a side and [RawChip.side]. await tester.pumpWidget(buildChip( shape: const RoundedRectangleBorder( side: BorderSide(color: Color(0xffff00ff)), borderRadius: BorderRadius.all(Radius.circular(7.0)), ), side: const BorderSide(color: Color(0xfffff000))), ); await tester.pumpAndSettle(); // Chip use shape from [RawChip.shape] and the side from [RawChip.side]. // [RawChip.shape]'s side should be ignored. expect( getMaterial(tester).shape, const RoundedRectangleBorder( side: BorderSide(color: Color(0xfffff000)), borderRadius: BorderRadius.all(Radius.circular(7.0)), ), ); }); testWidgets('Material3 - Chip.iconTheme respects default iconTheme.size', (WidgetTester tester) async { Widget buildChip({ IconThemeData? iconTheme }) { return MaterialApp( home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: RawChip( iconTheme: iconTheme, avatar: const Icon(Icons.add), label: const SizedBox(width: 100, height: 100), onSelected: (bool newValue) { }, ), ), ), ), ); } await tester.pumpWidget(buildChip(iconTheme: const IconThemeData(color: Color(0xff332211)))); // Icon should have the default chip iconSize. expect(getIconData(tester).size, 18.0); expect(getIconData(tester).color, const Color(0xff332211)); // Icon should have the provided iconSize. await tester.pumpWidget(buildChip(iconTheme: const IconThemeData(color: Color(0xff112233), size: 23.0))); await tester.pumpAndSettle(); expect(getIconData(tester).size, 23.0); expect(getIconData(tester).color, const Color(0xff112233)); }); // This is a regression test for https://github.com/flutter/flutter/issues/138287. testWidgets("Enabling and disabling Chip with Tooltip doesn't throw an exception", (WidgetTester tester) async { bool isEnabled = true; await tester.pumpWidget(MaterialApp( home: Material( child: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ RawChip( tooltip: 'tooltip', isEnabled: isEnabled, onPressed: isEnabled ? () {} : null, label: const Text('RawChip'), ), ElevatedButton( onPressed: () { setState(() { isEnabled = !isEnabled; }); }, child: Text('${isEnabled ? 'Disable' : 'Enable'} Chip'), ), ], ); }, ), ), ), )); // Tap the elevated button to disable the chip with a tooltip. await tester.tap(find.widgetWithText(ElevatedButton, 'Disable Chip')); await tester.pumpAndSettle(); // No exception should be thrown. expect(tester.takeException(), isNull); // Tap the elevated button to enable the chip with a tooltip. await tester.tap(find.widgetWithText(ElevatedButton, 'Enable Chip')); await tester.pumpAndSettle(); // No exception should be thrown. expect(tester.takeException(), isNull); }); testWidgets('Delete button is visible on disabled RawChip', (WidgetTester tester) async { await tester.pumpWidget( wrapForChip( child: RawChip( isEnabled: false, label: const Text('Label'), onDeleted: () { }, ), ), ); // Delete button should be visible. await expectLater(find.byType(RawChip), matchesGoldenFile('raw_chip.disabled.delete_button.png')); }); testWidgets('Delete button tooltip is not shown on disabled RawChip', (WidgetTester tester) async { Widget buildChip({ bool enabled = true }) { return wrapForChip( child: RawChip( isEnabled: enabled, label: const Text('Label'), onDeleted: () { }, ), ); } // Test enabled chip. await tester.pumpWidget(buildChip()); final Offset deleteButtonLocation = tester.getCenter(find.byType(Icon)); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.moveTo(deleteButtonLocation); await tester.pump(); // Delete button tooltip should be visible. expect(findTooltipContainer('Delete'), findsOneWidget); // Test disabled chip. await tester.pumpWidget(buildChip(enabled: false)); await tester.pump(); // Delete button tooltip should not be visible. expect(findTooltipContainer('Delete'), findsNothing); }); testWidgets('Chip avatar layout constraints can be customized', (WidgetTester tester) async { const double border = 1.0; const double iconSize = 18.0; const double labelPadding = 8.0; const double padding = 8.0; const Size labelSize = Size(100, 100); Widget buildChip({BoxConstraints? avatarBoxConstraints}) { return wrapForChip( child: Center( child: Chip( avatarBoxConstraints: avatarBoxConstraints, avatar: const Icon(Icons.favorite), label: Container( width: labelSize.width, height: labelSize.width, color: const Color(0xFFFF0000), ), ), ), ); } // Test default avatar layout constraints. await tester.pumpWidget(buildChip()); expect(tester.getSize(find.byType(Chip)).width, equals(234.0)); expect(tester.getSize(find.byType(Chip)).height, equals(118.0)); // Calculate the distance between avatar and chip edges. Offset chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester))); final Offset avatarCenter = tester.getCenter(find.byIcon(Icons.favorite)); expect(chipTopLeft.dx, avatarCenter.dx - (labelSize.width / 2) - padding - border); expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between avatar and label. Offset labelTopLeft = tester.getTopLeft(find.byType(Container)); expect(labelTopLeft.dx, avatarCenter.dx + (labelSize.width / 2) + labelPadding); // Test custom avatar layout constraints. await tester.pumpWidget(buildChip(avatarBoxConstraints: const BoxConstraints.tightForFinite())); await tester.pump(); expect(tester.getSize(find.byType(Chip)).width, equals(152.0)); expect(tester.getSize(find.byType(Chip)).height, equals(118.0)); // Calculate the distance between avatar and chip edges. chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester))); expect(chipTopLeft.dx, avatarCenter.dx - (iconSize / 2) - padding - border); expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between avatar and label. labelTopLeft = tester.getTopLeft(find.byType(Container)); expect(labelTopLeft.dx, avatarCenter.dx + (iconSize / 2) + labelPadding); }); testWidgets('RawChip avatar layout constraints can be customized', (WidgetTester tester) async { const double border = 1.0; const double iconSize = 18.0; const double labelPadding = 8.0; const double padding = 8.0; const Size labelSize = Size(100, 100); Widget buildChip({BoxConstraints? avatarBoxConstraints}) { return wrapForChip( child: Center( child: RawChip( avatarBoxConstraints: avatarBoxConstraints, avatar: const Icon(Icons.favorite), label: Container( width: labelSize.width, height: labelSize.width, color: const Color(0xFFFF0000), ), ), ), ); } // Test default avatar layout constraints. await tester.pumpWidget(buildChip()); expect(tester.getSize(find.byType(RawChip)).width, equals(234.0)); expect(tester.getSize(find.byType(RawChip)).height, equals(118.0)); // Calculate the distance between avatar and chip edges. Offset chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester))); final Offset avatarCenter = tester.getCenter(find.byIcon(Icons.favorite)); expect(chipTopLeft.dx, avatarCenter.dx - (labelSize.width / 2) - padding - border); expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between avatar and label. Offset labelTopLeft = tester.getTopLeft(find.byType(Container)); expect(labelTopLeft.dx, avatarCenter.dx + (labelSize.width / 2) + labelPadding); // Test custom avatar layout constraints. await tester.pumpWidget(buildChip(avatarBoxConstraints: const BoxConstraints.tightForFinite())); await tester.pump(); expect(tester.getSize(find.byType(RawChip)).width, equals(152.0)); expect(tester.getSize(find.byType(RawChip)).height, equals(118.0)); // Calculate the distance between avatar and chip edges. chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester))); expect(chipTopLeft.dx, avatarCenter.dx - (iconSize / 2) - padding - border); expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between avatar and label. labelTopLeft = tester.getTopLeft(find.byType(Container)); expect(labelTopLeft.dx, avatarCenter.dx + (iconSize / 2) + labelPadding); }); testWidgets('Chip delete icon layout constraints can be customized', (WidgetTester tester) async { const double border = 1.0; const double iconSize = 18.0; const double labelPadding = 8.0; const double padding = 8.0; const Size labelSize = Size(100, 100); Widget buildChip({BoxConstraints? deleteIconBoxConstraints}) { return wrapForChip( child: Center( child: Chip( deleteIconBoxConstraints: deleteIconBoxConstraints, onDeleted: () { }, label: Container( width: labelSize.width, height: labelSize.width, color: const Color(0xFFFF0000), ), ), ), ); } // Test default delete icon layout constraints. await tester.pumpWidget(buildChip()); expect(tester.getSize(find.byType(Chip)).width, equals(234.0)); expect(tester.getSize(find.byType(Chip)).height, equals(118.0)); // Calculate the distance between delete icon and chip edges. Offset chipTopRight = tester.getTopRight(find.byWidget(getMaterial(tester))); final Offset deleteIconCenter = tester.getCenter(find.byIcon(Icons.cancel)); expect(chipTopRight.dx, deleteIconCenter.dx + (labelSize.width / 2) + padding + border); expect(chipTopRight.dy, deleteIconCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between delete icon and label. Offset labelTopRight = tester.getTopRight(find.byType(Container)); expect(labelTopRight.dx, deleteIconCenter.dx - (labelSize.width / 2) - labelPadding); // Test custom avatar layout constraints. await tester.pumpWidget(buildChip( deleteIconBoxConstraints: const BoxConstraints.tightForFinite(), )); await tester.pump(); expect(tester.getSize(find.byType(Chip)).width, equals(152.0)); expect(tester.getSize(find.byType(Chip)).height, equals(118.0)); // Calculate the distance between delete icon and chip edges. chipTopRight = tester.getTopRight(find.byWidget(getMaterial(tester))); expect(chipTopRight.dx, deleteIconCenter.dx + (iconSize / 2) + padding + border); expect(chipTopRight.dy, deleteIconCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between delete icon and label. labelTopRight = tester.getTopRight(find.byType(Container)); expect(labelTopRight.dx, deleteIconCenter.dx - (iconSize / 2) - labelPadding); }); testWidgets('RawChip delete icon layout constraints can be customized', (WidgetTester tester) async { const double border = 1.0; const double iconSize = 18.0; const double labelPadding = 8.0; const double padding = 8.0; const Size labelSize = Size(100, 100); Widget buildChip({BoxConstraints? deleteIconBoxConstraints}) { return wrapForChip( child: Center( child: RawChip( deleteIconBoxConstraints: deleteIconBoxConstraints, onDeleted: () { }, label: Container( width: labelSize.width, height: labelSize.width, color: const Color(0xFFFF0000), ), ), ), ); } // Test default delete icon layout constraints. await tester.pumpWidget(buildChip()); expect(tester.getSize(find.byType(RawChip)).width, equals(234.0)); expect(tester.getSize(find.byType(RawChip)).height, equals(118.0)); // Calculate the distance between delete icon and chip edges. Offset chipTopRight = tester.getTopRight(find.byWidget(getMaterial(tester))); final Offset deleteIconCenter = tester.getCenter(find.byIcon(Icons.cancel)); expect(chipTopRight.dx, deleteIconCenter.dx + (labelSize.width / 2) + padding + border); expect(chipTopRight.dy, deleteIconCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between delete icon and label. Offset labelTopRight = tester.getTopRight(find.byType(Container)); expect(labelTopRight.dx, deleteIconCenter.dx - (labelSize.width / 2) - labelPadding); // Test custom avatar layout constraints. await tester.pumpWidget(buildChip( deleteIconBoxConstraints: const BoxConstraints.tightForFinite(), )); await tester.pump(); expect(tester.getSize(find.byType(RawChip)).width, equals(152.0)); expect(tester.getSize(find.byType(RawChip )).height, equals(118.0)); // Calculate the distance between delete icon and chip edges. chipTopRight = tester.getTopRight(find.byWidget(getMaterial(tester))); expect(chipTopRight.dx, deleteIconCenter.dx + (iconSize / 2) + padding + border); expect(chipTopRight.dy, deleteIconCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between delete icon and label. labelTopRight = tester.getTopRight(find.byType(Container)); expect(labelTopRight.dx, deleteIconCenter.dx - (iconSize / 2) - labelPadding); }); testWidgets('Default delete button InkWell shape', (WidgetTester tester) async { await tester.pumpWidget(wrapForChip( child: Center( child: RawChip( onDeleted: () { }, label: const Text('RawChip'), ), ), )); final InkWell deleteButtonInkWell = tester.widget<InkWell>(find.ancestor( of: find.byIcon(Icons.cancel), matching: find.byType(InkWell).last, )); expect(deleteButtonInkWell.customBorder, const CircleBorder()); }); testWidgets('Default delete button overlay', (WidgetTester tester) async { final ThemeData theme = ThemeData(); await tester.pumpWidget(wrapForChip( child: Center( child: RawChip( onDeleted: () { }, label: const Text('RawChip'), ), ), theme: theme, )); RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, isNot(paints..rect(color: theme.hoverColor))); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); // Hover over the delete icon. final Offset centerOfDeleteButton = tester.getCenter(find.byType(Icon)); final TestGesture hoverGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await hoverGesture.moveTo(centerOfDeleteButton); addTearDown(hoverGesture.removePointer); await tester.pumpAndSettle(); inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..rect(color: theme.hoverColor)); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 1)); const Rect expectedClipRect = Rect.fromLTRB(124.7, 10.0, 142.7, 28.0); final Path expectedClipPath = Path()..addRect(expectedClipRect); expect( inkFeatures, paints..clipPath(pathMatcher: coversSameAreaAs( expectedClipPath, areaToCompare: expectedClipRect.inflate(48.0), sampleSize: 100, )), ); }); group('Material 2', () { // These tests are only relevant for Material 2. Once Material 2 // support is deprecated and the APIs are removed, these tests // can be deleted. testWidgets('M2 Chip defaults', (WidgetTester tester) async { late TextTheme textTheme; Widget buildFrame(Brightness brightness) { return MaterialApp( theme: ThemeData(brightness: brightness, useMaterial3: false), home: Scaffold( body: Center( child: Builder( builder: (BuildContext context) { textTheme = Theme.of(context).textTheme; return Chip( avatar: const CircleAvatar(child: Text('A')), label: const Text('Chip A'), onDeleted: () { }, ); }, ), ), ), ); } await tester.pumpWidget(buildFrame(Brightness.light)); expect(getMaterialBox(tester), paints..rrect()..circle(color: const Color(0xff1976d2))); expect(tester.getSize(find.byType(Chip)), const Size(156.0, 48.0)); expect(getMaterial(tester).color, null); expect(getMaterial(tester).elevation, 0); expect(getMaterial(tester).shape, const StadiumBorder()); expect(getIconData(tester).color?.value, 0xffffffff); expect(getIconData(tester).opacity, null); expect(getIconData(tester).size, null); TextStyle labelStyle = getLabelStyle(tester, 'Chip A').style; expect(labelStyle.color?.value, 0xde000000); expect(labelStyle.fontFamily, textTheme.bodyLarge?.fontFamily); expect(labelStyle.fontFamilyFallback, textTheme.bodyLarge?.fontFamilyFallback); expect(labelStyle.fontFeatures, textTheme.bodyLarge?.fontFeatures); expect(labelStyle.fontSize, textTheme.bodyLarge?.fontSize); expect(labelStyle.fontStyle, textTheme.bodyLarge?.fontStyle); expect(labelStyle.fontWeight, textTheme.bodyLarge?.fontWeight); expect(labelStyle.height, textTheme.bodyLarge?.height); expect(labelStyle.inherit, textTheme.bodyLarge?.inherit); expect(labelStyle.leadingDistribution, textTheme.bodyLarge?.leadingDistribution); expect(labelStyle.letterSpacing, textTheme.bodyLarge?.letterSpacing); expect(labelStyle.overflow, textTheme.bodyLarge?.overflow); expect(labelStyle.textBaseline, textTheme.bodyLarge?.textBaseline); expect(labelStyle.wordSpacing, textTheme.bodyLarge?.wordSpacing); await tester.pumpWidget(buildFrame(Brightness.dark)); await tester.pumpAndSettle(); // Theme transition animation expect(getMaterialBox(tester), paints..rrect(color: const Color(0x1fffffff))); expect(tester.getSize(find.byType(Chip)), const Size(156.0, 48.0)); expect(getMaterial(tester).color, null); expect(getMaterial(tester).elevation, 0); expect(getMaterial(tester).shape, const StadiumBorder()); expect(getIconData(tester).color?.value, 0xffffffff); expect(getIconData(tester).opacity, null); expect(getIconData(tester).size, null); labelStyle = getLabelStyle(tester, 'Chip A').style; expect(labelStyle.color?.value, 0xdeffffff); expect(labelStyle.fontFamily, textTheme.bodyLarge?.fontFamily); expect(labelStyle.fontFamilyFallback, textTheme.bodyLarge?.fontFamilyFallback); expect(labelStyle.fontFeatures, textTheme.bodyLarge?.fontFeatures); expect(labelStyle.fontSize, textTheme.bodyLarge?.fontSize); expect(labelStyle.fontStyle, textTheme.bodyLarge?.fontStyle); expect(labelStyle.fontWeight, textTheme.bodyLarge?.fontWeight); expect(labelStyle.height, textTheme.bodyLarge?.height); expect(labelStyle.inherit, textTheme.bodyLarge?.inherit); expect(labelStyle.leadingDistribution, textTheme.bodyLarge?.leadingDistribution); expect(labelStyle.letterSpacing, textTheme.bodyLarge?.letterSpacing); expect(labelStyle.overflow, textTheme.bodyLarge?.overflow); expect(labelStyle.textBaseline, textTheme.bodyLarge?.textBaseline); expect(labelStyle.wordSpacing, textTheme.bodyLarge?.wordSpacing); }); testWidgets('Chip uses the right theme colors for the right components', (WidgetTester tester) async { final ThemeData themeData = ThemeData( platform: TargetPlatform.android, primarySwatch: Colors.blue, useMaterial3: false, ); final ChipThemeData defaultChipTheme = ChipThemeData.fromDefaults( brightness: themeData.brightness, secondaryColor: Colors.blue, labelStyle: themeData.textTheme.bodyLarge!, ); bool value = false; Widget buildApp({ ChipThemeData? chipTheme, Widget? avatar, Widget? deleteIcon, bool isSelectable = true, bool isPressable = false, bool isDeletable = true, bool showCheckmark = true, }) { chipTheme ??= defaultChipTheme; return wrapForChip( child: Theme( data: themeData, child: ChipTheme( data: chipTheme, child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RawChip( showCheckmark: showCheckmark, onDeleted: isDeletable ? () { } : null, avatar: avatar, deleteIcon: deleteIcon, isEnabled: isSelectable || isPressable, shape: chipTheme?.shape, selected: isSelectable && value, label: Text('$value'), onSelected: isSelectable ? (bool newValue) { setState(() { value = newValue; }); } : null, onPressed: isPressable ? () { setState(() { value = true; }); } : null, ); }), ), ), ); } await tester.pumpWidget(buildApp()); RenderBox materialBox = getMaterialBox(tester); IconThemeData iconData = getIconData(tester); DefaultTextStyle labelStyle = getLabelStyle(tester, 'false'); // Check default theme for enabled chip. expect(materialBox, paints..rrect(color: defaultChipTheme.backgroundColor)); expect(iconData.color, equals(const Color(0xde000000))); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); // Check default theme for disabled chip. await tester.pumpWidget(buildApp(isSelectable: false)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); labelStyle = getLabelStyle(tester, 'false'); expect(materialBox, paints..rrect(color: defaultChipTheme.disabledColor)); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); // Check default theme for enabled and selected chip. await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); await tester.tap(find.byType(RawChip)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); expect(materialBox, paints..rrect(color: defaultChipTheme.selectedColor)); // Check default theme for disabled and selected chip. await tester.pumpWidget(buildApp(isSelectable: false)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); labelStyle = getLabelStyle(tester, 'true'); expect(materialBox, paints..rrect(color: defaultChipTheme.disabledColor)); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); // Enable the chip again. await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); // Tap to unselect the chip. await tester.tap(find.byType(RawChip)); await tester.pumpAndSettle(); // Apply a custom theme. const Color customColor1 = Color(0xcafefeed); const Color customColor2 = Color(0xdeadbeef); const Color customColor3 = Color(0xbeefcafe); const Color customColor4 = Color(0xaddedabe); final ChipThemeData customTheme = defaultChipTheme.copyWith( brightness: Brightness.dark, backgroundColor: customColor1, disabledColor: customColor2, selectedColor: customColor3, deleteIconColor: customColor4, ); await tester.pumpWidget(buildApp(chipTheme: customTheme)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); iconData = getIconData(tester); labelStyle = getLabelStyle(tester, 'false'); // Check custom theme for enabled chip. expect(materialBox, paints..rrect(color: customTheme.backgroundColor)); expect(iconData.color, equals(customTheme.deleteIconColor)); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); // Check custom theme with disabled widget. await tester.pumpWidget(buildApp( chipTheme: customTheme, isSelectable: false, )); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); labelStyle = getLabelStyle(tester, 'false'); expect(materialBox, paints..rrect(color: customTheme.disabledColor)); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); // Check custom theme for enabled and selected chip. await tester.pumpWidget(buildApp(chipTheme: customTheme)); await tester.pumpAndSettle(); await tester.tap(find.byType(RawChip)); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); expect(materialBox, paints..rrect(color: customTheme.selectedColor)); // Check custom theme for disabled and selected chip. await tester.pumpWidget(buildApp( chipTheme: customTheme, isSelectable: false, )); await tester.pumpAndSettle(); materialBox = getMaterialBox(tester); labelStyle = getLabelStyle(tester, 'true'); expect(materialBox, paints..rrect(color: customTheme.disabledColor)); expect(labelStyle.style.color, equals(Colors.black.withAlpha(0xde))); }); }); } class _MaterialStateOutlinedBorder extends StadiumBorder implements MaterialStateOutlinedBorder { const _MaterialStateOutlinedBorder(this.resolver); final MaterialPropertyResolver<OutlinedBorder?> resolver; @override OutlinedBorder? resolve(Set<MaterialState> states) => resolver(states); } class _MaterialStateBorderSide extends MaterialStateBorderSide { const _MaterialStateBorderSide(this.resolver); final MaterialPropertyResolver<BorderSide?> resolver; @override BorderSide? resolve(Set<MaterialState> states) => resolver(states); }
flutter/packages/flutter/test/material/chip_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/chip_test.dart", "repo_id": "flutter", "token_count": 90274 }
659
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; MaterialApp _appWithDialog(WidgetTester tester, Widget dialog, { ThemeData? theme }) { return MaterialApp( theme: theme, home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { showDialog<void>( context: context, builder: (BuildContext context) { return RepaintBoundary(key: _painterKey, child: dialog); }, ); }, ), ); }, ), ), ); } final Key _painterKey = UniqueKey(); Material _getMaterialFromDialog(WidgetTester tester) { return tester.widget<Material>(find.descendant(of: find.byType(AlertDialog), matching: find.byType(Material))); } RenderParagraph _getTextRenderObject(WidgetTester tester, String text) { return tester.element<StatelessElement>(find.text(text)).renderObject! as RenderParagraph; } void main() { test('DialogTheme copyWith, ==, hashCode basics', () { expect(const DialogTheme(), const DialogTheme().copyWith()); expect(const DialogTheme().hashCode, const DialogTheme().copyWith().hashCode); }); test('DialogTheme lerp special cases', () { expect(DialogTheme.lerp(null, null, 0), const DialogTheme()); const DialogTheme theme = DialogTheme(); expect(identical(DialogTheme.lerp(theme, theme, 0.5), theme), true); }); testWidgets('Dialog Theme implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const DialogTheme( backgroundColor: Color(0xff123456), elevation: 8.0, shadowColor: Color(0xff000001), surfaceTintColor: Color(0xff000002), alignment: Alignment.bottomLeft, iconColor: Color(0xff654321), titleTextStyle: TextStyle(color: Color(0xffffffff)), contentTextStyle: TextStyle(color: Color(0xff000000)), actionsPadding: EdgeInsets.all(8.0), barrierColor: Color(0xff000005), insetPadding: EdgeInsets.all(20.0), ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode n) => n.toString()).toList(); expect(description, <String>[ 'backgroundColor: Color(0xff123456)', 'elevation: 8.0', 'shadowColor: Color(0xff000001)', 'surfaceTintColor: Color(0xff000002)', 'alignment: Alignment.bottomLeft', 'iconColor: Color(0xff654321)', 'titleTextStyle: TextStyle(inherit: true, color: Color(0xffffffff))', 'contentTextStyle: TextStyle(inherit: true, color: Color(0xff000000))', 'actionsPadding: EdgeInsets.all(8.0)', 'barrierColor: Color(0xff000005)', 'insetPadding: EdgeInsets.all(20.0)', ]); }); testWidgets('Dialog background color', (WidgetTester tester) async { const Color customColor = Colors.pink; const AlertDialog dialog = AlertDialog( title: Text('Title'), actions: <Widget>[ ], ); final ThemeData theme = ThemeData(dialogTheme: const DialogTheme(backgroundColor: customColor)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.color, customColor); }); testWidgets('Custom dialog elevation', (WidgetTester tester) async { const double customElevation = 12.0; const Color shadowColor = Color(0xFF000001); const Color surfaceTintColor = Color(0xFF000002); const AlertDialog dialog = AlertDialog( title: Text('Title'), actions: <Widget>[ ], ); final ThemeData theme = ThemeData( dialogTheme: const DialogTheme( elevation: customElevation, shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, ), ); await tester.pumpWidget( _appWithDialog(tester, dialog, theme: theme), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.elevation, customElevation); expect(materialWidget.shadowColor, shadowColor); expect(materialWidget.surfaceTintColor, surfaceTintColor); }); testWidgets('Custom dialog shape', (WidgetTester tester) async { const RoundedRectangleBorder customBorder = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))); const AlertDialog dialog = AlertDialog( title: Text('Title'), actions: <Widget>[ ], ); final ThemeData theme = ThemeData(dialogTheme: const DialogTheme(shape: customBorder)); await tester.pumpWidget( _appWithDialog(tester, dialog, theme: theme), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.shape, customBorder); }); testWidgets('Custom dialog alignment', (WidgetTester tester) async { const AlertDialog dialog = AlertDialog( title: Text('Title'), actions: <Widget>[ ], ); final ThemeData theme = ThemeData(dialogTheme: const DialogTheme(alignment: Alignment.bottomLeft)); await tester.pumpWidget( _appWithDialog(tester, dialog, theme: theme), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Offset bottomLeft = tester.getBottomLeft( find.descendant(of: find.byType(Dialog), matching: find.byType(Material)), ); expect(bottomLeft.dx, 40.0); expect(bottomLeft.dy, 576.0); }); testWidgets('Material3 - Dialog alignment takes priority over theme', (WidgetTester tester) async { const AlertDialog dialog = AlertDialog( title: Text('Title'), actions: <Widget>[ ], alignment: Alignment.topRight, ); final ThemeData theme = ThemeData( useMaterial3: true, dialogTheme: const DialogTheme(alignment: Alignment.bottomLeft), ); await tester.pumpWidget( _appWithDialog(tester, dialog, theme: theme), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Offset bottomLeft = tester.getBottomLeft( find.descendant(of: find.byType(Dialog), matching: find.byType(Material)), ); expect(bottomLeft.dx, 480.0); if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933 expect(bottomLeft.dy, 124.0); } }); testWidgets('Material2 - Dialog alignment takes priority over theme', (WidgetTester tester) async { const AlertDialog dialog = AlertDialog( title: Text('Title'), actions: <Widget>[ ], alignment: Alignment.topRight, ); final ThemeData theme = ThemeData(useMaterial3: false, dialogTheme: const DialogTheme(alignment: Alignment.bottomLeft)); await tester.pumpWidget( _appWithDialog(tester, dialog, theme: theme), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Offset bottomLeft = tester.getBottomLeft( find.descendant(of: find.byType(Dialog), matching: find.byType(Material)), ); expect(bottomLeft.dx, 480.0); expect(bottomLeft.dy, 104.0); }); testWidgets('Material3 - Custom dialog shape matches golden', (WidgetTester tester) async { const RoundedRectangleBorder customBorder = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))); const AlertDialog dialog = AlertDialog( title: Text('Title'), actions: <Widget>[ ], ); final ThemeData theme = ThemeData( useMaterial3: true, dialogTheme: const DialogTheme(shape: customBorder), ); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); await expectLater( find.byKey(_painterKey), matchesGoldenFile('m3_dialog_theme.dialog_with_custom_border.png'), ); }); testWidgets('Material2 - Custom dialog shape matches golden', (WidgetTester tester) async { const RoundedRectangleBorder customBorder = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))); const AlertDialog dialog = AlertDialog( title: Text('Title'), actions: <Widget>[ ], ); final ThemeData theme = ThemeData(useMaterial3: false, dialogTheme: const DialogTheme(shape: customBorder)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); await expectLater( find.byKey(_painterKey), matchesGoldenFile('m2_dialog_theme.dialog_with_custom_border.png'), ); }); testWidgets('Custom Icon Color - Constructor Param - highest preference', (WidgetTester tester) async { const Color iconColor = Colors.pink, dialogThemeColor = Colors.green, iconThemeColor = Colors.yellow; final ThemeData theme = ThemeData( iconTheme: const IconThemeData(color: iconThemeColor), dialogTheme: const DialogTheme(iconColor: dialogThemeColor), ); const AlertDialog dialog = AlertDialog( icon: Icon(Icons.ac_unit), iconColor: iconColor, actions: <Widget>[ ], ); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // first is Text('X') final RichText text = tester.widget(find.byType(RichText).last); expect(text.text.style!.color, iconColor); }); testWidgets('Custom Icon Color - Dialog Theme - preference over Theme', (WidgetTester tester) async { const Color dialogThemeColor = Colors.green, iconThemeColor = Colors.yellow; final ThemeData theme = ThemeData( iconTheme: const IconThemeData(color: iconThemeColor), dialogTheme: const DialogTheme(iconColor: dialogThemeColor), ); const AlertDialog dialog = AlertDialog( icon: Icon(Icons.ac_unit), actions: <Widget>[ ], ); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // first is Text('X') final RichText text = tester.widget(find.byType(RichText).last); expect(text.text.style!.color, dialogThemeColor); }); testWidgets('Material3 - Custom Icon Color - Theme - lowest preference', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); const AlertDialog dialog = AlertDialog( icon: Icon(Icons.ac_unit), actions: <Widget>[ ], ); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // first is Text('X') final RichText text = tester.widget(find.byType(RichText).last); expect(text.text.style!.color, theme.colorScheme.secondary); }); testWidgets('Material2 - Custom Icon Color - Theme - lowest preference', (WidgetTester tester) async { const Color iconThemeColor = Colors.yellow; final ThemeData theme = ThemeData(useMaterial3: false, iconTheme: const IconThemeData(color: iconThemeColor)); const AlertDialog dialog = AlertDialog( icon: Icon(Icons.ac_unit), actions: <Widget>[ ], ); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // first is Text('X') final RichText text = tester.widget(find.byType(RichText).last); expect(text.text.style!.color, iconThemeColor); }); testWidgets('Custom Title Text Style - Constructor Param', (WidgetTester tester) async { const String titleText = 'Title'; const TextStyle titleTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog( title: Text(titleText), titleTextStyle: titleTextStyle, actions: <Widget>[ ], ); await tester.pumpWidget(_appWithDialog(tester, dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph title = _getTextRenderObject(tester, titleText); expect(title.text.style, titleTextStyle); }); testWidgets('Custom Title Text Style - Dialog Theme', (WidgetTester tester) async { const String titleText = 'Title'; const TextStyle titleTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog( title: Text(titleText), actions: <Widget>[ ], ); final ThemeData theme = ThemeData(dialogTheme: const DialogTheme(titleTextStyle: titleTextStyle)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph title = _getTextRenderObject(tester, titleText); expect(title.text.style, titleTextStyle); }); testWidgets('Material3 - Custom Title Text Style - Theme', (WidgetTester tester) async { const String titleText = 'Title'; const TextStyle titleTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog(title: Text(titleText)); final ThemeData theme = ThemeData(useMaterial3: true, textTheme: const TextTheme(headlineSmall: titleTextStyle)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph title = _getTextRenderObject(tester, titleText); expect(title.text.style!.color, titleTextStyle.color); }); testWidgets('Material2 - Custom Title Text Style - Theme', (WidgetTester tester) async { const String titleText = 'Title'; const TextStyle titleTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog(title: Text(titleText)); final ThemeData theme = ThemeData(useMaterial3: false, textTheme: const TextTheme(titleLarge: titleTextStyle)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph title = _getTextRenderObject(tester, titleText); expect(title.text.style!.color, titleTextStyle.color); }); testWidgets('Simple Dialog - Custom Title Text Style - Constructor Param', (WidgetTester tester) async { const String titleText = 'Title'; const TextStyle titleTextStyle = TextStyle(color: Colors.pink); const SimpleDialog dialog = SimpleDialog( title: Text(titleText), titleTextStyle: titleTextStyle, ); await tester.pumpWidget(_appWithDialog(tester, dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph title = _getTextRenderObject(tester, titleText); expect(title.text.style, titleTextStyle); }); testWidgets('Simple Dialog - Custom Title Text Style - Dialog Theme', (WidgetTester tester) async { const String titleText = 'Title'; const TextStyle titleTextStyle = TextStyle(color: Colors.pink); const SimpleDialog dialog = SimpleDialog( title: Text(titleText), ); final ThemeData theme = ThemeData(dialogTheme: const DialogTheme(titleTextStyle: titleTextStyle)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph title = _getTextRenderObject(tester, titleText); expect(title.text.style, titleTextStyle); }); testWidgets('Simple Dialog - Custom Title Text Style - Theme', (WidgetTester tester) async { const String titleText = 'Title'; const TextStyle titleTextStyle = TextStyle(color: Colors.pink); const SimpleDialog dialog = SimpleDialog( title: Text(titleText), ); final ThemeData theme = ThemeData(textTheme: const TextTheme(titleLarge: titleTextStyle)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph title = _getTextRenderObject(tester, titleText); expect(title.text.style!.color, titleTextStyle.color); }); testWidgets('Custom Content Text Style - Constructor Param', (WidgetTester tester) async { const String contentText = 'Content'; const TextStyle contentTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog( content: Text(contentText), contentTextStyle: contentTextStyle, actions: <Widget>[ ], ); await tester.pumpWidget(_appWithDialog(tester, dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph content = _getTextRenderObject(tester, contentText); expect(content.text.style, contentTextStyle); }); testWidgets('Custom Content Text Style - Dialog Theme', (WidgetTester tester) async { const String contentText = 'Content'; const TextStyle contentTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog( content: Text(contentText), actions: <Widget>[ ], ); final ThemeData theme = ThemeData(dialogTheme: const DialogTheme(contentTextStyle: contentTextStyle)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph content = _getTextRenderObject(tester, contentText); expect(content.text.style, contentTextStyle); }); testWidgets('Material3 - Custom Content Text Style - Theme', (WidgetTester tester) async { const String contentText = 'Content'; const TextStyle contentTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog(content: Text(contentText),); final ThemeData theme = ThemeData(useMaterial3: true, textTheme: const TextTheme(bodyMedium: contentTextStyle)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph content = _getTextRenderObject(tester, contentText); expect(content.text.style!.color, contentTextStyle.color); }); testWidgets('Material2 - Custom Content Text Style - Theme', (WidgetTester tester) async { const String contentText = 'Content'; const TextStyle contentTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog(content: Text(contentText)); final ThemeData theme = ThemeData(useMaterial3: false, textTheme: const TextTheme(titleMedium: contentTextStyle)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph content = _getTextRenderObject(tester, contentText); expect(content.text.style!.color, contentTextStyle.color); }); testWidgets('Custom barrierColor - Theme', (WidgetTester tester) async { const Color barrierColor = Colors.blue; const SimpleDialog dialog = SimpleDialog(); final ThemeData theme = ThemeData(dialogTheme: const DialogTheme(barrierColor: barrierColor)); await tester.pumpWidget(_appWithDialog(tester, dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final ModalBarrier modalBarrier = tester.widget(find.byType(ModalBarrier).last); expect(modalBarrier.color, barrierColor); }); testWidgets('DialogTheme.insetPadding updates Dialog insetPadding', (WidgetTester tester) async { // The default testing screen (800, 600) const Rect screenRect = Rect.fromLTRB(0.0, 0.0, 800.0, 600.0); const DialogTheme dialogTheme = DialogTheme( insetPadding: EdgeInsets.fromLTRB(10, 15, 20, 25) ); const Dialog dialog = Dialog(child: Placeholder()); await tester.pumpWidget(_appWithDialog( tester, dialog, theme: ThemeData(dialogTheme: dialogTheme), )); await tester.tap(find.text('X')); await tester.pump(); expect( tester.getRect(find.byType(Placeholder)), Rect.fromLTRB( screenRect.left + dialogTheme.insetPadding!.left, screenRect.top + dialogTheme.insetPadding!.top, screenRect.right - dialogTheme.insetPadding!.right, screenRect.bottom - dialogTheme.insetPadding!.bottom, ), ); }); }
flutter/packages/flutter/test/material/dialog_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/dialog_theme_test.dart", "repo_id": "flutter", "token_count": 7371 }
660
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; class TestIcon extends StatefulWidget { const TestIcon({super.key}); @override TestIconState createState() => TestIconState(); } class TestIconState extends State<TestIcon> { late IconThemeData iconTheme; @override Widget build(BuildContext context) { iconTheme = IconTheme.of(context); return const Icon(Icons.expand_more); } } class TestText extends StatefulWidget { const TestText(this.text, {super.key}); final String text; @override TestTextState createState() => TestTextState(); } class TestTextState extends State<TestText> { late TextStyle textStyle; @override Widget build(BuildContext context) { textStyle = DefaultTextStyle.of(context).style; return Text(widget.text); } } void main() { Material getMaterial(WidgetTester tester) { return tester.widget<Material>(find.descendant( of: find.byType(ExpansionTile), matching: find.byType(Material), )); } test('ExpansionTileThemeData copyWith, ==, hashCode basics', () { expect(const ExpansionTileThemeData(), const ExpansionTileThemeData().copyWith()); expect(const ExpansionTileThemeData().hashCode, const ExpansionTileThemeData().copyWith().hashCode); }); test('ExpansionTileThemeData lerp special cases', () { expect(ExpansionTileThemeData.lerp(null, null, 0), null); const ExpansionTileThemeData data = ExpansionTileThemeData(); expect(identical(ExpansionTileThemeData.lerp(data, data, 0.5), data), true); }); test('ExpansionTileThemeData defaults', () { const ExpansionTileThemeData theme = ExpansionTileThemeData(); expect(theme.backgroundColor, null); expect(theme.collapsedBackgroundColor, null); expect(theme.tilePadding, null); expect(theme.expandedAlignment, null); expect(theme.childrenPadding, null); expect(theme.iconColor, null); expect(theme.collapsedIconColor, null); expect(theme.textColor, null); expect(theme.collapsedTextColor, null); expect(theme.shape, null); expect(theme.collapsedShape, null); expect(theme.clipBehavior, null); expect(theme.expansionAnimationStyle, null); }); testWidgets('Default ExpansionTileThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const TooltipThemeData().debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[]); }); testWidgets('ExpansionTileThemeData implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); ExpansionTileThemeData( backgroundColor: const Color(0xff000000), collapsedBackgroundColor: const Color(0xff6f83fc), tilePadding: const EdgeInsets.all(20.0), expandedAlignment: Alignment.bottomCenter, childrenPadding: const EdgeInsets.all(10.0), iconColor: const Color(0xffa7c61c), collapsedIconColor: const Color(0xffdd0b1f), textColor: const Color(0xffffffff), collapsedTextColor: const Color(0xff522bab), shape: const Border(), collapsedShape: const Border(), clipBehavior: Clip.antiAlias, expansionAnimationStyle: AnimationStyle(curve: Curves.easeInOut), ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, equalsIgnoringHashCodes(<String>[ 'backgroundColor: Color(0xff000000)', 'collapsedBackgroundColor: Color(0xff6f83fc)', 'tilePadding: EdgeInsets.all(20.0)', 'expandedAlignment: Alignment.bottomCenter', 'childrenPadding: EdgeInsets.all(10.0)', 'iconColor: Color(0xffa7c61c)', 'collapsedIconColor: Color(0xffdd0b1f)', 'textColor: Color(0xffffffff)', 'collapsedTextColor: Color(0xff522bab)', 'shape: Border.all(BorderSide(width: 0.0, style: none))', 'collapsedShape: Border.all(BorderSide(width: 0.0, style: none))', 'clipBehavior: Clip.antiAlias', 'expansionAnimationStyle: AnimationStyle#983ac(curve: Cubic(0.42, 0.00, 0.58, 1.00))', ])); }); testWidgets('ExpansionTileTheme - collapsed', (WidgetTester tester) async { final Key tileKey = UniqueKey(); final Key titleKey = UniqueKey(); final Key iconKey = UniqueKey(); const Color backgroundColor = Colors.orange; const Color collapsedBackgroundColor = Colors.red; const Color iconColor = Colors.green; const Color collapsedIconColor = Colors.blue; const Color textColor = Colors.black; const Color collapsedTextColor = Colors.white; const ShapeBorder shape = Border( top: BorderSide(color: Colors.red), bottom: BorderSide(color: Colors.red), ); const ShapeBorder collapsedShape = Border( top: BorderSide(color: Colors.green), bottom: BorderSide(color: Colors.green), ); const Clip clipBehavior = Clip.antiAlias; await tester.pumpWidget( MaterialApp( theme: ThemeData( expansionTileTheme: const ExpansionTileThemeData( backgroundColor: backgroundColor, collapsedBackgroundColor: collapsedBackgroundColor, tilePadding: EdgeInsets.fromLTRB(8, 12, 4, 10), expandedAlignment: Alignment.centerRight, childrenPadding: EdgeInsets.all(20.0), iconColor: iconColor, collapsedIconColor: collapsedIconColor, textColor: textColor, collapsedTextColor: collapsedTextColor, shape: shape, collapsedShape: collapsedShape, clipBehavior: clipBehavior, ), ), home: Material( child: Center( child: ExpansionTile( key: tileKey, title: TestText('Collapsed Tile', key: titleKey), trailing: TestIcon(key: iconKey), children: const <Widget>[Text('Tile 1')], ), ), ), ), ); // When a custom shape is provided, ExpansionTile will use the // Material widget to draw the shape and background color // instead of a Container. final Material material = getMaterial(tester); // ExpansionTile should have Clip.antiAlias as clipBehavior. expect(material.clipBehavior, clipBehavior); // Check the tile's collapsed background color when collapsedBackgroundColor is applied. expect(material.color, collapsedBackgroundColor); final Rect titleRect = tester.getRect(find.text('Collapsed Tile')); final Rect trailingRect = tester.getRect(find.byIcon(Icons.expand_more)); final Rect listTileRect = tester.getRect(find.byType(ListTile)); final Rect tallerWidget = titleRect.height > trailingRect.height ? titleRect : trailingRect; // Check the positions of title and trailing Widgets, after padding is applied. expect(listTileRect.left, titleRect.left - 8); expect(listTileRect.right, trailingRect.right + 4); // Calculate the remaining height of ListTile from the default height. final double remainingHeight = 56 - tallerWidget.height; expect(listTileRect.top, tallerWidget.top - remainingHeight / 2 - 12); expect(listTileRect.bottom, tallerWidget.bottom + remainingHeight / 2 + 10); Color getIconColor() => tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color!; Color getTextColor() => tester.state<TestTextState>(find.byType(TestText)).textStyle.color!; // Check the collapsed icon color when iconColor is applied. expect(getIconColor(), collapsedIconColor); // Check the collapsed text color when textColor is applied. expect(getTextColor(), collapsedTextColor); // Check the collapsed ShapeBorder when shape is applied. expect(material.shape, collapsedShape); }); testWidgets('ExpansionTileTheme - expanded', (WidgetTester tester) async { final Key tileKey = UniqueKey(); final Key titleKey = UniqueKey(); final Key iconKey = UniqueKey(); const Color backgroundColor = Colors.orange; const Color collapsedBackgroundColor = Colors.red; const Color iconColor = Colors.green; const Color collapsedIconColor = Colors.blue; const Color textColor = Colors.black; const Color collapsedTextColor = Colors.white; const ShapeBorder shape = Border( top: BorderSide(color: Colors.red), bottom: BorderSide(color: Colors.red), ); const ShapeBorder collapsedShape = Border( top: BorderSide(color: Colors.green), bottom: BorderSide(color: Colors.green), ); const Clip clipBehavior = Clip.none; await tester.pumpWidget( MaterialApp( theme: ThemeData( expansionTileTheme: const ExpansionTileThemeData( backgroundColor: backgroundColor, collapsedBackgroundColor: collapsedBackgroundColor, tilePadding: EdgeInsets.fromLTRB(8, 12, 4, 10), expandedAlignment: Alignment.centerRight, childrenPadding: EdgeInsets.all(20.0), iconColor: iconColor, collapsedIconColor: collapsedIconColor, textColor: textColor, collapsedTextColor: collapsedTextColor, shape: shape, collapsedShape: collapsedShape, clipBehavior: clipBehavior, ), ), home: Material( child: Center( child: ExpansionTile( key: tileKey, initiallyExpanded: true, title: TestText('Expanded Tile', key: titleKey), trailing: TestIcon(key: iconKey), children: const <Widget>[Text('Tile 1')], ), ), ), ), ); // When a custom shape is provided, ExpansionTile will use the // Material widget to draw the shape and background color // instead of a Container. final Material material = getMaterial(tester); // Check the tile's background color when backgroundColor is applied. expect(material.color, backgroundColor); final Rect titleRect = tester.getRect(find.text('Expanded Tile')); final Rect trailingRect = tester.getRect(find.byIcon(Icons.expand_more)); final Rect listTileRect = tester.getRect(find.byType(ListTile)); final Rect tallerWidget = titleRect.height > trailingRect.height ? titleRect : trailingRect; // Check the positions of title and trailing Widgets, after padding is applied. expect(listTileRect.left, titleRect.left - 8); expect(listTileRect.right, trailingRect.right + 4); // Calculate the remaining height of ListTile from the default height. final double remainingHeight = 56 - tallerWidget.height; expect(listTileRect.top, tallerWidget.top - remainingHeight / 2 - 12); expect(listTileRect.bottom, tallerWidget.bottom + remainingHeight / 2 + 10); Color getIconColor() => tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color!; Color getTextColor() => tester.state<TestTextState>(find.byType(TestText)).textStyle.color!; // Check the expanded icon color when iconColor is applied. expect(getIconColor(), iconColor); // Check the expanded text color when textColor is applied. expect(getTextColor(), textColor); // Check the expanded ShapeBorder when shape is applied. expect(material.shape, shape); // Check the clipBehavior when shape is applied. expect(material.clipBehavior, clipBehavior); // Check the child position when expandedAlignment is applied. final Rect childRect = tester.getRect(find.text('Tile 1')); expect(childRect.right, 800 - 20); expect(childRect.left, 800 - childRect.width - 20); // Check the child padding when childrenPadding is applied. final Rect paddingRect = tester.getRect(find.byType(Padding).last); expect(childRect.top, paddingRect.top + 20); expect(childRect.left, paddingRect.left + 20); expect(childRect.right, paddingRect.right - 20); expect(childRect.bottom, paddingRect.bottom - 20); }); testWidgets('Override ExpansionTile animation using ExpansionTileThemeData.AnimationStyle', (WidgetTester tester) async { const Key expansionTileKey = Key('expansionTileKey'); Widget buildExpansionTile({ AnimationStyle? animationStyle }) { return MaterialApp( theme: ThemeData( expansionTileTheme: ExpansionTileThemeData( expansionAnimationStyle: animationStyle, ), ), home: const Material( child: Center( child: ExpansionTile( key: expansionTileKey, title: TestText('title'), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), ), ); } await tester.pumpWidget(buildExpansionTile()); double getHeight(Key key) => tester.getSize(find.byKey(key)).height; // Test initial ExpansionTile height. expect(getHeight(expansionTileKey), 58.0); // Test the default expansion animation. await tester.tap(find.text('title')); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); // Advance the animation by 1/4 of its duration. expect(getHeight(expansionTileKey), closeTo(67.4, 0.1)); await tester.pump(const Duration(milliseconds: 50)); // Advance the animation by 2/4 of its duration. expect(getHeight(expansionTileKey), closeTo(89.6, 0.1)); await tester.pumpAndSettle(); // Advance the animation to the end. expect(getHeight(expansionTileKey), 158.0); // Tap to collapse the ExpansionTile. await tester.tap(find.text('title')); await tester.pumpAndSettle(); // Override the animation duration. await tester.pumpWidget(buildExpansionTile(animationStyle: AnimationStyle(duration: const Duration(milliseconds: 800)))); await tester.pumpAndSettle(); // Test the overridden animation duration. await tester.tap(find.text('title')); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // Advance the animation by 1/4 of its duration. expect(getHeight(expansionTileKey), closeTo(67.4, 0.1)); await tester.pump(const Duration(milliseconds: 200)); // Advance the animation by 2/4 of its duration. expect(getHeight(expansionTileKey), closeTo(89.6, 0.1)); await tester.pumpAndSettle(); // Advance the animation to the end. expect(getHeight(expansionTileKey), 158.0); // Tap to collapse the ExpansionTile. await tester.tap(find.text('title')); await tester.pumpAndSettle(); // Override the animation curve. await tester.pumpWidget(buildExpansionTile(animationStyle: AnimationStyle(curve: Easing.emphasizedDecelerate))); await tester.pumpAndSettle(); // Test the overridden animation curve. await tester.tap(find.text('title')); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); // Advance the animation by 1/4 of its duration. expect(getHeight(expansionTileKey), closeTo(141.2, 0.1)); await tester.pump(const Duration(milliseconds: 50)); // Advance the animation by 2/4 of its duration. expect(getHeight(expansionTileKey), closeTo(153, 0.1)); await tester.pumpAndSettle(); // Advance the animation to the end. expect(getHeight(expansionTileKey), 158.0); // Tap to collapse the ExpansionTile. await tester.tap(find.text('title')); // Test no animation. await tester.pumpWidget(buildExpansionTile(animationStyle: AnimationStyle.noAnimation)); // Tap to expand the ExpansionTile. await tester.tap(find.text('title')); await tester.pump(); expect(getHeight(expansionTileKey), 158.0); }); }
flutter/packages/flutter/test/material/expansion_tile_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/expansion_tile_theme_test.dart", "repo_id": "flutter", "token_count": 5754 }
661
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:platform/platform.dart'; void main() { testWidgets('IconData object test', (WidgetTester tester) async { expect(Icons.account_balance, isNot(equals(Icons.account_box))); expect(Icons.account_balance.hashCode, isNot(equals(Icons.account_box.hashCode))); expect(Icons.account_balance, hasOneLineDescription); }); testWidgets('Icons specify the material font', (WidgetTester tester) async { expect(Icons.clear.fontFamily, 'MaterialIcons'); expect(Icons.search.fontFamily, 'MaterialIcons'); }); testWidgets('Certain icons (and their variants) match text direction', (WidgetTester tester) async { expect(Icons.arrow_back.matchTextDirection, true); expect(Icons.arrow_back_rounded.matchTextDirection, true); expect(Icons.arrow_back_outlined.matchTextDirection, true); expect(Icons.arrow_back_sharp.matchTextDirection, true); expect(Icons.access_time.matchTextDirection, false); expect(Icons.access_time_rounded.matchTextDirection, false); expect(Icons.access_time_outlined.matchTextDirection, false); expect(Icons.access_time_sharp.matchTextDirection, false); }); testWidgets('Adaptive icons are correct on cupertino platforms', (WidgetTester tester) async { expect(Icons.adaptive.arrow_back, Icons.arrow_back_ios); expect(Icons.adaptive.arrow_back_outlined, Icons.arrow_back_ios_outlined); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, }), ); testWidgets('Adaptive icons are correct on non-cupertino platforms', (WidgetTester tester) async { expect(Icons.adaptive.arrow_back, Icons.arrow_back); expect(Icons.adaptive.arrow_back_outlined, Icons.arrow_back_outlined); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.windows, TargetPlatform.linux, }), ); testWidgets('A sample of icons look as expected', (WidgetTester tester) async { await _loadIconFont(); await tester.pumpWidget(const MaterialApp( home: IconTheme( data: IconThemeData(size: 200), child: Wrap( children: <Icon>[ Icon(Icons.ten_k), Icon(Icons.ac_unit), Icon(Icons.local_taxi), Icon(Icons.local_taxi_outlined), Icon(Icons.local_taxi_rounded), Icon(Icons.local_taxi_sharp), Icon(Icons.zoom_out_sharp), ], ), ), )); await expectLater(find.byType(Wrap), matchesGoldenFile('test.icons.sample.png')); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/39998 // Regression test for https://github.com/flutter/flutter/issues/95886 testWidgets('Another sample of icons look as expected', (WidgetTester tester) async { await _loadIconFont(); await tester.pumpWidget(const MaterialApp( home: IconTheme( data: IconThemeData(size: 200), child: Wrap( children: <Icon>[ Icon(Icons.water_drop), Icon(Icons.water_drop_outlined), Icon(Icons.water_drop_rounded), Icon(Icons.water_drop_sharp), ], ), ), )); await expectLater(find.byType(Wrap), matchesGoldenFile('test.icons.sample2.png')); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/39998 testWidgets('Another sample of icons look as expected', (WidgetTester tester) async { await _loadIconFont(); await tester.pumpWidget(const MaterialApp( home: IconTheme( data: IconThemeData(size: 200), child: Wrap( children: <Icon>[ Icon(Icons.electric_bolt), Icon(Icons.electric_bolt_outlined), Icon(Icons.electric_bolt_rounded), Icon(Icons.electric_bolt_sharp), ], ), ), )); await expectLater(find.byType(Wrap), matchesGoldenFile('test.icons.sample3.png')); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/39998 // Regression test for https://github.com/flutter/flutter/issues/103202. testWidgets('Another sample of icons look as expected', (WidgetTester tester) async { await _loadIconFont(); await tester.pumpWidget(const MaterialApp( home: IconTheme( data: IconThemeData(size: 200), child: Wrap( children: <Icon>[ Icon(Icons.repeat_on), Icon(Icons.repeat_on_outlined), Icon(Icons.repeat_on_rounded), Icon(Icons.repeat_on_sharp), ], ), ), )); await expectLater(find.byType(Wrap), matchesGoldenFile('test.icons.sample4.png')); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/39998 } // Loads the cached material icon font. // Only necessary for golden tests. Relies on the tool updating cached assets before // running tests. Future<void> _loadIconFont() async { const FileSystem fs = LocalFileSystem(); const Platform platform = LocalPlatform(); final Directory flutterRoot = fs.directory(platform.environment['FLUTTER_ROOT']); final File iconFont = flutterRoot.childFile( fs.path.join( 'bin', 'cache', 'artifacts', 'material_fonts', 'MaterialIcons-Regular.otf', ), ); final Future<ByteData> bytes = Future<ByteData>.value( iconFont.readAsBytesSync().buffer.asByteData(), ); await (FontLoader('MaterialIcons')..addFont(bytes)).load(); }
flutter/packages/flutter/test/material/icons_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/icons_test.dart", "repo_id": "flutter", "token_count": 2336 }
662
// 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_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { test('MaterialStatesController constructor', () { expect(MaterialStatesController().value, <MaterialState>{}); expect(MaterialStatesController(<MaterialState>{}).value, <MaterialState>{}); expect(MaterialStatesController(<MaterialState>{MaterialState.selected}).value, <MaterialState>{MaterialState.selected}); }); test('MaterialStatesController dispatches memory events', () async { await expectLater( await memoryEvents(() => MaterialStatesController().dispose(), MaterialStatesController), areCreateAndDispose, ); }); test('MaterialStatesController update, listener', () { int count = 0; void valueChanged() { count += 1; } final MaterialStatesController controller = MaterialStatesController(); controller.addListener(valueChanged); controller.update(MaterialState.selected, true); expect(controller.value, <MaterialState>{MaterialState.selected}); expect(count, 1); controller.update(MaterialState.selected, true); expect(controller.value, <MaterialState>{MaterialState.selected}); expect(count, 1); controller.update(MaterialState.hovered, false); expect(count, 1); expect(controller.value, <MaterialState>{MaterialState.selected}); controller.update(MaterialState.selected, false); expect(count, 2); expect(controller.value, <MaterialState>{}); controller.update(MaterialState.hovered, true); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 3); controller.update(MaterialState.hovered, true); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 3); controller.update(MaterialState.pressed, true); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed}); expect(count, 4); controller.update(MaterialState.selected, true); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed, MaterialState.selected}); expect(count, 5); controller.update(MaterialState.selected, false); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed}); expect(count, 6); controller.update(MaterialState.selected, false); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed}); expect(count, 6); controller.update(MaterialState.pressed, false); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 7); controller.update(MaterialState.hovered, false); expect(controller.value, <MaterialState>{}); expect(count, 8); controller.removeListener(valueChanged); controller.update(MaterialState.selected, true); expect(controller.value, <MaterialState>{MaterialState.selected}); expect(count, 8); }); test('MaterialStatesController const initial value', () { int count = 0; void valueChanged() { count += 1; } final MaterialStatesController controller = MaterialStatesController(const <MaterialState>{MaterialState.selected}); controller.addListener(valueChanged); controller.update(MaterialState.selected, true); expect(controller.value, <MaterialState>{MaterialState.selected}); expect(count, 0); controller.update(MaterialState.selected, false); expect(controller.value, <MaterialState>{}); expect(count, 1); }); }
flutter/packages/flutter/test/material/material_states_controller_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/material_states_controller_test.dart", "repo_id": "flutter", "token_count": 1140 }
663
// 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_test/flutter_test.dart'; const Color kSelectedColor = Color(0xFF00FF00); const Color kUnselectedColor = Colors.transparent; Widget buildFrame(TabController tabController, { Color? color, Color? selectedColor, double indicatorSize = 12.0, BorderStyle? borderStyle }) { return Localizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: Theme( data: ThemeData(colorScheme: const ColorScheme.light().copyWith(secondary: kSelectedColor)), child: SizedBox.expand( child: Center( child: SizedBox( width: 400.0, height: 400.0, child: Column( children: <Widget>[ TabPageSelector( controller: tabController, color: color, selectedColor: selectedColor, indicatorSize: indicatorSize, borderStyle: borderStyle, ), Flexible( child: TabBarView( controller: tabController, children: const <Widget>[ Center(child: Text('0')), Center(child: Text('1')), Center(child: Text('2')), ], ), ), ], ), ), ), ), ), ), ); } List<Color> indicatorColors(WidgetTester tester) { final Iterable<TabPageSelectorIndicator> indicators = tester.widgetList( find.descendant( of: find.byType(TabPageSelector), matching: find.byType(TabPageSelectorIndicator), ), ); return indicators.map<Color>((TabPageSelectorIndicator indicator) => indicator.backgroundColor).toList(); } void main() { testWidgets('PageSelector responds correctly to setting the TabController index', (WidgetTester tester) async { final TabController tabController = TabController( vsync: const TestVSync(), length: 3, ); addTearDown(tabController.dispose); await tester.pumpWidget(buildFrame(tabController)); expect(tabController.index, 0); expect(indicatorColors(tester), const <Color>[kSelectedColor, kUnselectedColor, kUnselectedColor]); tabController.index = 1; await tester.pump(); expect(tabController.index, 1); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kSelectedColor, kUnselectedColor]); tabController.index = 2; await tester.pump(); expect(tabController.index, 2); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kUnselectedColor, kSelectedColor]); }); testWidgets('PageSelector responds correctly to TabController.animateTo()', (WidgetTester tester) async { final TabController tabController = TabController( vsync: const TestVSync(), length: 3, ); addTearDown(tabController.dispose); await tester.pumpWidget(buildFrame(tabController)); expect(tabController.index, 0); expect(indicatorColors(tester), const <Color>[kSelectedColor, kUnselectedColor, kUnselectedColor]); tabController.animateTo(1, duration: const Duration(milliseconds: 200)); await tester.pump(); // Verify that indicator 0's color is becoming increasingly transparent, // and indicator 1's color is becoming increasingly opaque during the // 200ms animation. Indicator 2 remains transparent throughout. await tester.pump(const Duration(milliseconds: 10)); List<Color> colors = indicatorColors(tester); expect(colors[0].alpha, greaterThan(colors[1].alpha)); expect(colors[2], kUnselectedColor); await tester.pump(const Duration(milliseconds: 175)); colors = indicatorColors(tester); expect(colors[0].alpha, lessThan(colors[1].alpha)); expect(colors[2], kUnselectedColor); await tester.pumpAndSettle(); expect(tabController.index, 1); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kSelectedColor, kUnselectedColor]); tabController.animateTo(2, duration: const Duration(milliseconds: 200)); await tester.pump(); // Same animation test as above for indicators 1 and 2. await tester.pump(const Duration(milliseconds: 10)); colors = indicatorColors(tester); expect(colors[1].alpha, greaterThan(colors[2].alpha)); expect(colors[0], kUnselectedColor); await tester.pump(const Duration(milliseconds: 175)); colors = indicatorColors(tester); expect(colors[1].alpha, lessThan(colors[2].alpha)); expect(colors[0], kUnselectedColor); await tester.pumpAndSettle(); expect(tabController.index, 2); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kUnselectedColor, kSelectedColor]); }); testWidgets('PageSelector responds correctly to TabBarView drags', (WidgetTester tester) async { final TabController tabController = TabController( vsync: const TestVSync(), initialIndex: 1, length: 3, ); addTearDown(tabController.dispose); await tester.pumpWidget(buildFrame(tabController)); expect(tabController.index, 1); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kSelectedColor, kUnselectedColor]); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); // Drag to the left moving the selection towards indicator 2. Indicator 2's // opacity should increase and Indicator 1's opacity should decrease. await gesture.moveBy(const Offset(-100.0, 0.0)); await tester.pumpAndSettle(); List<Color> colors = indicatorColors(tester); expect(colors[1].alpha, greaterThan(colors[2].alpha)); expect(colors[0], kUnselectedColor); // Drag back to where we started. await gesture.moveBy(const Offset(100.0, 0.0)); await tester.pumpAndSettle(); colors = indicatorColors(tester); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kSelectedColor, kUnselectedColor]); // Drag to the left moving the selection towards indicator 0. Indicator 0's // opacity should increase and Indicator 1's opacity should decrease. await gesture.moveBy(const Offset(100.0, 0.0)); await tester.pumpAndSettle(); colors = indicatorColors(tester); expect(colors[1].alpha, greaterThan(colors[0].alpha)); expect(colors[2], kUnselectedColor); // Drag back to where we started. await gesture.moveBy(const Offset(-100.0, 0.0)); await tester.pumpAndSettle(); colors = indicatorColors(tester); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kSelectedColor, kUnselectedColor]); // Completing the gesture doesn't change anything await gesture.up(); await tester.pumpAndSettle(); colors = indicatorColors(tester); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kSelectedColor, kUnselectedColor]); // Fling to the left, selects indicator 2 await tester.fling(find.byType(TabBarView), const Offset(-100.0, 0.0), 1000.0); await tester.pumpAndSettle(); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kUnselectedColor, kSelectedColor]); // Fling to the right, selects indicator 1 await tester.fling(find.byType(TabBarView), const Offset(100.0, 0.0), 1000.0); await tester.pumpAndSettle(); expect(indicatorColors(tester), const <Color>[kUnselectedColor, kSelectedColor, kUnselectedColor]); }); testWidgets('PageSelector indicatorColors', (WidgetTester tester) async { const Color kRed = Color(0xFFFF0000); const Color kBlue = Color(0xFF0000FF); final TabController tabController = TabController( vsync: const TestVSync(), initialIndex: 1, length: 3, ); addTearDown(tabController.dispose); await tester.pumpWidget(buildFrame(tabController, color: kRed, selectedColor: kBlue)); expect(tabController.index, 1); expect(indicatorColors(tester), const <Color>[kRed, kBlue, kRed]); tabController.index = 0; await tester.pumpAndSettle(); expect(indicatorColors(tester), const <Color>[kBlue, kRed, kRed]); }); testWidgets('PageSelector indicatorSize', (WidgetTester tester) async { final TabController tabController = TabController( vsync: const TestVSync(), initialIndex: 1, length: 3, ); addTearDown(tabController.dispose); await tester.pumpWidget(buildFrame(tabController, indicatorSize: 16.0)); final Iterable<Element> indicatorElements = find.descendant( of: find.byType(TabPageSelector), matching: find.byType(TabPageSelectorIndicator), ).evaluate(); // Indicators get an 8 pixel margin, 16 + 8 = 24. for (final Element indicatorElement in indicatorElements) { expect(indicatorElement.size, const Size(24.0, 24.0)); } expect(tester.getSize(find.byType(TabPageSelector)).height, 24.0); }); testWidgets('PageSelector circle border', (WidgetTester tester) async { final TabController tabController = TabController( vsync: const TestVSync(), initialIndex: 1, length: 3, ); addTearDown(tabController.dispose); Iterable<TabPageSelectorIndicator> indicators; // Default border await tester.pumpWidget(buildFrame(tabController)); indicators = tester.widgetList( find.descendant( of: find.byType(TabPageSelector), matching: find.byType(TabPageSelectorIndicator), ), ); for (final TabPageSelectorIndicator indicator in indicators) { expect(indicator.borderStyle, BorderStyle.solid); } // No border await tester.pumpWidget(buildFrame(tabController, borderStyle: BorderStyle.none)); indicators = tester.widgetList( find.descendant( of: find.byType(TabPageSelector), matching: find.byType(TabPageSelectorIndicator), ), ); for (final TabPageSelectorIndicator indicator in indicators) { expect(indicator.borderStyle, BorderStyle.none); } // Solid border await tester.pumpWidget(buildFrame(tabController, borderStyle: BorderStyle.solid)); indicators = tester.widgetList( find.descendant( of: find.byType(TabPageSelector), matching: find.byType(TabPageSelectorIndicator), ), ); for (final TabPageSelectorIndicator indicator in indicators) { expect(indicator.borderStyle, BorderStyle.solid); } }); }
flutter/packages/flutter/test/material/page_selector_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/page_selector_test.dart", "repo_id": "flutter", "token_count": 4040 }
664
// 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 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../widgets/semantics_tester.dart'; // From bottom_sheet.dart. const Duration _bottomSheetExitDuration = Duration(milliseconds: 200); void main() { // Regression test for https://github.com/flutter/flutter/issues/103741 testWidgets('extendBodyBehindAppBar change should not cause the body widget lose state', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); Widget buildFrame({required bool extendBodyBehindAppBar}) { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Scaffold( extendBodyBehindAppBar: extendBodyBehindAppBar, resizeToAvoidBottomInset: false, body: SingleChildScrollView( controller: controller, child: const FlutterLogo( size: 1107, ), ), ), ), ); } await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: true)); expect(controller.position.pixels, 0.0); controller.jumpTo(100.0); await tester.pump(); expect(controller.position.pixels, 100.0); await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: false)); expect(controller.position.pixels, 100.0); }); testWidgets('Scaffold drawer callback test', (WidgetTester tester) async { bool isDrawerOpen = false; bool isEndDrawerOpen = false; await tester.pumpWidget(MaterialApp( home: Scaffold( drawer: Container( color: Colors.blue, ), onDrawerChanged: (bool isOpen) { isDrawerOpen = isOpen; }, endDrawer: Container( color: Colors.green, ), onEndDrawerChanged: (bool isOpen) { isEndDrawerOpen = isOpen; }, body: Container(), ), )); final ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); scaffoldState.openDrawer(); await tester.pumpAndSettle(); expect(isDrawerOpen, true); scaffoldState.openEndDrawer(); await tester.pumpAndSettle(); expect(isDrawerOpen, false); scaffoldState.openEndDrawer(); await tester.pumpAndSettle(); expect(isEndDrawerOpen, true); scaffoldState.openDrawer(); await tester.pumpAndSettle(); expect(isEndDrawerOpen, false); }); testWidgets('Scaffold drawer callback test - only call when changed', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/87914 bool onDrawerChangedCalled = false; bool onEndDrawerChangedCalled = false; await tester.pumpWidget(MaterialApp( home: Scaffold( drawer: Container( color: Colors.blue, ), onDrawerChanged: (bool isOpen) { onDrawerChangedCalled = true; }, endDrawer: Container( color: Colors.green, ), onEndDrawerChanged: (bool isOpen) { onEndDrawerChangedCalled = true; }, body: Container(), ), )); await tester.flingFrom(Offset.zero, const Offset(10.0, 0.0), 10.0); expect(onDrawerChangedCalled, false); await tester.pumpAndSettle(); final double width = tester.getSize(find.byType(MaterialApp)).width; await tester.flingFrom(Offset(width - 1, 0.0), const Offset(-10.0, 0.0), 10.0); await tester.pumpAndSettle(); expect(onEndDrawerChangedCalled, false); }); testWidgets('Scaffold control test', (WidgetTester tester) async { final Key bodyKey = UniqueKey(); Widget boilerplate(Widget child) { return Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: child, ), ); } await tester.pumpWidget(MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Title')), body: Container(key: bodyKey), ), )); RenderBox bodyBox = tester.renderObject(find.byKey(bodyKey)); expect(bodyBox.size, equals(const Size(800.0, 544.0))); await tester.pumpWidget(boilerplate(MediaQuery( data: const MediaQueryData(viewInsets: EdgeInsets.only(bottom: 100.0)), child: Scaffold( appBar: AppBar(title: const Text('Title')), body: Container(key: bodyKey), ), ), )); bodyBox = tester.renderObject(find.byKey(bodyKey)); expect(bodyBox.size, equals(const Size(800.0, 444.0))); await tester.pumpWidget(boilerplate(MediaQuery( data: const MediaQueryData(viewInsets: EdgeInsets.only(bottom: 100.0)), child: Scaffold( appBar: AppBar(title: const Text('Title')), body: Container(key: bodyKey), resizeToAvoidBottomInset: false, ), ))); bodyBox = tester.renderObject(find.byKey(bodyKey)); expect(bodyBox.size, equals(const Size(800.0, 544.0))); }); testWidgets('Scaffold large bottom padding test', (WidgetTester tester) async { final Key bodyKey = UniqueKey(); Widget boilerplate(Widget child) { return Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: child, ), ); } await tester.pumpWidget(boilerplate(MediaQuery( data: const MediaQueryData( viewInsets: EdgeInsets.only(bottom: 700.0), ), child: Scaffold( body: Container(key: bodyKey), ), ))); final RenderBox bodyBox = tester.renderObject(find.byKey(bodyKey)); expect(bodyBox.size, equals(const Size(800.0, 0.0))); await tester.pumpWidget(boilerplate(MediaQuery( data: const MediaQueryData( viewInsets: EdgeInsets.only(bottom: 500.0), ), child: Scaffold( body: Container(key: bodyKey), ), ), )); expect(bodyBox.size, equals(const Size(800.0, 100.0))); await tester.pumpWidget(boilerplate(MediaQuery( data: const MediaQueryData( viewInsets: EdgeInsets.only(bottom: 580.0), ), child: Scaffold( appBar: AppBar( title: const Text('Title'), ), body: Container(key: bodyKey), ), ), )); expect(bodyBox.size, equals(const Size(800.0, 0.0))); }); testWidgets('Floating action entrance/exit animation', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: Scaffold( floatingActionButton: FloatingActionButton( key: Key('one'), onPressed: null, child: Text('1'), ), ))); expect(tester.binding.transientCallbackCount, 0); await tester.pumpWidget(const MaterialApp(home: Scaffold( floatingActionButton: FloatingActionButton( key: Key('two'), onPressed: null, child: Text('2'), ), ))); expect(tester.binding.transientCallbackCount, greaterThan(0)); await tester.pumpWidget(Container()); expect(tester.binding.transientCallbackCount, 0); await tester.pumpWidget(const MaterialApp(home: Scaffold())); expect(tester.binding.transientCallbackCount, 0); await tester.pumpWidget(const MaterialApp(home: Scaffold( floatingActionButton: FloatingActionButton( key: Key('one'), onPressed: null, child: Text('1'), ), ))); expect(tester.binding.transientCallbackCount, greaterThan(0)); }); testWidgets('Floating action button shrinks when bottom sheet becomes dominant', (WidgetTester tester) async { final DraggableScrollableController draggableController = DraggableScrollableController(); addTearDown(draggableController.dispose); const double kBottomSheetDominatesPercentage = 0.3; await tester.pumpWidget(MaterialApp(home: Scaffold( floatingActionButton: const FloatingActionButton( key: Key('one'), onPressed: null, child: Text('1'), ), bottomSheet: DraggableScrollableSheet( expand: false, controller: draggableController, builder: (BuildContext context, ScrollController scrollController) { return SingleChildScrollView( controller: scrollController, child: const SizedBox(), ); }, ), ))); double getScale() => tester.firstWidget<ScaleTransition>(find.byType(ScaleTransition)).scale.value; for (double i = 0, extent = i / 10; i <= 10; i++, extent = i / 10) { draggableController.jumpTo(extent); final double extentRemaining = 1.0 - extent; if (extentRemaining < kBottomSheetDominatesPercentage) { final double visValue = extentRemaining * kBottomSheetDominatesPercentage * 10; // since FAB uses easeIn curve, we're testing this by using the fact that // easeIn curve is always less than or equal to x=y curve. expect(getScale(), lessThanOrEqualTo(visValue)); } else { expect(getScale(), equals(1.0)); } } }); testWidgets('Scaffold shows scrim when bottom sheet becomes dominant', (WidgetTester tester) async { final DraggableScrollableController draggableController = DraggableScrollableController(); addTearDown(draggableController.dispose); const double kBottomSheetDominatesPercentage = 0.3; const double kMinBottomSheetScrimOpacity = 0.1; const double kMaxBottomSheetScrimOpacity = 0.6; await tester.pumpWidget(MaterialApp(home: Scaffold( bottomSheet: DraggableScrollableSheet( expand: false, controller: draggableController, builder: (BuildContext context, ScrollController scrollController) { return SingleChildScrollView( controller: scrollController, child: const SizedBox(), ); }, ), ))); Finder findModalBarrier() => find.descendant(of: find.byType(Scaffold), matching: find.byType(ModalBarrier)); double getOpacity() => tester.firstWidget<ModalBarrier>(findModalBarrier()).color!.opacity; double getExpectedOpacity(double visValue) => math.max(kMinBottomSheetScrimOpacity, kMaxBottomSheetScrimOpacity - visValue); for (double i = 0, extent = i / 10; i <= 10; i++, extent = i / 10) { draggableController.jumpTo(extent); await tester.pump(); final double extentRemaining = 1.0 - extent; if (extentRemaining < kBottomSheetDominatesPercentage) { final double visValue = extentRemaining * kBottomSheetDominatesPercentage * 10; expect(findModalBarrier(), findsOneWidget); expect(getOpacity(), moreOrLessEquals(getExpectedOpacity(visValue), epsilon: 0.02)); } else { expect(findModalBarrier(), findsNothing); } } }); testWidgets('Floating action button directionality', (WidgetTester tester) async { Widget build(TextDirection textDirection) { return Directionality( textDirection: textDirection, child: const MediaQuery( data: MediaQueryData( viewInsets: EdgeInsets.only(bottom: 200.0), ), child: Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, child: Text('1'), ), ), ), ); } await tester.pumpWidget(build(TextDirection.ltr)); expect(tester.getCenter(find.byType(FloatingActionButton)), const Offset(756.0, 356.0)); await tester.pumpWidget(build(TextDirection.rtl)); expect(tester.binding.transientCallbackCount, 0); expect(tester.getCenter(find.byType(FloatingActionButton)), const Offset(44.0, 356.0)); }); testWidgets('Floating Action Button bottom padding not consumed by viewInsets', (WidgetTester tester) async { final Widget child = Directionality( textDirection: TextDirection.ltr, child: Scaffold( resizeToAvoidBottomInset: false, body: Container(), floatingActionButton: const Placeholder(), ), ); await tester.pumpWidget( MediaQuery( data: const MediaQueryData( viewPadding: EdgeInsets.only(bottom: 20.0), ), child: child, ), ); final Offset initialPoint = tester.getCenter(find.byType(Placeholder)); expect( tester.getBottomLeft(find.byType(Placeholder)).dy, moreOrLessEquals(600.0 - 20.0 - kFloatingActionButtonMargin) ); // Consume bottom padding - as if by the keyboard opening await tester.pumpWidget( MediaQuery( data: const MediaQueryData( viewPadding: EdgeInsets.only(bottom: 20), viewInsets: EdgeInsets.only(bottom: 300), ), child: child, ), ); final Offset finalPoint = tester.getCenter(find.byType(Placeholder)); expect(initialPoint, finalPoint); }); testWidgets('viewPadding change should trigger _ScaffoldLayout re-layout', (WidgetTester tester) async { Widget buildFrame(EdgeInsets viewPadding) { return MediaQuery( data: MediaQueryData( viewPadding: viewPadding, ), child: Directionality( textDirection: TextDirection.ltr, child: Scaffold( resizeToAvoidBottomInset: false, body: Container(), floatingActionButton: const Placeholder(), ), ), ); } await tester.pumpWidget(buildFrame(const EdgeInsets.only(bottom: 300))); final RenderBox renderBox = tester.renderObject<RenderBox>(find.byType(CustomMultiChildLayout)); expect(renderBox.debugNeedsLayout, false); await tester.pumpWidget( buildFrame(const EdgeInsets.only(bottom: 400)), phase: EnginePhase.build, ); expect(renderBox.debugNeedsLayout, true); }); testWidgets('Drawer scrolling', (WidgetTester tester) async { final Key drawerKey = UniqueKey(); const double appBarHeight = 256.0; final ScrollController scrollOffset = ScrollController(); addTearDown(scrollOffset.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( drawer: Drawer( key: drawerKey, child: ListView( dragStartBehavior: DragStartBehavior.down, controller: scrollOffset, children: List<Widget>.generate(10, (int index) => SizedBox(height: 100.0, child: Text('D$index')), ), ), ), body: CustomScrollView( slivers: <Widget>[ const SliverAppBar( pinned: true, expandedHeight: appBarHeight, title: Text('Title'), flexibleSpace: FlexibleSpaceBar(title: Text('Title')), ), SliverPadding( padding: const EdgeInsets.only(top: appBarHeight), sliver: SliverList( delegate: SliverChildListDelegate(List<Widget>.generate( 10, (int index) => SizedBox(height: 100.0, child: Text('B$index')), )), ), ), ], ), ), ), ); final ScaffoldState state = tester.firstState(find.byType(Scaffold)); state.openDrawer(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(scrollOffset.offset, 0.0); const double scrollDelta = 80.0; await tester.drag(find.byKey(drawerKey), const Offset(0.0, -scrollDelta)); await tester.pump(); expect(scrollOffset.offset, scrollDelta); final RenderBox renderBox = tester.renderObject(find.byType(AppBar)); expect(renderBox.size.height, equals(appBarHeight)); }); Widget buildStatusBarTestApp(TargetPlatform? platform) { return MaterialApp( theme: ThemeData(platform: platform), home: MediaQuery( data: const MediaQueryData(padding: EdgeInsets.only(top: 25.0)), // status bar child: Scaffold( body: CustomScrollView( primary: true, slivers: <Widget>[ const SliverAppBar( title: Text('Title'), ), SliverList( delegate: SliverChildListDelegate(List<Widget>.generate( 20, (int index) => SizedBox(height: 100.0, child: Text('$index')), )), ), ], ), ), ), ); } testWidgets('Tapping the status bar scrolls to top', (WidgetTester tester) async { await tester.pumpWidget(buildStatusBarTestApp(debugDefaultTargetPlatformOverride)); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); scrollable.position.jumpTo(500.0); expect(scrollable.position.pixels, equals(500.0)); await tester.tapAt(const Offset(100.0, 10.0)); await tester.pumpAndSettle(); expect(scrollable.position.pixels, equals(0.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Tapping the status bar scrolls to top with ease out curve animation', (WidgetTester tester) async { const int duration = 1000; final List<double> stops = <double>[0.842, 0.959, 0.993, 1.0]; const double scrollOffset = 1000; await tester.pumpWidget(buildStatusBarTestApp(debugDefaultTargetPlatformOverride)); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); scrollable.position.jumpTo(scrollOffset); await tester.tapAt(const Offset(100.0, 10.0)); await tester.pump(Duration.zero); expect(scrollable.position.pixels, equals(scrollOffset)); for (int i = 0; i < stops.length; i++) { await tester.pump( Duration(milliseconds: duration ~/ stops.length)); // Scroll pixel position is very long double, compare with floored int // pixel position expect( scrollable.position.pixels.toInt(), equals( (scrollOffset * (1 - stops[i])).toInt() ) ); } // Finally stops at the top. expect(scrollable.position.pixels, equals(0.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Tapping the status bar does not scroll to top', (WidgetTester tester) async { await tester.pumpWidget(buildStatusBarTestApp(TargetPlatform.android)); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); scrollable.position.jumpTo(500.0); expect(scrollable.position.pixels, equals(500.0)); await tester.tapAt(const Offset(100.0, 10.0)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(scrollable.position.pixels, equals(500.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android })); testWidgets('Bottom sheet cannot overlap app bar', (WidgetTester tester) async { final Key sheetKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: Scaffold( appBar: AppBar( title: const Text('Title'), ), body: Builder( builder: (BuildContext context) { return GestureDetector( onTap: () { Scaffold.of(context).showBottomSheet((BuildContext context) { return Container( key: sheetKey, color: Colors.blue[500], ); }); }, child: const Text('X'), ); }, ), ), ), ); await tester.tap(find.text('X')); await tester.pump(); // start animation await tester.pump(const Duration(seconds: 1)); final RenderBox appBarBox = tester.renderObject(find.byType(AppBar)); final RenderBox sheetBox = tester.renderObject(find.byKey(sheetKey)); final Offset appBarBottomRight = appBarBox.localToGlobal(appBarBox.size.bottomRight(Offset.zero)); final Offset sheetTopRight = sheetBox.localToGlobal(sheetBox.size.topRight(Offset.zero)); expect(appBarBottomRight, equals(sheetTopRight)); }); testWidgets('BottomSheet bottom padding is not consumed by viewInsets', (WidgetTester tester) async { final Widget child = Directionality( textDirection: TextDirection.ltr, child: Scaffold( resizeToAvoidBottomInset: false, body: Container(), bottomSheet: const Placeholder(), ), ); await tester.pumpWidget( MediaQuery( data: const MediaQueryData( padding: EdgeInsets.only(bottom: 20.0), ), child: child, ), ); final Offset initialPoint = tester.getCenter(find.byType(Placeholder)); // Consume bottom padding - as if by the keyboard opening await tester.pumpWidget( MediaQuery( data: const MediaQueryData( viewPadding: EdgeInsets.only(bottom: 20), viewInsets: EdgeInsets.only(bottom: 300), ), child: child, ), ); final Offset finalPoint = tester.getCenter(find.byType(Placeholder)); expect(initialPoint, finalPoint); }); testWidgets('Persistent bottom buttons are persistent', (WidgetTester tester) async { bool didPressButton = false; await tester.pumpWidget( MaterialApp( home: Scaffold( body: SingleChildScrollView( child: Container( color: Colors.amber[500], height: 5000.0, child: const Text('body'), ), ), persistentFooterButtons: <Widget>[ TextButton( onPressed: () { didPressButton = true; }, child: const Text('X'), ), ], ), ), ); await tester.drag(find.byType(SingleChildScrollView), const Offset(0.0, -1000.0)); expect(didPressButton, isFalse); await tester.tap(find.text('X')); expect(didPressButton, isTrue); }); testWidgets('Persistent bottom buttons alignment', (WidgetTester tester) async { Widget buildApp(AlignmentDirectional persistentAlignment) { return MaterialApp( home: Scaffold( body: SingleChildScrollView( child: Container( color: Colors.amber[500], height: 5000.0, child: const Text('body'), ), ), persistentFooterAlignment: persistentAlignment, persistentFooterButtons: <Widget>[ TextButton( onPressed: () { }, child: const Text('X'), ), ], ), ); } await tester.pumpWidget(buildApp(AlignmentDirectional.centerEnd)); Finder footerButton = find.byType(TextButton); expect(tester.getTopRight(footerButton).dx, 800.0 - 8.0); await tester.pumpWidget(buildApp(AlignmentDirectional.center)); footerButton = find.byType(TextButton); expect(tester.getCenter(footerButton).dx, 800.0 / 2); await tester.pumpWidget(buildApp(AlignmentDirectional.centerStart)); footerButton = find.byType(TextButton); expect(tester.getTopLeft(footerButton).dx, 8.0); }); testWidgets('Persistent bottom buttons apply media padding', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.fromLTRB(10.0, 20.0, 30.0, 40.0), ), child: Scaffold( body: SingleChildScrollView( child: Container( color: Colors.amber[500], height: 5000.0, child: const Text('body'), ), ), persistentFooterButtons: const <Widget>[Placeholder()], ), ), ), ); final Finder buttonsBar = find.ancestor(of: find.byType(OverflowBar), matching: find.byType(Padding)).first; expect(tester.getBottomLeft(buttonsBar), const Offset(10.0, 560.0)); expect(tester.getBottomRight(buttonsBar), const Offset(770.0, 560.0)); }); testWidgets('persistentFooterButtons with bottomNavigationBar apply SafeArea properly', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/92039 await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: MediaQuery( data: const MediaQueryData( // Representing a navigational notch at the bottom of the screen viewPadding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 40.0), ), child: Scaffold( body: SingleChildScrollView( child: Container( color: Colors.amber[500], height: 5000.0, child: const Text('body'), ), ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.business), label: 'Business', ), BottomNavigationBarItem( icon: Icon(Icons.school), label: 'School', ), ], ), persistentFooterButtons: const <Widget>[Placeholder()], ), ), ), ); final Finder buttonsBar = find.ancestor(of: find.byType(OverflowBar), matching: find.byType(Padding)).first; // The SafeArea of the persistentFooterButtons should not pad below them // since they are stacked on top of the bottomNavigationBar. The // bottomNavigationBar will handle the padding instead. // 488 represents the height of the persistentFooterButtons, with the bottom // of the screen being 600. If the 40 pixels of bottom padding were being // errantly applied, the buttons would be higher (448). expect(tester.getTopLeft(buttonsBar), const Offset(0.0, 488.0)); }); testWidgets('Persistent bottom buttons bottom padding is not consumed by viewInsets', (WidgetTester tester) async { final Widget child = Directionality( textDirection: TextDirection.ltr, child: Scaffold( resizeToAvoidBottomInset: false, body: Container(), persistentFooterButtons: const <Widget>[Placeholder()], ), ); await tester.pumpWidget( MediaQuery( data: const MediaQueryData( padding: EdgeInsets.only(bottom: 20.0), ), child: child, ), ); final Offset initialPoint = tester.getCenter(find.byType(Placeholder)); // Consume bottom padding - as if by the keyboard opening await tester.pumpWidget( MediaQuery( data: const MediaQueryData( viewPadding: EdgeInsets.only(bottom: 20), viewInsets: EdgeInsets.only(bottom: 300), ), child: child, ), ); final Offset finalPoint = tester.getCenter(find.byType(Placeholder)); expect(initialPoint, finalPoint); }); group('back arrow', () { Future<void> expectBackIcon(WidgetTester tester, IconData expectedIcon) async { final GlobalKey rootKey = GlobalKey(); final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (_) => Container(key: rootKey, child: const Text('Home')), '/scaffold': (_) => Scaffold( appBar: AppBar(), body: const Text('Scaffold'), ), }; await tester.pumpWidget(MaterialApp(routes: routes)); Navigator.pushNamed(rootKey.currentContext!, '/scaffold'); await tester.pump(); await tester.pump(const Duration(seconds: 1)); final Icon icon = tester.widget(find.byType(Icon)); expect(icon.icon, expectedIcon); } testWidgets('Back arrow uses correct default', (WidgetTester tester) async { await expectBackIcon(tester, Icons.arrow_back); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia })); testWidgets('Back arrow uses correct default', (WidgetTester tester) async { await expectBackIcon(tester, kIsWeb ? Icons.arrow_back : Icons.arrow_back_ios_new_rounded); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); }); group('close button', () { Future<void> expectCloseIcon(WidgetTester tester, PageRoute<void> Function() routeBuilder, String type) async { const IconData expectedIcon = Icons.close; await tester.pumpWidget( MaterialApp( home: Scaffold(appBar: AppBar(), body: const Text('Page 1')), ), ); tester.state<NavigatorState>(find.byType(Navigator)).push(routeBuilder()); await tester.pump(); await tester.pump(const Duration(seconds: 1)); final Icon icon = tester.widget(find.byType(Icon)); expect(icon.icon, expectedIcon, reason: "didn't find close icon for $type"); expect(find.byType(CloseButton), findsOneWidget, reason: "didn't find close button for $type"); } PageRoute<void> materialRouteBuilder() { return MaterialPageRoute<void>( builder: (BuildContext context) { return Scaffold(appBar: AppBar(), body: const Text('Page 2')); }, fullscreenDialog: true, ); } PageRoute<void> pageRouteBuilder() { return PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return Scaffold(appBar: AppBar(), body: const Text('Page 2')); }, fullscreenDialog: true, ); } PageRoute<void> customPageRouteBuilder() { return _CustomPageRoute<void>( builder: (BuildContext context) { return Scaffold(appBar: AppBar(), body: const Text('Page 2')); }, fullscreenDialog: true, ); } testWidgets('Close button shows correctly', (WidgetTester tester) async { await expectCloseIcon(tester, materialRouteBuilder, 'materialRouteBuilder'); }, variant: TargetPlatformVariant.all()); testWidgets('Close button shows correctly with PageRouteBuilder', (WidgetTester tester) async { await expectCloseIcon(tester, pageRouteBuilder, 'pageRouteBuilder'); }, variant: TargetPlatformVariant.all()); testWidgets('Close button shows correctly with custom page route', (WidgetTester tester) async { await expectCloseIcon(tester, customPageRouteBuilder, 'customPageRouteBuilder'); }, variant: TargetPlatformVariant.all()); }); group('body size', () { testWidgets('body size with container', (WidgetTester tester) async { final Key testKey = UniqueKey(); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Scaffold( body: Container( key: testKey, ), ), ), )); expect(tester.element(find.byKey(testKey)).size, const Size(800.0, 600.0)); expect(tester.renderObject<RenderBox>(find.byKey(testKey)).localToGlobal(Offset.zero), Offset.zero); }); testWidgets('body size with sized container', (WidgetTester tester) async { final Key testKey = UniqueKey(); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Scaffold( body: Container( key: testKey, height: 100.0, ), ), ), )); expect(tester.element(find.byKey(testKey)).size, const Size(800.0, 100.0)); expect(tester.renderObject<RenderBox>(find.byKey(testKey)).localToGlobal(Offset.zero), Offset.zero); }); testWidgets('body size with centered container', (WidgetTester tester) async { final Key testKey = UniqueKey(); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Scaffold( body: Center( child: Container( key: testKey, ), ), ), ), )); expect(tester.element(find.byKey(testKey)).size, const Size(800.0, 600.0)); expect(tester.renderObject<RenderBox>(find.byKey(testKey)).localToGlobal(Offset.zero), Offset.zero); }); testWidgets('body size with button', (WidgetTester tester) async { final Key testKey = UniqueKey(); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Scaffold( body: TextButton( key: testKey, onPressed: () { }, child: const Text(''), ), ), ), )); expect(tester.element(find.byKey(testKey)).size, const Size(64.0, 48.0)); expect(tester.renderObject<RenderBox>(find.byKey(testKey)).localToGlobal(Offset.zero), Offset.zero); }); testWidgets('body size with extendBody', (WidgetTester tester) async { final Key bodyKey = UniqueKey(); late double mediaQueryBottom; Widget buildFrame({ required bool extendBody, bool? resizeToAvoidBottomInset, double viewInsetBottom = 0.0 }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: MediaQuery( data: MediaQueryData( viewInsets: EdgeInsets.only(bottom: viewInsetBottom), ), child: Scaffold( resizeToAvoidBottomInset: resizeToAvoidBottomInset, extendBody: extendBody, body: Builder( builder: (BuildContext context) { mediaQueryBottom = MediaQuery.paddingOf(context).bottom; return Container(key: bodyKey); }, ), bottomNavigationBar: const BottomAppBar( child: SizedBox(height: 48.0), ), ), ), ); } await tester.pumpWidget(buildFrame(extendBody: true)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); expect(mediaQueryBottom, 48.0); await tester.pumpWidget(buildFrame(extendBody: false)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 552.0)); // 552 = 600 - 48 (BAB height) expect(mediaQueryBottom, 0.0); // If resizeToAvoidBottomInsets is false, same results as if it was unspecified (null). await tester.pumpWidget(buildFrame(extendBody: true, resizeToAvoidBottomInset: false, viewInsetBottom: 100.0)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); expect(mediaQueryBottom, 48.0); await tester.pumpWidget(buildFrame(extendBody: false, resizeToAvoidBottomInset: false, viewInsetBottom: 100.0)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 552.0)); expect(mediaQueryBottom, 0.0); // If resizeToAvoidBottomInsets is true and viewInsets.bottom is > the bottom // navigation bar's height then the body always resizes and the MediaQuery // isn't adjusted. This case corresponds to the keyboard appearing. await tester.pumpWidget(buildFrame(extendBody: true, resizeToAvoidBottomInset: true, viewInsetBottom: 100.0)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); expect(mediaQueryBottom, 0.0); await tester.pumpWidget(buildFrame(extendBody: false, resizeToAvoidBottomInset: true, viewInsetBottom: 100.0)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); expect(mediaQueryBottom, 0.0); }); testWidgets('body size with extendBodyBehindAppBar', (WidgetTester tester) async { final Key appBarKey = UniqueKey(); final Key bodyKey = UniqueKey(); const double appBarHeight = 100; const double windowPaddingTop = 24; late bool fixedHeightAppBar; late double mediaQueryTop; Widget buildFrame({ required bool extendBodyBehindAppBar, required bool hasAppBar }) { return Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.only(top: windowPaddingTop), ), child: Builder( builder: (BuildContext context) { return Scaffold( extendBodyBehindAppBar: extendBodyBehindAppBar, appBar: !hasAppBar ? null : PreferredSize( key: appBarKey, preferredSize: const Size.fromHeight(appBarHeight), child: Container( constraints: BoxConstraints( minHeight: appBarHeight, maxHeight: fixedHeightAppBar ? appBarHeight : double.infinity, ), ), ), body: Builder( builder: (BuildContext context) { mediaQueryTop = MediaQuery.paddingOf(context).top; return Container(key: bodyKey); }, ), ); }, ), ), ); } fixedHeightAppBar = false; // When an appbar is provided, the Scaffold's body is built within a // MediaQuery with padding.top = 0, and the appBar's maxHeight is // constrained to its preferredSize.height + the original MediaQuery // padding.top. When extendBodyBehindAppBar is true, an additional // inner MediaQuery is added around the Scaffold's body with padding.top // equal to the overall height of the appBar. See _BodyBuilder in // material/scaffold.dart. await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: true, hasAppBar: true)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); expect(tester.getSize(find.byKey(appBarKey)), const Size(800.0, appBarHeight + windowPaddingTop)); expect(mediaQueryTop, appBarHeight + windowPaddingTop); await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: true, hasAppBar: false)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); expect(find.byKey(appBarKey), findsNothing); expect(mediaQueryTop, windowPaddingTop); await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: false, hasAppBar: true)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0 - appBarHeight - windowPaddingTop)); expect(tester.getSize(find.byKey(appBarKey)), const Size(800.0, appBarHeight + windowPaddingTop)); expect(mediaQueryTop, 0.0); await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: false, hasAppBar: false)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); expect(find.byKey(appBarKey), findsNothing); expect(mediaQueryTop, windowPaddingTop); fixedHeightAppBar = true; await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: true, hasAppBar: true)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); expect(tester.getSize(find.byKey(appBarKey)), const Size(800.0, appBarHeight)); expect(mediaQueryTop, appBarHeight); await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: true, hasAppBar: false)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); expect(find.byKey(appBarKey), findsNothing); expect(mediaQueryTop, windowPaddingTop); await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: false, hasAppBar: true)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0 - appBarHeight)); expect(tester.getSize(find.byKey(appBarKey)), const Size(800.0, appBarHeight)); expect(mediaQueryTop, 0.0); await tester.pumpWidget(buildFrame(extendBodyBehindAppBar: false, hasAppBar: false)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); expect(find.byKey(appBarKey), findsNothing); expect(mediaQueryTop, windowPaddingTop); }); }); testWidgets('Open drawer hides underlying semantics tree', (WidgetTester tester) async { const String bodyLabel = 'I am the body'; const String persistentFooterButtonLabel = 'a button on the bottom'; const String bottomNavigationBarLabel = 'a bar in an app'; const String floatingActionButtonLabel = 'I float in space'; const String drawerLabel = 'I am the reason for this test'; final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(const MaterialApp(home: Scaffold( body: Text(bodyLabel), persistentFooterButtons: <Widget>[Text(persistentFooterButtonLabel)], bottomNavigationBar: Text(bottomNavigationBarLabel), floatingActionButton: Text(floatingActionButtonLabel), drawer: Drawer(child: Text(drawerLabel)), ))); expect(semantics, includesNodeWith(label: bodyLabel)); expect(semantics, includesNodeWith(label: persistentFooterButtonLabel)); expect(semantics, includesNodeWith(label: bottomNavigationBarLabel)); expect(semantics, includesNodeWith(label: floatingActionButtonLabel)); expect(semantics, isNot(includesNodeWith(label: drawerLabel))); final ScaffoldState state = tester.firstState(find.byType(Scaffold)); state.openDrawer(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(semantics, isNot(includesNodeWith(label: bodyLabel))); expect(semantics, isNot(includesNodeWith(label: persistentFooterButtonLabel))); expect(semantics, isNot(includesNodeWith(label: bottomNavigationBarLabel))); expect(semantics, isNot(includesNodeWith(label: floatingActionButtonLabel))); expect(semantics, includesNodeWith(label: drawerLabel)); semantics.dispose(); }); testWidgets('Scaffold and extreme window padding', (WidgetTester tester) async { final Key appBar = UniqueKey(); final Key body = UniqueKey(); final Key floatingActionButton = UniqueKey(); final Key persistentFooterButton = UniqueKey(); final Key drawer = UniqueKey(); final Key bottomNavigationBar = UniqueKey(); final Key insideAppBar = UniqueKey(); final Key insideBody = UniqueKey(); final Key insideFloatingActionButton = UniqueKey(); final Key insidePersistentFooterButton = UniqueKey(); final Key insideDrawer = UniqueKey(); final Key insideBottomNavigationBar = UniqueKey(); await tester.pumpWidget( Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.rtl, child: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.only( left: 20.0, top: 30.0, right: 50.0, bottom: 60.0, ), viewInsets: EdgeInsets.only(bottom: 200.0), ), child: Scaffold( drawerDragStartBehavior: DragStartBehavior.down, appBar: PreferredSize( preferredSize: const Size(11.0, 13.0), child: Container( key: appBar, child: SafeArea( child: Placeholder(key: insideAppBar), ), ), ), body: Container( key: body, child: SafeArea( child: Placeholder(key: insideBody), ), ), floatingActionButton: SizedBox( key: floatingActionButton, width: 77.0, height: 77.0, child: SafeArea( child: Placeholder(key: insideFloatingActionButton), ), ), persistentFooterButtons: <Widget>[ SizedBox( key: persistentFooterButton, width: 100.0, height: 90.0, child: SafeArea( child: Placeholder(key: insidePersistentFooterButton), ), ), ], drawer: SizedBox( key: drawer, width: 204.0, child: SafeArea( child: Placeholder(key: insideDrawer), ), ), bottomNavigationBar: SizedBox( key: bottomNavigationBar, height: 85.0, child: SafeArea( child: Placeholder(key: insideBottomNavigationBar), ), ), ), ), ), ), ); // open drawer await tester.flingFrom(const Offset(795.0, 5.0), const Offset(-200.0, 0.0), 10.0); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(tester.getRect(find.byKey(appBar)), const Rect.fromLTRB(0.0, 0.0, 800.0, 43.0)); expect(tester.getRect(find.byKey(body)), const Rect.fromLTRB(0.0, 43.0, 800.0, 400.0)); expect(tester.getRect(find.byKey(floatingActionButton)), rectMoreOrLessEquals(const Rect.fromLTRB(36.0, 307.0, 113.0, 384.0))); expect(tester.getRect(find.byKey(persistentFooterButton)),const Rect.fromLTRB(28.0, 417.0, 128.0, 507.0)); // Includes 8px each top/bottom padding. expect(tester.getRect(find.byKey(drawer)), const Rect.fromLTRB(596.0, 0.0, 800.0, 600.0)); expect(tester.getRect(find.byKey(bottomNavigationBar)), const Rect.fromLTRB(0.0, 515.0, 800.0, 600.0)); expect(tester.getRect(find.byKey(insideAppBar)), const Rect.fromLTRB(20.0, 30.0, 750.0, 43.0)); expect(tester.getRect(find.byKey(insideBody)), const Rect.fromLTRB(20.0, 43.0, 750.0, 400.0)); expect(tester.getRect(find.byKey(insideFloatingActionButton)), rectMoreOrLessEquals(const Rect.fromLTRB(36.0, 307.0, 113.0, 384.0))); expect(tester.getRect(find.byKey(insidePersistentFooterButton)), const Rect.fromLTRB(28.0, 417.0, 128.0, 507.0)); expect(tester.getRect(find.byKey(insideDrawer)), const Rect.fromLTRB(596.0, 30.0, 750.0, 540.0)); expect(tester.getRect(find.byKey(insideBottomNavigationBar)), const Rect.fromLTRB(20.0, 515.0, 750.0, 540.0)); }); testWidgets('Scaffold and extreme window padding - persistent footer buttons only', (WidgetTester tester) async { final Key appBar = UniqueKey(); final Key body = UniqueKey(); final Key floatingActionButton = UniqueKey(); final Key persistentFooterButton = UniqueKey(); final Key drawer = UniqueKey(); final Key insideAppBar = UniqueKey(); final Key insideBody = UniqueKey(); final Key insideFloatingActionButton = UniqueKey(); final Key insidePersistentFooterButton = UniqueKey(); final Key insideDrawer = UniqueKey(); await tester.pumpWidget( Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.rtl, child: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.only( left: 20.0, top: 30.0, right: 50.0, bottom: 60.0, ), viewInsets: EdgeInsets.only(bottom: 200.0), ), child: Scaffold( appBar: PreferredSize( preferredSize: const Size(11.0, 13.0), child: Container( key: appBar, child: SafeArea( child: Placeholder(key: insideAppBar), ), ), ), body: Container( key: body, child: SafeArea( child: Placeholder(key: insideBody), ), ), floatingActionButton: SizedBox( key: floatingActionButton, width: 77.0, height: 77.0, child: SafeArea( child: Placeholder(key: insideFloatingActionButton), ), ), persistentFooterButtons: <Widget>[ SizedBox( key: persistentFooterButton, width: 100.0, height: 90.0, child: SafeArea( child: Placeholder(key: insidePersistentFooterButton), ), ), ], drawer: SizedBox( key: drawer, width: 204.0, child: SafeArea( child: Placeholder(key: insideDrawer), ), ), ), ), ), ), ); // open drawer await tester.flingFrom(const Offset(795.0, 5.0), const Offset(-200.0, 0.0), 10.0); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(tester.getRect(find.byKey(appBar)), const Rect.fromLTRB(0.0, 0.0, 800.0, 43.0)); expect(tester.getRect(find.byKey(body)), const Rect.fromLTRB(0.0, 43.0, 800.0, 400.0)); expect(tester.getRect(find.byKey(floatingActionButton)), rectMoreOrLessEquals(const Rect.fromLTRB(36.0, 307.0, 113.0, 384.0))); expect(tester.getRect(find.byKey(persistentFooterButton)), const Rect.fromLTRB(28.0, 442.0, 128.0, 532.0)); // Includes 8px each top/bottom padding. expect(tester.getRect(find.byKey(drawer)), const Rect.fromLTRB(596.0, 0.0, 800.0, 600.0)); expect(tester.getRect(find.byKey(insideAppBar)), const Rect.fromLTRB(20.0, 30.0, 750.0, 43.0)); expect(tester.getRect(find.byKey(insideBody)), const Rect.fromLTRB(20.0, 43.0, 750.0, 400.0)); expect(tester.getRect(find.byKey(insideFloatingActionButton)), rectMoreOrLessEquals(const Rect.fromLTRB(36.0, 307.0, 113.0, 384.0))); expect(tester.getRect(find.byKey(insidePersistentFooterButton)), const Rect.fromLTRB(28.0, 442.0, 128.0, 532.0)); expect(tester.getRect(find.byKey(insideDrawer)), const Rect.fromLTRB(596.0, 30.0, 750.0, 540.0)); }); group('ScaffoldGeometry', () { testWidgets('bottomNavigationBar', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(MaterialApp(home: Scaffold( body: Container(), bottomNavigationBar: ConstrainedBox( key: key, constraints: const BoxConstraints.expand(height: 80.0), child: const _GeometryListener(), ), ))); final RenderBox navigationBox = tester.renderObject(find.byKey(key)); final RenderBox appBox = tester.renderObject(find.byType(MaterialApp)); final _GeometryListenerState listenerState = tester.state(find.byType(_GeometryListener)); final ScaffoldGeometry geometry = listenerState.cache.value; expect( geometry.bottomNavigationBarTop, appBox.size.height - navigationBox.size.height, ); }); testWidgets('no bottomNavigationBar', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(home: Scaffold( body: ConstrainedBox( constraints: const BoxConstraints.expand(height: 80.0), child: const _GeometryListener(), ), ))); final _GeometryListenerState listenerState = tester.state(find.byType(_GeometryListener)); final ScaffoldGeometry geometry = listenerState.cache.value; expect( geometry.bottomNavigationBarTop, null, ); }); testWidgets('Scaffold BottomNavigationBar bottom padding is not consumed by viewInsets.', (WidgetTester tester) async { Widget boilerplate(Widget child) { return Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: child, ), ); } final Widget child = boilerplate( Scaffold( resizeToAvoidBottomInset: false, body: const Placeholder(), bottomNavigationBar: Navigator( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( builder: (BuildContext context) { return BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.add), label: 'test', ), BottomNavigationBarItem( icon: Icon(Icons.add), label: 'test', ), ], ); }, ); }, ), ), ); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(padding: EdgeInsets.only(bottom: 20.0)), child: child, ), ); final Offset initialPoint = tester.getCenter(find.byType(Placeholder)); // Consume bottom padding - as if by the keyboard opening await tester.pumpWidget( MediaQuery( data: const MediaQueryData( viewPadding: EdgeInsets.only(bottom: 20), viewInsets: EdgeInsets.only(bottom: 300), ), child: child, ), ); final Offset finalPoint = tester.getCenter(find.byType(Placeholder)); expect(initialPoint, finalPoint); }); testWidgets('floatingActionButton', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(MaterialApp(home: Scaffold( body: Container(), floatingActionButton: FloatingActionButton( key: key, child: const _GeometryListener(), onPressed: () { }, ), ))); final RenderBox floatingActionButtonBox = tester.renderObject(find.byKey(key)); final _GeometryListenerState listenerState = tester.state(find.byType(_GeometryListener)); final ScaffoldGeometry geometry = listenerState.cache.value; final Rect fabRect = floatingActionButtonBox.localToGlobal(Offset.zero) & floatingActionButtonBox.size; expect( geometry.floatingActionButtonArea, fabRect, ); }); testWidgets('no floatingActionButton', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(home: Scaffold( body: ConstrainedBox( constraints: const BoxConstraints.expand(height: 80.0), child: const _GeometryListener(), ), ))); final _GeometryListenerState listenerState = tester.state(find.byType(_GeometryListener)); final ScaffoldGeometry geometry = listenerState.cache.value; expect( geometry.floatingActionButtonArea, null, ); }); testWidgets('floatingActionButton entrance/exit animation', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(MaterialApp(home: Scaffold( body: ConstrainedBox( constraints: const BoxConstraints.expand(height: 80.0), child: const _GeometryListener(), ), ))); await tester.pumpWidget(MaterialApp(home: Scaffold( body: Container(), floatingActionButton: FloatingActionButton( key: key, child: const _GeometryListener(), onPressed: () { }, ), ))); final _GeometryListenerState listenerState = tester.state(find.byType(_GeometryListener)); await tester.pump(const Duration(milliseconds: 50)); ScaffoldGeometry geometry = listenerState.cache.value; final Rect transitioningFabRect = geometry.floatingActionButtonArea!; final double transitioningRotation = tester.widget<RotationTransition>( find.byType(RotationTransition), ).turns.value; await tester.pump(const Duration(seconds: 3)); geometry = listenerState.cache.value; final RenderBox floatingActionButtonBox = tester.renderObject(find.byKey(key)); final Rect fabRect = floatingActionButtonBox.localToGlobal(Offset.zero) & floatingActionButtonBox.size; final double completedRotation = tester.widget<RotationTransition>( find.byType(RotationTransition), ).turns.value; expect(transitioningRotation, lessThan(1.0)); expect(completedRotation, equals(1.0)); expect( geometry.floatingActionButtonArea, fabRect, ); expect( geometry.floatingActionButtonArea!.center, transitioningFabRect.center, ); expect( geometry.floatingActionButtonArea!.width, greaterThan(transitioningFabRect.width), ); expect( geometry.floatingActionButtonArea!.height, greaterThan(transitioningFabRect.height), ); }); testWidgets('change notifications', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); int numNotificationsAtLastFrame = 0; await tester.pumpWidget(MaterialApp(home: Scaffold( body: ConstrainedBox( constraints: const BoxConstraints.expand(height: 80.0), child: const _GeometryListener(), ), ))); final _GeometryListenerState listenerState = tester.state(find.byType(_GeometryListener)); expect(listenerState.numNotifications, greaterThan(numNotificationsAtLastFrame)); numNotificationsAtLastFrame = listenerState.numNotifications; await tester.pumpWidget(MaterialApp(home: Scaffold( body: Container(), floatingActionButton: FloatingActionButton( key: key, child: const _GeometryListener(), onPressed: () { }, ), ))); expect(listenerState.numNotifications, greaterThan(numNotificationsAtLastFrame)); numNotificationsAtLastFrame = listenerState.numNotifications; await tester.pump(const Duration(milliseconds: 50)); expect(listenerState.numNotifications, greaterThan(numNotificationsAtLastFrame)); numNotificationsAtLastFrame = listenerState.numNotifications; await tester.pump(const Duration(seconds: 3)); expect(listenerState.numNotifications, greaterThan(numNotificationsAtLastFrame)); numNotificationsAtLastFrame = listenerState.numNotifications; }); testWidgets('Simultaneous drawers on either side', (WidgetTester tester) async { const String bodyLabel = 'I am the body'; const String drawerLabel = 'I am the label on start side'; const String endDrawerLabel = 'I am the label on end side'; final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(const MaterialApp(home: Scaffold( body: Text(bodyLabel), drawer: Drawer(child: Text(drawerLabel)), endDrawer: Drawer(child: Text(endDrawerLabel)), ))); expect(semantics, includesNodeWith(label: bodyLabel)); expect(semantics, isNot(includesNodeWith(label: drawerLabel))); expect(semantics, isNot(includesNodeWith(label: endDrawerLabel))); final ScaffoldState state = tester.firstState(find.byType(Scaffold)); state.openDrawer(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(semantics, isNot(includesNodeWith(label: bodyLabel))); expect(semantics, includesNodeWith(label: drawerLabel)); state.openEndDrawer(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(semantics, isNot(includesNodeWith(label: bodyLabel))); expect(semantics, includesNodeWith(label: endDrawerLabel)); semantics.dispose(); }); testWidgets('Drawer state query correctly', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: SafeArea( left: false, right: false, bottom: false, child: Scaffold( endDrawer: const Drawer( child: Text('endDrawer'), ), drawer: const Drawer( child: Text('drawer'), ), body: const Text('scaffold body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ), ); final ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); final Finder drawerOpenButton = find.byType(IconButton).first; final Finder endDrawerOpenButton = find.byType(IconButton).last; await tester.tap(drawerOpenButton); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, true); await tester.tap(endDrawerOpenButton, warnIfMissed: false); // hits the modal barrier await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); await tester.tap(endDrawerOpenButton); await tester.pumpAndSettle(); expect(scaffoldState.isEndDrawerOpen, true); await tester.tap(drawerOpenButton, warnIfMissed: false); // hits the modal barrier await tester.pumpAndSettle(); expect(scaffoldState.isEndDrawerOpen, false); scaffoldState.openDrawer(); expect(scaffoldState.isDrawerOpen, true); await tester.tap(endDrawerOpenButton, warnIfMissed: false); // hits the modal barrier await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); scaffoldState.openEndDrawer(); expect(scaffoldState.isEndDrawerOpen, true); scaffoldState.openDrawer(); expect(scaffoldState.isDrawerOpen, true); }); testWidgets('Dual Drawer Opening', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: SafeArea( left: false, right: false, bottom: false, child: Scaffold( endDrawer: const Drawer( child: Text('endDrawer'), ), drawer: const Drawer( child: Text('drawer'), ), body: const Text('scaffold body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ), ); // Open Drawer, tap on end drawer, which closes the drawer, but does // not open the drawer. await tester.tap(find.byType(IconButton).first); await tester.pumpAndSettle(); await tester.tap(find.byType(IconButton).last, warnIfMissed: false); // hits the modal barrier await tester.pumpAndSettle(); expect(find.text('endDrawer'), findsNothing); expect(find.text('drawer'), findsNothing); // Tapping the first opens the first drawer await tester.tap(find.byType(IconButton).first); await tester.pumpAndSettle(); expect(find.text('endDrawer'), findsNothing); expect(find.text('drawer'), findsOneWidget); // Tapping on the end drawer and then on the drawer should close the // drawer and then reopen it. await tester.tap(find.byType(IconButton).last, warnIfMissed: false); // hits the modal barrier await tester.pumpAndSettle(); await tester.tap(find.byType(IconButton).first); await tester.pumpAndSettle(); expect(find.text('endDrawer'), findsNothing); expect(find.text('drawer'), findsOneWidget); }); testWidgets('Drawer opens correctly with padding from MediaQuery (LTR)', (WidgetTester tester) async { const double simulatedNotchSize = 40.0; await tester.pumpWidget( MaterialApp( home: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), body: const Text('Scaffold Body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ); ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); await tester.dragFrom(const Offset(simulatedNotchSize + 15.0, 100), const Offset(300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); await tester.pumpWidget( MaterialApp( home: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.fromLTRB(simulatedNotchSize, 0, 0, 0), ), child: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), body: const Text('Scaffold Body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ), ); scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); await tester.dragFrom( const Offset(simulatedNotchSize + 15.0, 100), const Offset(300, 0), ); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, true); }); testWidgets('Drawer opens correctly with padding from MediaQuery (RTL)', (WidgetTester tester) async { const double simulatedNotchSize = 40.0; await tester.pumpWidget( MaterialApp( home: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), body: const Text('Scaffold Body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ); final double scaffoldWidth = tester.renderObject<RenderBox>( find.byType(Scaffold), ).size.width; ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); await tester.dragFrom( Offset(scaffoldWidth - simulatedNotchSize - 15.0, 100), const Offset(-300, 0), ); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); await tester.pumpWidget( MaterialApp( home: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.fromLTRB(0, 0, simulatedNotchSize, 0), ), child: Directionality( textDirection: TextDirection.rtl, child: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), body: const Text('Scaffold body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ), ), ); scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); await tester.dragFrom( Offset(scaffoldWidth - simulatedNotchSize - 15.0, 100), const Offset(-300, 0), ); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, true); }); }); testWidgets('Drawer opens correctly with custom edgeDragWidth', (WidgetTester tester) async { // The default edge drag width is 20.0. await tester.pumpWidget( MaterialApp( home: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), body: const Text('Scaffold body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ); ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); await tester.dragFrom(const Offset(35, 100), const Offset(300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); await tester.pumpWidget( MaterialApp( home: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), drawerEdgeDragWidth: 40.0, body: const Text('Scaffold Body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ); scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); await tester.dragFrom(const Offset(35, 100), const Offset(300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, true); }); testWidgets('Drawer does not open with a drag gesture when it is disabled on mobile', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), body: const Text('Scaffold Body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ); ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); // Test that we can open the drawer with a drag gesture when // `Scaffold.drawerEnableDragGesture` is true. await tester.dragFrom(const Offset(0, 100), const Offset(300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, true); await tester.dragFrom(const Offset(300, 100), const Offset(-300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); await tester.pumpWidget( MaterialApp( home: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), drawerEnableOpenDragGesture: false, body: const Text('Scaffold body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ); scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); // Test that we cannot open the drawer with a drag gesture when // `Scaffold.drawerEnableDragGesture` is false. await tester.dragFrom(const Offset(0, 100), const Offset(300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); // Test that we can close drawer with a drag gesture when // `Scaffold.drawerEnableDragGesture` is false. final Finder drawerOpenButton = find.byType(IconButton).first; await tester.tap(drawerOpenButton); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, true); await tester.dragFrom(const Offset(300, 100), const Offset(-300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); }, variant: TargetPlatformVariant.mobile()); testWidgets('Drawer does not open with a drag gesture on desktop', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( drawer: const Drawer( child: Text('Drawer'), ), body: const Text('Scaffold Body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ); final ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isDrawerOpen, false); // Test that we cannot open the drawer with a drag gesture. await tester.dragFrom(const Offset(0, 100), const Offset(300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); // Test that we can open the drawer with a tap gesture on drawer icon button. final Finder drawerOpenButton = find.byType(IconButton).first; await tester.tap(drawerOpenButton); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, true); // Test that we cannot close the drawer with a drag gesture. await tester.dragFrom(const Offset(300, 100), const Offset(-300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, true); // Test that we can close the drawer with a tap gesture in the body. await tester.tapAt(const Offset(500, 300)); await tester.pumpAndSettle(); expect(scaffoldState.isDrawerOpen, false); }, variant: TargetPlatformVariant.desktop()); testWidgets('End drawer does not open with a drag gesture when it is disabled', (WidgetTester tester) async { late double screenWidth; await tester.pumpWidget( MaterialApp( home: Builder( builder: (BuildContext context) { screenWidth = MediaQuery.sizeOf(context).width; return Scaffold( endDrawer: const Drawer( child: Text('Drawer'), ), body: const Text('Scaffold Body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ); }, ), ), ); ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isEndDrawerOpen, false); // Test that we can open the end drawer with a drag gesture when // `Scaffold.endDrawerEnableDragGesture` is true. await tester.dragFrom(Offset(screenWidth - 1, 100), const Offset(-300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isEndDrawerOpen, true); await tester.dragFrom(Offset(screenWidth - 300, 100), const Offset(300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isEndDrawerOpen, false); await tester.pumpWidget( MaterialApp( home: Scaffold( endDrawer: const Drawer( child: Text('Drawer'), ), endDrawerEnableOpenDragGesture: false, body: const Text('Scaffold body'), appBar: AppBar( centerTitle: true, title: const Text('Title'), ), ), ), ); scaffoldState = tester.state(find.byType(Scaffold)); expect(scaffoldState.isEndDrawerOpen, false); // Test that we cannot open the end drawer with a drag gesture when // `Scaffold.endDrawerEnableDragGesture` is false. await tester.dragFrom(Offset(screenWidth - 1, 100), const Offset(-300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isEndDrawerOpen, false); // Test that we can close the end drawer a with drag gesture when // `Scaffold.endDrawerEnableDragGesture` is false. final Finder endDrawerOpenButton = find.byType(IconButton).first; await tester.tap(endDrawerOpenButton); await tester.pumpAndSettle(); expect(scaffoldState.isEndDrawerOpen, true); await tester.dragFrom(Offset(screenWidth - 300, 100), const Offset(300, 0)); await tester.pumpAndSettle(); expect(scaffoldState.isEndDrawerOpen, false); }); testWidgets('Nested scaffold body insets', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/20295 final Key bodyKey = UniqueKey(); Widget buildFrame(bool? innerResizeToAvoidBottomInset, bool? outerResizeToAvoidBottomInset) { return Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(viewInsets: EdgeInsets.only(bottom: 100.0)), child: Builder( builder: (BuildContext context) { return Scaffold( resizeToAvoidBottomInset: outerResizeToAvoidBottomInset, body: Builder( builder: (BuildContext context) { return Scaffold( resizeToAvoidBottomInset: innerResizeToAvoidBottomInset, body: Container(key: bodyKey), ); }, ), ); }, ), ), ); } await tester.pumpWidget(buildFrame(true, true)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); await tester.pumpWidget(buildFrame(false, true)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); await tester.pumpWidget(buildFrame(true, false)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); // This is the only case where the body is not bottom inset. await tester.pumpWidget(buildFrame(false, false)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 600.0)); await tester.pumpWidget(buildFrame(null, null)); // resizeToAvoidBottomInset default is true expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); await tester.pumpWidget(buildFrame(null, false)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); await tester.pumpWidget(buildFrame(false, null)); expect(tester.getSize(find.byKey(bodyKey)), const Size(800.0, 500.0)); }); group('FlutterError control test', () { testWidgets('showBottomSheet() while Scaffold has bottom sheet', (WidgetTester tester) async { final GlobalKey<ScaffoldState> key = GlobalKey<ScaffoldState>(); await tester.pumpWidget( MaterialApp( home: Scaffold( key: key, body: Center( child: Container(), ), bottomSheet: const Text('Bottom sheet'), ), ), ); late FlutterError error; try { key.currentState!.showBottomSheet((BuildContext context) { final ThemeData themeData = Theme.of(context); return Container( decoration: BoxDecoration( border: Border(top: BorderSide(color: themeData.disabledColor)), ), child: Padding( padding: const EdgeInsets.all(32.0), child: Text('This is a Material persistent bottom sheet. Drag downwards to dismiss it.', textAlign: TextAlign.center, style: TextStyle( color: themeData.colorScheme.secondary, fontSize: 24.0, ), ), ), ); }); } on FlutterError catch (e) { error = e; } finally { expect(error, isNotNull); expect(error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' Scaffold.bottomSheet cannot be specified while a bottom sheet\n' ' displayed with showBottomSheet() is still visible.\n' ' Rebuild the Scaffold with a null bottomSheet before calling\n' ' showBottomSheet().\n', )); } }, ); testWidgets( 'didUpdate bottomSheet while a previous bottom sheet is still displayed', // TODO(polina-c): clean up leaks, https://github.com/flutter/flutter/issues/134787 [leaks-to-clean] experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(), (WidgetTester tester) async { final GlobalKey<ScaffoldState> key = GlobalKey<ScaffoldState>(); const Key buttonKey = Key('button'); final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); int state = 0; await tester.pumpWidget( MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Scaffold( key: key, body: Container(), floatingActionButton: FloatingActionButton( key: buttonKey, onPressed: () { state += 1; setState(() {}); }, ), bottomSheet: state == 0 ? null : const SizedBox(), ); }, ), ), ); key.currentState!.showBottomSheet((_) => Container()); await tester.tap(find.byKey(buttonKey)); await tester.pump(); expect(errors, isNotEmpty); expect(errors.first.exception, isFlutterError); final FlutterError error = errors.first.exception as FlutterError; expect(error.diagnostics.length, 2); expect(error.diagnostics.last.level, DiagnosticLevel.hint); expect( error.diagnostics.last.toStringDeep(), 'Use the PersistentBottomSheetController returned by\n' 'showBottomSheet() to close the old bottom sheet before creating a\n' 'Scaffold with a (non null) bottomSheet.\n', ); expect( error.toStringDeep(), 'FlutterError\n' ' Scaffold.bottomSheet cannot be specified while a bottom sheet\n' ' displayed with showBottomSheet() is still visible.\n' ' Use the PersistentBottomSheetController returned by\n' ' showBottomSheet() to close the old bottom sheet before creating a\n' ' Scaffold with a (non null) bottomSheet.\n', ); await tester.pumpAndSettle(); }, ); testWidgets('Call to Scaffold.of() without context', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Builder( builder: (BuildContext context) { Scaffold.of(context).showBottomSheet((BuildContext context) { return Container(); }); return Container(); }, ), ), ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); final FlutterError error = exception as FlutterError; expect(error.diagnostics.length, 5); expect(error.diagnostics[2].level, DiagnosticLevel.hint); expect( error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes( 'There are several ways to avoid this problem. The simplest is to\n' 'use a Builder to get a context that is "under" the Scaffold. For\n' 'an example of this, please see the documentation for\n' 'Scaffold.of():\n' ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n', ), ); expect(error.diagnostics[3].level, DiagnosticLevel.hint); expect( error.diagnostics[3].toStringDeep(), equalsIgnoringHashCodes( 'A more efficient solution is to split your build function into\n' 'several widgets. This introduces a new context from which you can\n' 'obtain the Scaffold. In this solution, you would have an outer\n' 'widget that creates the Scaffold populated by instances of your\n' 'new inner widgets, and then in these inner widgets you would use\n' 'Scaffold.of().\n' 'A less elegant but more expedient solution is assign a GlobalKey\n' 'to the Scaffold, then use the key.currentState property to obtain\n' 'the ScaffoldState rather than using the Scaffold.of() function.\n', ), ); expect(error.diagnostics[4], isA<DiagnosticsProperty<Element>>()); expect( error.toStringDeep(), 'FlutterError\n' ' Scaffold.of() called with a context that does not contain a\n' ' Scaffold.\n' ' No Scaffold ancestor could be found starting from the context\n' ' that was passed to Scaffold.of(). This usually happens when the\n' ' context provided is from the same StatefulWidget as that whose\n' ' build function actually creates the Scaffold widget being sought.\n' ' There are several ways to avoid this problem. The simplest is to\n' ' use a Builder to get a context that is "under" the Scaffold. For\n' ' an example of this, please see the documentation for\n' ' Scaffold.of():\n' ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n' ' A more efficient solution is to split your build function into\n' ' several widgets. This introduces a new context from which you can\n' ' obtain the Scaffold. In this solution, you would have an outer\n' ' widget that creates the Scaffold populated by instances of your\n' ' new inner widgets, and then in these inner widgets you would use\n' ' Scaffold.of().\n' ' A less elegant but more expedient solution is assign a GlobalKey\n' ' to the Scaffold, then use the key.currentState property to obtain\n' ' the ScaffoldState rather than using the Scaffold.of() function.\n' ' The context used was:\n' ' Builder\n', ); await tester.pumpAndSettle(); }); testWidgets('Call to Scaffold.geometryOf() without context', (WidgetTester tester) async { ValueListenable<ScaffoldGeometry>? geometry; await tester.pumpWidget( MaterialApp( home: Builder( builder: (BuildContext context) { geometry = Scaffold.geometryOf(context); return Container(); }, ), ), ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect(geometry, isNull); final FlutterError error = exception as FlutterError; expect(error.diagnostics.length, 5); expect(error.diagnostics[2].level, DiagnosticLevel.hint); expect( error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes( 'There are several ways to avoid this problem. The simplest is to\n' 'use a Builder to get a context that is "under" the Scaffold. For\n' 'an example of this, please see the documentation for\n' 'Scaffold.of():\n' ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n', ), ); expect(error.diagnostics[3].level, DiagnosticLevel.hint); expect( error.diagnostics[3].toStringDeep(), equalsIgnoringHashCodes( 'A more efficient solution is to split your build function into\n' 'several widgets. This introduces a new context from which you can\n' 'obtain the Scaffold. In this solution, you would have an outer\n' 'widget that creates the Scaffold populated by instances of your\n' 'new inner widgets, and then in these inner widgets you would use\n' 'Scaffold.geometryOf().\n', ), ); expect(error.diagnostics[4], isA<DiagnosticsProperty<Element>>()); expect( error.toStringDeep(), 'FlutterError\n' ' Scaffold.geometryOf() called with a context that does not contain\n' ' a Scaffold.\n' ' This usually happens when the context provided is from the same\n' ' StatefulWidget as that whose build function actually creates the\n' ' Scaffold widget being sought.\n' ' There are several ways to avoid this problem. The simplest is to\n' ' use a Builder to get a context that is "under" the Scaffold. For\n' ' an example of this, please see the documentation for\n' ' Scaffold.of():\n' ' https://api.flutter.dev/flutter/material/Scaffold/of.html\n' ' A more efficient solution is to split your build function into\n' ' several widgets. This introduces a new context from which you can\n' ' obtain the Scaffold. In this solution, you would have an outer\n' ' widget that creates the Scaffold populated by instances of your\n' ' new inner widgets, and then in these inner widgets you would use\n' ' Scaffold.geometryOf().\n' ' The context used was:\n' ' Builder\n', ); await tester.pumpAndSettle(); }); testWidgets('FloatingActionButton always keeps the same position regardless of extendBodyBehindAppBar', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Scaffold( appBar: AppBar(), floatingActionButton: FloatingActionButton( onPressed: () {}, child: const Icon(Icons.add), ), floatingActionButtonLocation: FloatingActionButtonLocation.endTop, ), )); final Offset defaultOffset = tester.getCenter(find.byType(FloatingActionButton)); await tester.pumpWidget(MaterialApp( home: Scaffold( appBar: AppBar(), floatingActionButton: FloatingActionButton( onPressed: () {}, child: const Icon(Icons.add), ), floatingActionButtonLocation: FloatingActionButtonLocation.endTop, extendBodyBehindAppBar: true, ), )); final Offset extendedBodyOffset = tester.getCenter(find.byType(FloatingActionButton)); expect(defaultOffset.dy, extendedBodyOffset.dy); }); }); testWidgets('ScaffoldMessenger.maybeOf can return null if not found', (WidgetTester tester) async { ScaffoldMessengerState? scaffoldMessenger; const Key tapTarget = Key('tap-target'); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Scaffold( body: Builder( builder: (BuildContext context) { return GestureDetector( key: tapTarget, onTap: () { scaffoldMessenger = ScaffoldMessenger.maybeOf(context); }, behavior: HitTestBehavior.opaque, child: const SizedBox( height: 100.0, width: 100.0, ), ); }, ), ), ), )); await tester.tap(find.byKey(tapTarget)); await tester.pump(); expect(scaffoldMessenger, isNull); }); testWidgets('ScaffoldMessenger.of will assert if not found', (WidgetTester tester) async { const Key tapTarget = Key('tap-target'); final List<dynamic> exceptions = <dynamic>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Scaffold( body: Builder( builder: (BuildContext context) { return GestureDetector( key: tapTarget, onTap: () { ScaffoldMessenger.of(context); }, behavior: HitTestBehavior.opaque, child: const SizedBox( height: 100.0, width: 100.0, ), ); }, ), ), )); await tester.tap(find.byKey(tapTarget)); FlutterError.onError = oldHandler; expect(exceptions.length, 1); // ignore: avoid_dynamic_calls expect(exceptions.single.runtimeType, FlutterError); final FlutterError error = exceptions.first as FlutterError; expect(error.diagnostics.length, 5); expect(error.diagnostics[2], isA<DiagnosticsProperty<Element>>()); expect(error.diagnostics[3], isA<DiagnosticsBlock>()); expect(error.diagnostics[4].level, DiagnosticLevel.hint); expect( error.diagnostics[4].toStringDeep(), equalsIgnoringHashCodes( 'Typically, the ScaffoldMessenger widget is introduced by the\n' 'MaterialApp at the top of your application widget tree.\n', ), ); expect(error.toStringDeep(), startsWith( 'FlutterError\n' ' No ScaffoldMessenger widget found.\n' ' Builder widgets require a ScaffoldMessenger widget ancestor.\n' ' The specific widget that could not find a ScaffoldMessenger\n' ' ancestor was:\n' ' Builder\n' ' The ancestors of this widget were:\n' )); expect(error.toStringDeep(), endsWith( ' [root]\n' ' Typically, the ScaffoldMessenger widget is introduced by the\n' ' MaterialApp at the top of your application widget tree.\n', )); }); testWidgets('ScaffoldMessenger checks for nesting when a new Scaffold is registered', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/77251 const String snackBarContent = 'SnackBar Content'; await tester.pumpWidget(MaterialApp( home: Builder( builder: (BuildContext context) => Scaffold( body: Scaffold( body: TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute<void>( builder: (BuildContext context) { return Scaffold( body: Column( children: <Widget>[ TextButton( onPressed: () { const SnackBar snackBar = SnackBar( content: Text(snackBarContent), behavior: SnackBarBehavior.floating, ); ScaffoldMessenger.of(context).showSnackBar(snackBar); }, child: const Text('Show SnackBar'), ), TextButton( onPressed: () { Navigator.pop(context); }, child: const Text('Pop route'), ), ], ), ); }, ), ); }, child: const Text('Push route'), ), ), ), ), )); expect(find.text(snackBarContent), findsNothing); await tester.tap(find.text('Push route')); await tester.pumpAndSettle(); expect(find.text(snackBarContent), findsNothing); expect(find.text('Pop route'), findsOneWidget); // Show SnackBar on second page await tester.tap(find.text('Show SnackBar')); await tester.pump(); expect(find.text(snackBarContent), findsOneWidget); // Pop the second page, the SnackBar completes a hero animation to the next route. // If we have not handled the nested Scaffolds properly, this will throw an // exception as duplicate SnackBars on the first route would have a common hero tag. await tester.tap(find.text('Pop route')); await tester.pump(); // There are SnackBars two during the execution of the hero animation. expect(find.text(snackBarContent), findsNWidgets(2)); await tester.pumpAndSettle(); expect(find.text(snackBarContent), findsOneWidget); // Allow the SnackBar to animate out await tester.pump(const Duration(seconds: 4)); await tester.pumpAndSettle(); expect(find.text(snackBarContent), findsNothing); }); testWidgets('Drawer can be dismissed with escape keyboard shortcut', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/106131 bool isDrawerOpen = false; bool isEndDrawerOpen = false; await tester.pumpWidget(MaterialApp( home: Scaffold( drawer: Container( color: Colors.blue, ), onDrawerChanged: (bool isOpen) { isDrawerOpen = isOpen; }, endDrawer: Container( color: Colors.green, ), onEndDrawerChanged: (bool isOpen) { isEndDrawerOpen = isOpen; }, body: Container(), ), )); final ScaffoldState scaffoldState = tester.state(find.byType(Scaffold)); scaffoldState.openDrawer(); await tester.pumpAndSettle(); expect(isDrawerOpen, true); expect(isEndDrawerOpen, false); // Try to dismiss the drawer with the shortcut key await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(isDrawerOpen, false); expect(isEndDrawerOpen, false); scaffoldState.openEndDrawer(); await tester.pumpAndSettle(); expect(isDrawerOpen, false); expect(isEndDrawerOpen, true); // Try to dismiss the drawer with the shortcut key await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(isDrawerOpen, false); expect(isEndDrawerOpen, false); }); testWidgets('ScaffoldMessenger showSnackBar throws an intuitive error message if called during build', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('SnackBar'))); return const SizedBox.shrink(); }, ), ), )); final FlutterError error = tester.takeException() as FlutterError; final ErrorSummary summary = error.diagnostics.first as ErrorSummary; expect(summary.toString(), 'The showSnackBar() method cannot be called during build.'); }); testWidgets('Persistent BottomSheet is not dismissible via a11y means', (WidgetTester tester) async { final Key bottomSheetKey = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( bottomSheet: Container( key: bottomSheetKey, height: 44, color: Colors.blue, child: const Text('BottomSheet'), ), ), )); expect( tester.getSemantics(find.byKey(bottomSheetKey)), // Having the redundant argument value makes the intent of the test clear. // ignore: avoid_redundant_argument_values matchesSemantics(label: 'BottomSheet', hasDismissAction: false), ); }); // Regression test for https://github.com/flutter/flutter/issues/117004 testWidgets('can rebuild and remove bottomSheet at the same time', (WidgetTester tester) async { bool themeIsLight = true; bool? defaultBottomSheet = true; final GlobalKey bottomSheetKey1 = GlobalKey(); final GlobalKey bottomSheetKey2 = GlobalKey(); late StateSetter setState; await tester.pumpWidget( StatefulBuilder( builder: (BuildContext context, StateSetter stateSetter) { setState = stateSetter; return MaterialApp( theme: themeIsLight ? ThemeData.light() : ThemeData.dark(), home: Scaffold( bottomSheet: defaultBottomSheet == null ? null : defaultBottomSheet! ? Container( key: bottomSheetKey1, width: double.infinity, height: 100, color: Colors.blue, child: const Text('BottomSheet'), ) : Container( key: bottomSheetKey2, width: double.infinity, height: 100, color: Colors.red, child: const Text('BottomSheet'), ), body: const Placeholder(), ), ); }, ), ); expect(find.byKey(bottomSheetKey1), findsOneWidget); expect(find.byKey(bottomSheetKey2), findsNothing); // Change to the other bottomSheet. setState(() { defaultBottomSheet = false; }); expect(find.byKey(bottomSheetKey1), findsOneWidget); expect(find.byKey(bottomSheetKey2), findsNothing); await tester.pumpAndSettle(); expect(find.byKey(bottomSheetKey1), findsNothing); expect(find.byKey(bottomSheetKey2), findsOneWidget); // Set bottomSheet to null, which starts its exit animation. setState(() { defaultBottomSheet = null; }); expect(find.byKey(bottomSheetKey1), findsNothing); expect(find.byKey(bottomSheetKey2), findsOneWidget); // While the bottomSheet is on the way out, change the theme to cause it to // rebuild. setState(() { themeIsLight = false; }); expect(find.byKey(bottomSheetKey1), findsNothing); expect(find.byKey(bottomSheetKey2), findsOneWidget); // The most recent bottomSheet remains on screen during the exit animation. await tester.pump(_bottomSheetExitDuration); expect(find.byKey(bottomSheetKey1), findsNothing); expect(find.byKey(bottomSheetKey2), findsOneWidget); // After animating out, the bottomSheet is gone. await tester.pumpAndSettle(); expect(find.byKey(bottomSheetKey1), findsNothing); expect(find.byKey(bottomSheetKey2), findsNothing); expect(tester.takeException(), isNull); }); testWidgets('showBottomSheet removes scrim when draggable sheet is dismissed', (WidgetTester tester) async { final DraggableScrollableController draggableController = DraggableScrollableController(); addTearDown(draggableController.dispose); final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey(); PersistentBottomSheetController? sheetController; await tester.pumpWidget(MaterialApp( home: Scaffold( key: scaffoldKey, body: const Center(child: Text('body')), ), )); sheetController = scaffoldKey.currentState!.showBottomSheet((_) { return DraggableScrollableSheet( expand: false, controller: draggableController, builder: (BuildContext context, ScrollController scrollController) { return SingleChildScrollView( controller: scrollController, child: const Placeholder(), ); }, ); }); Finder findModalBarrier() => find.descendant(of: find.byType(Scaffold), matching: find.byType(ModalBarrier)); await tester.pump(); expect(find.byType(BottomSheet), findsOneWidget); // The scrim is not present yet. expect(findModalBarrier(), findsNothing); // Expand the sheet to 80% of parent height to show the scrim. draggableController.jumpTo(0.8); await tester.pump(); expect(findModalBarrier(), findsOneWidget); // Dismiss the sheet. sheetController.close(); await tester.pumpAndSettle(); // The scrim should be gone. expect(findModalBarrier(), findsNothing); }); testWidgets("Closing bottom sheet & removing FAB at the same time doesn't throw assertion", (WidgetTester tester) async { final Key bottomSheetKey = UniqueKey(); PersistentBottomSheetController? controller; bool show = true; await tester.pumpWidget(StatefulBuilder( builder: (_, StateSetter setState) => MaterialApp( home: Scaffold( body: Center( child: Builder( builder: (BuildContext context) => ElevatedButton( onPressed: () { if (controller == null) { controller = showBottomSheet( context: context, builder: (_) => Container( key: bottomSheetKey, height: 200, ), ); } else { controller!.close(); controller = null; } }, child: const Text('BottomSheet'), )), ), floatingActionButton: show ? FloatingActionButton(onPressed: () => setState(() => show = false)) : null, ), ), )); // Show bottom sheet. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(const Duration(seconds: 1)); // Bottom sheet and FAB are visible. expect(find.byType(FloatingActionButton), findsOneWidget); expect(find.byKey(bottomSheetKey), findsOneWidget); // Close bottom sheet while removing FAB. await tester.tap(find.byType(FloatingActionButton)); await tester.pump(); // start animation await tester.tap(find.byType(ElevatedButton)); // Let the animation finish. await tester.pumpAndSettle(const Duration(seconds: 1)); // Bottom sheet and FAB are gone. expect(find.byType(FloatingActionButton), findsNothing); expect(find.byKey(bottomSheetKey), findsNothing); // No exception is thrown. expect(tester.takeException(), isNull); }); testWidgets('ScaffoldMessenger showSnackBar default animatiom', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('I am a snack bar.'), showCloseIcon: true, ), ); }, child: const Text('Show SnackBar'), ); }, ), ), )); // Tap the button to show the SnackBar. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); await tester.pump(const Duration(milliseconds: 125)); // Advance the animation by 125ms. // The SnackBar is partially visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(576.7, 0.1)); await tester.pump(const Duration(milliseconds: 125)); // Advance the animation by 125ms. // The SnackBar is fully visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(566, 0.1)); // Tap the close button to dismiss the SnackBar. await tester.tap(find.byType(IconButton)); await tester.pump(); await tester.pump(const Duration(milliseconds: 125)); // Advance the animation by 125ms. // The SnackBar is partially visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(576.7, 0.1)); await tester.pump(const Duration(milliseconds: 125)); // Advance the animation by 125ms. // The SnackBar is dismissed. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(614, 0.1)); }); testWidgets('ScaffoldMessenger showSnackBar animation can be customized', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('I am a snack bar.'), showCloseIcon: true, ), snackBarAnimationStyle: AnimationStyle( duration: const Duration(milliseconds: 1200), reverseDuration: const Duration(milliseconds: 600), ), ); }, child: const Text('Show SnackBar'), ); }, ), ), )); // Tap the button to show the SnackBar. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); await tester.pump(const Duration(milliseconds: 300)); // Advance the animation by 300ms. // The SnackBar is partially visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(602.6, 0.1)); await tester.pump(const Duration(milliseconds: 300)); // Advance the animation by 300ms. // The SnackBar is partially visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(576.7, 0.1)); await tester.pump(const Duration(milliseconds: 600)); // Advance the animation by 600ms. // The SnackBar is fully visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(566, 0.1)); // Tap the close button to dismiss the SnackBar. await tester.tap(find.byType(IconButton)); await tester.pump(); await tester.pump(const Duration(milliseconds: 300)); // Advance the animation by 300ns. // The SnackBar is partially visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(576.7, 0.1)); await tester.pump(const Duration(milliseconds: 300)); // Advance the animation by 300ms. // The SnackBar is dismissed. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(614, 0.1)); }); testWidgets('Updated snackBarAnimationStyle updates snack bar animation', (WidgetTester tester) async { Widget buildSnackBar(AnimationStyle snackBarAnimationStyle) { return MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('I am a snack bar.'), showCloseIcon: true, ), snackBarAnimationStyle: snackBarAnimationStyle, ); }, child: const Text('Show SnackBar'), ); }, ), ), ); } // Test custom animation style. await tester.pumpWidget(buildSnackBar(AnimationStyle( duration: const Duration(milliseconds: 800), reverseDuration: const Duration(milliseconds: 400), ))); // Tap the button to show the SnackBar. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); // Advance the animation by 400ms. // The SnackBar is partially visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(576.7, 0.1)); await tester.pump(const Duration(milliseconds: 400)); // Advance the animation by 400ms. // The SnackBar is fully visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(566, 0.1)); // Tap the close button to dismiss the SnackBar. await tester.tap(find.byType(IconButton)); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); // Advance the animation by 400ms. // The SnackBar is dismissed. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(614, 0.1)); // Test no animation style. await tester.pumpWidget(buildSnackBar(AnimationStyle.noAnimation)); await tester.pumpAndSettle(); // Tap the button to show the SnackBar. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); // The SnackBar is fully visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(566, 0.1)); // Tap the close button to dismiss the SnackBar. await tester.tap(find.byType(IconButton)); await tester.pump(); // The SnackBar is dismissed. expect(find.text('I am a snack bar.'), findsNothing); }); testWidgets('snackBarAnimationStyle with only reverseDuration uses default forward duration', (WidgetTester tester) async { Widget buildSnackBar(AnimationStyle snackBarAnimationStyle) { return MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('I am a snack bar.'), showCloseIcon: true, ), snackBarAnimationStyle: snackBarAnimationStyle, ); }, child: const Text('Show SnackBar'), ); }, ), ), ); } // Test custom animation style with only reverseDuration. await tester.pumpWidget(buildSnackBar(AnimationStyle( reverseDuration: const Duration(milliseconds: 400), ))); // Tap the button to show the SnackBar. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); // Advance the animation by 1/2 of the default forward duration. await tester.pump(const Duration(milliseconds: 125)); // The SnackBar is partially visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(576.7, 0.1)); // Advance the animation by 1/2 of the default forward duration. await tester.pump(const Duration(milliseconds: 125)); // Advance the animation by 125ms. // The SnackBar is fully visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(566, 0.1)); // Tap the close button to dismiss the SnackBar. await tester.tap(find.byType(IconButton)); await tester.pump(); // Advance the animation by 1/2 of the reverse duration. await tester.pump(const Duration(milliseconds: 200)); // The SnackBar is partially visible. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(576.7, 0.1)); // Advance the animation by 1/2 of the reverse duration. await tester.pump(const Duration(milliseconds: 200)); // Advance the animation by 200ms. // The SnackBar is dismissed. expect(tester.getTopLeft(find.text('I am a snack bar.')).dy, closeTo(614, 0.1)); }); } class _GeometryListener extends StatefulWidget { const _GeometryListener(); @override _GeometryListenerState createState() => _GeometryListenerState(); } class _GeometryListenerState extends State<_GeometryListener> { @override Widget build(BuildContext context) { return CustomPaint( painter: cache, ); } int numNotifications = 0; ValueListenable<ScaffoldGeometry>? geometryListenable; late _GeometryCachePainter cache; @override void didChangeDependencies() { super.didChangeDependencies(); final ValueListenable<ScaffoldGeometry> newListenable = Scaffold.geometryOf(context); if (geometryListenable == newListenable) { return; } if (geometryListenable != null) { geometryListenable!.removeListener(onGeometryChanged); } geometryListenable = newListenable; geometryListenable!.addListener(onGeometryChanged); cache = _GeometryCachePainter(geometryListenable!); } void onGeometryChanged() { numNotifications += 1; } } // The Scaffold.geometryOf() value is only available at paint time. // To fetch it for the tests we implement this CustomPainter that just // caches the ScaffoldGeometry value in its paint method. class _GeometryCachePainter extends CustomPainter { _GeometryCachePainter(this.geometryListenable) : super(repaint: geometryListenable); final ValueListenable<ScaffoldGeometry> geometryListenable; late ScaffoldGeometry value; @override void paint(Canvas canvas, Size size) { value = geometryListenable.value; } @override bool shouldRepaint(_GeometryCachePainter oldDelegate) { return true; } } class _CustomPageRoute<T> extends PageRoute<T> { _CustomPageRoute({ required this.builder, RouteSettings super.settings = const RouteSettings(), this.maintainState = true, super.fullscreenDialog, }); final WidgetBuilder builder; @override Duration get transitionDuration => const Duration(milliseconds: 300); @override Color? get barrierColor => null; @override String? get barrierLabel => null; @override final bool maintainState; @override Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return builder(context); } @override Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return child; } }
flutter/packages/flutter/test/material/scaffold_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/scaffold_test.dart", "repo_id": "flutter", "token_count": 50906 }
665
// 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/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; // Vertical position at which to anchor the toolbar for testing. const double _kAnchor = 200; // Amount for toolbar to overlap bottom padding for testing. const double _kTestToolbarOverlap = 10; void main() { TestWidgetsFlutterBinding.ensureInitialized(); /// Builds test button items for each of the suggestions provided. List<ContextMenuButtonItem> buildSuggestionButtons(List<String> suggestions) { final List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; for (final String suggestion in suggestions) { buttonItems.add(ContextMenuButtonItem( onPressed: () {}, label: suggestion, )); } final ContextMenuButtonItem deleteButton = ContextMenuButtonItem( onPressed: () {}, type: ContextMenuButtonType.delete, label: 'DELETE', ); buttonItems.add(deleteButton); return buttonItems; } /// Finds the container of the [SpellCheckSuggestionsToolbar] so that /// the position of the toolbar itself may be determined. Finder findSpellCheckSuggestionsToolbar() { return find.descendant( of: find.byType(MaterialApp), matching: find.byWidgetPredicate( (Widget w) => '${w.runtimeType}' == '_SpellCheckSuggestionsToolbarContainer'), ); } testWidgets('positions toolbar below anchor when it fits above bottom view padding', (WidgetTester tester) async { // We expect the toolbar to be positioned right below the anchor with padding accounted for. await tester.pumpWidget( MaterialApp( home: Scaffold( body: SpellCheckSuggestionsToolbar( anchor: const Offset(0.0, _kAnchor), buttonItems: buildSuggestionButtons(<String>['hello', 'yellow', 'yell']), ), ), ), ); final double toolbarY = tester.getTopLeft(findSpellCheckSuggestionsToolbar()).dy; expect(toolbarY, equals(_kAnchor)); }); testWidgets('re-positions toolbar higher below anchor when it does not fit above bottom view padding', (WidgetTester tester) async { // We expect the toolbar to be positioned _kTestToolbarOverlap pixels above the anchor. const double expectedToolbarY = _kAnchor - _kTestToolbarOverlap; await tester.pumpWidget( MaterialApp( home: Scaffold( body: SpellCheckSuggestionsToolbar( anchor: const Offset(0.0, _kAnchor - _kTestToolbarOverlap), buttonItems: buildSuggestionButtons(<String>['hello', 'yellow', 'yell']), ), ), ), ); final double toolbarY = tester.getTopLeft(findSpellCheckSuggestionsToolbar()).dy; expect(toolbarY, equals(expectedToolbarY)); }); testWidgets('more than three suggestions throws an error', (WidgetTester tester) async { Future<void> pumpToolbar(List<String> suggestions) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: SpellCheckSuggestionsToolbar( anchor: const Offset(0.0, _kAnchor - _kTestToolbarOverlap), buttonItems: buildSuggestionButtons(suggestions), ), ), ), ); } await pumpToolbar(<String>['hello', 'yellow', 'yell']); expect(() async { await pumpToolbar(<String>['hello', 'yellow', 'yell', 'yeller']); }, throwsAssertionError); }, skip: kIsWeb, // [intended] ); test('buildSuggestionButtons only considers the first three suggestions', () { final _FakeEditableTextState editableTextState = _FakeEditableTextState( suggestions: <String>[ 'hello', 'yellow', 'yell', 'yeller', ], ); final List<ContextMenuButtonItem>? buttonItems = SpellCheckSuggestionsToolbar.buildButtonItems(editableTextState); expect(buttonItems, isNotNull); final Iterable<String?> labels = buttonItems!.map((ContextMenuButtonItem buttonItem) { return buttonItem.label; }); expect(labels, hasLength(4)); expect(labels, contains('hello')); expect(labels, contains('yellow')); expect(labels, contains('yell')); expect(labels, contains(null)); // For the delete button. expect(labels, isNot(contains('yeller'))); }); test('buildButtonItems builds only a delete button when no suggestions', () { final _FakeEditableTextState editableTextState = _FakeEditableTextState(); final List<ContextMenuButtonItem>? buttonItems = SpellCheckSuggestionsToolbar.buildButtonItems(editableTextState); expect(buttonItems, hasLength(1)); expect(buttonItems!.first.type, ContextMenuButtonType.delete); }); } class _FakeEditableTextState extends EditableTextState { _FakeEditableTextState({ this.suggestions, }); final List<String>? suggestions; @override TextEditingValue get currentTextEditingValue => TextEditingValue.empty; @override SuggestionSpan? findSuggestionSpanAtCursorIndex(int cursorIndex) { return SuggestionSpan( const TextRange( start: 0, end: 0, ), suggestions ?? <String>[], ); } }
flutter/packages/flutter/test/material/spell_check_suggestions_toolbar_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/spell_check_suggestions_toolbar_test.dart", "repo_id": "flutter", "token_count": 1957 }
666
// 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. // reduced-test-set: // This file is run as part of a reduced test set in CI on Mac and Windows // machines. // no-shuffle: // TODO(122950): Remove this tag once this test's state leaks/test // dependencies have been fixed. // https://github.com/flutter/flutter/issues/122950 // Fails with "flutter test --test-randomize-ordering-seed=20230318" @Tags(<String>['reduced-test-set', 'no-shuffle']) library; import 'dart:math' as math; import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/clipboard_utils.dart'; import '../widgets/editable_text_utils.dart'; import '../widgets/live_text_utils.dart'; import '../widgets/process_text_utils.dart'; import '../widgets/semantics_tester.dart'; import '../widgets/text_selection_toolbar_utils.dart'; import 'feedback_tester.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final MockClipboard mockClipboard = MockClipboard(); const String kThreeLines = 'First line of text is\n' 'Second line goes until\n' 'Third line of stuff'; const String kMoreThanFourLines = '$kThreeLines\n' "Fourth line won't display and ends at"; // Gap between caret and edge of input, defined in editable.dart. const int kCaretGap = 1; setUp(() async { debugResetSemanticsIdCounter(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, mockClipboard.handleMethodCall, ); // Fill the clipboard so that the Paste option is available in the text // selection menu. await Clipboard.setData(const ClipboardData(text: 'Clipboard data')); }); tearDown(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, null, ); }); final Key textFieldKey = UniqueKey(); Widget textFieldBuilder({ int? maxLines = 1, int? minLines, }) { return boilerplate( child: TextField( key: textFieldKey, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: maxLines, minLines: minLines, decoration: const InputDecoration( hintText: 'Placeholder', ), ), ); } testWidgets( 'Live Text button shows and hides correctly when LiveTextStatus changes', (WidgetTester tester) async { final LiveTextInputTester liveTextInputTester = LiveTextInputTester(); addTearDown(liveTextInputTester.dispose); final TextEditingController controller = _textEditingController(); const Key key = ValueKey<String>('TextField'); final FocusNode focusNode = _focusNode(); final Widget app = MaterialApp( theme: ThemeData(platform: TargetPlatform.iOS), home: Scaffold( body: Center( child: TextField( key: key, controller: controller, focusNode: focusNode, ), ), ), ); liveTextInputTester.mockLiveTextInputEnabled = true; await tester.pumpWidget(app); focusNode.requestFocus(); await tester.pumpAndSettle(); final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); await tester.pumpAndSettle(); expect( findLiveTextButton(), kIsWeb ? findsNothing : findsOneWidget, ); liveTextInputTester.mockLiveTextInputEnabled = false; await tester.longPress(textFinder); await tester.pumpAndSettle(); expect(findLiveTextButton(), findsNothing); }, ); testWidgets('text field selection toolbar should hide when the user starts typing', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Center( child: SizedBox( width: 100, height: 100, child: TextField( decoration: InputDecoration(hintText: 'Placeholder'), ), ), ), ), ), ); await tester.showKeyboard(find.byType(TextField)); const String testValue = 'A B C'; tester.testTextInput.updateEditingValue( const TextEditingValue( text: testValue, ), ); await tester.pump(); // The selectWordsInRange with SelectionChangedCause.tap seems to be needed to show the toolbar. // (This is true even if we provide selection parameter to the TextEditingValue above.) final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); expect(state.showToolbar(), true); // This is needed for the AnimatedOpacity to turn from 0 to 1 so the toolbar is visible. await tester.pumpAndSettle(); // Sanity check that the toolbar widget exists. expect(find.text('Paste'), findsOneWidget); const String newValue = 'A B C D'; tester.testTextInput.updateEditingValue( const TextEditingValue( text: newValue, ), ); await tester.pump(); expect(state.selectionOverlay!.toolbarIsVisible, isFalse); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('Composing change does not hide selection handle caret', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/108673 final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); const String testValue = 'I Love Flutter!'; await tester.enterText(find.byType(TextField), testValue); expect(controller.value.text, testValue); await skipPastScrollingAnimation(tester); // Handle not shown. expect(controller.selection.isCollapsed, true); final Finder fadeFinder = find.byType(FadeTransition); FadeTransition handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(0.0)); // Tap on the text field to show the handle. await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); expect(fadeFinder, findsNWidgets(1)); handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(1.0)); final RenderObject handleRenderObjectBegin = tester.renderObject(fadeFinder.at(0)); expect( controller.value, const TextEditingValue( text: 'I Love Flutter!', selection: TextSelection.collapsed(offset: 15, affinity: TextAffinity.upstream), ), ); // Simulate text composing change. tester.testTextInput.updateEditingValue( controller.value.copyWith( composing: const TextRange(start: 7, end: 15), ), ); await skipPastScrollingAnimation(tester); expect( controller.value, const TextEditingValue( text: 'I Love Flutter!', selection: TextSelection.collapsed(offset: 15, affinity: TextAffinity.upstream), composing: TextRange(start: 7, end: 15), ), ); // Handle still shown. expect(controller.selection.isCollapsed, true); handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(1.0)); // Simulate text composing and affinity change. tester.testTextInput.updateEditingValue( controller.value.copyWith( selection: controller.value.selection.copyWith(affinity: TextAffinity.downstream), composing: const TextRange(start: 8, end: 15), ), ); await skipPastScrollingAnimation(tester); expect( controller.value, const TextEditingValue( text: 'I Love Flutter!', selection: TextSelection.collapsed(offset: 15, affinity: TextAffinity.upstream), composing: TextRange(start: 8, end: 15), ), ); // Handle still shown. expect(controller.selection.isCollapsed, true); handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(1.0)); final RenderObject handleRenderObjectEnd = tester.renderObject(fadeFinder.at(0)); // The RenderObject sub-tree should not be unmounted. expect(identical(handleRenderObjectBegin, handleRenderObjectEnd), true); }); testWidgets('can use the desktop cut/copy/paste buttons on Mac', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'blah1 blah2', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Initially, the menu is not shown and there is no selection. expectNoCupertinoToolbar(); expect(controller.selection, const TextSelection(baseOffset: -1, extentOffset: -1)); final Offset midBlah1 = textOffsetToPosition(tester, 2); // Right clicking shows the menu. final TestGesture gesture = await tester.startGesture( midBlah1, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); // Copy the first word. await tester.tap(find.text('Copy')); await tester.pumpAndSettle(); expect(controller.text, 'blah1 blah2'); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expectNoCupertinoToolbar(); // Paste it at the end. await gesture.down(textOffsetToPosition(tester, controller.text.length)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream)); expect(find.text('Cut'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsOneWidget); await tester.tap(find.text('Paste')); await tester.pumpAndSettle(); expect(controller.text, 'blah1 blah2blah1'); expect(controller.selection, const TextSelection.collapsed(offset: 16)); // Cut the first word. await gesture.down(midBlah1); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); await tester.tap(find.text('Cut')); await tester.pumpAndSettle(); expect(controller.text, ' blah2blah1'); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 0)); expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('can use the desktop cut/copy/paste buttons on Windows and Linux', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'blah1 blah2', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Initially, the menu is not shown and there is no selection. expectNoCupertinoToolbar(); expect(controller.selection, const TextSelection(baseOffset: -1, extentOffset: -1)); final Offset midBlah1 = textOffsetToPosition(tester, 2); // Right clicking shows the menu. TestGesture gesture = await tester.startGesture( midBlah1, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection.collapsed(offset: 2)); expect(find.text('Cut'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsOneWidget); expect(find.text('Select all'), findsOneWidget); // Double tap to select the first word, then right click to show the menu. final Offset startBlah1 = textOffsetToPosition(tester, 0); gesture = await tester.startGesture( startBlah1, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 100)); await gesture.down(startBlah1); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.text('Cut'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsNothing); expect(find.text('Select all'), findsNothing); gesture = await tester.startGesture( midBlah1, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); // Copy the first word. await tester.tap(find.text('Copy')); await tester.pumpAndSettle(); expect(controller.text, 'blah1 blah2'); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expectNoCupertinoToolbar(); // Paste it at the end. gesture = await tester.startGesture( textOffsetToPosition(tester, controller.text.length), kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await gesture.removePointer(); expect(controller.selection, const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream)); gesture = await tester.startGesture( textOffsetToPosition(tester, controller.text.length), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream)); expect(find.text('Cut'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsOneWidget); await tester.tap(find.text('Paste')); await tester.pumpAndSettle(); expect(controller.text, 'blah1 blah2blah1'); expect(controller.selection, const TextSelection.collapsed(offset: 16)); // Cut the first word. gesture = await tester.startGesture( midBlah1, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 100)); await gesture.down(startBlah1); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.text('Cut'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsNothing); expect(find.text('Select all'), findsNothing); gesture = await tester.startGesture( textOffsetToPosition(tester, controller.text.length), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); await tester.tap(find.text('Cut')); await tester.pumpAndSettle(); expect(controller.text, ' blah2blah1'); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 0)); expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux, TargetPlatform.windows }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Look Up shows up on iOS only', (WidgetTester tester) async { String? lastLookUp; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'LookUp.invoke') { expect(methodCall.arguments, isA<String>()); lastLookUp = methodCall.arguments as String; } return null; }); final TextEditingController controller = _textEditingController( text: 'Test ', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final bool isTargetPlatformiOS = defaultTargetPlatform == TargetPlatform.iOS; // Long press to put the cursor after the "s". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4)); expect(find.text('Look Up'), isTargetPlatformiOS? findsOneWidget : findsNothing); if (isTargetPlatformiOS) { await tester.tap(find.text('Look Up')); expect(lastLookUp, 'Test'); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Search Web shows up on iOS only', (WidgetTester tester) async { String? lastSearch; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'SearchWeb.invoke') { expect(methodCall.arguments, isA<String>()); lastSearch = methodCall.arguments as String; } return null; }); final TextEditingController controller = _textEditingController( text: 'Test ', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final bool isTargetPlatformiOS = defaultTargetPlatform == TargetPlatform.iOS; // Long press to put the cursor after the "s". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4)); expect(find.text('Search Web'), isTargetPlatformiOS? findsOneWidget : findsNothing); if (isTargetPlatformiOS) { await tester.tap(find.text('Search Web')); expect(lastSearch, 'Test'); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Share shows up on iOS and Android', (WidgetTester tester) async { String? lastShare; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'Share.invoke') { expect(methodCall.arguments, isA<String>()); lastShare = methodCall.arguments as String; } return null; }); final TextEditingController controller = _textEditingController( text: 'Test ', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final bool isTargetPlatformiOS = defaultTargetPlatform == TargetPlatform.iOS; // Long press to put the cursor after the "s". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4)); if (isTargetPlatformiOS) { expect(find.text('Share...'), findsOneWidget); await tester.tap(find.text('Share...')); } else { expect(find.text('Share'), findsOneWidget); await tester.tap(find.text('Share')); } expect(lastShare, 'Test'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('uses DefaultSelectionStyle for selection and cursor colors if provided', (WidgetTester tester) async { const Color selectionColor = Colors.orange; const Color cursorColor = Colors.red; await tester.pumpWidget( const MaterialApp( home: Material( child: DefaultSelectionStyle( selectionColor: selectionColor, cursorColor: cursorColor, child: TextField(autofocus: true), ), ), ), ); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.widget.selectionColor, selectionColor); expect(state.widget.cursorColor, cursorColor); }); testWidgets('Use error cursor color when an InputDecoration with an errorText or error widget is provided', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: TextField( autofocus: true, decoration: InputDecoration( error: Text('error'), errorStyle: TextStyle(color: Colors.teal), ), ), ), ), ); await tester.pump(); EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.widget.cursorColor, Colors.teal); await tester.pumpWidget( const MaterialApp( home: Material( child: TextField( autofocus: true, decoration: InputDecoration( errorText: 'error', errorStyle: TextStyle(color: Colors.teal), ), ), ), ), ); await tester.pump(); state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.widget.cursorColor, Colors.teal); }); testWidgets('sets cursorOpacityAnimates on EditableText correctly', (WidgetTester tester) async { // True await tester.pumpWidget( const MaterialApp( home: Material( child: TextField(autofocus: true, cursorOpacityAnimates: true), ), ), ); await tester.pump(); EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.cursorOpacityAnimates, true); // False await tester.pumpWidget( const MaterialApp( home: Material( child: TextField(autofocus: true, cursorOpacityAnimates: false), ), ), ); await tester.pump(); editableText = tester.widget(find.byType(EditableText)); expect(editableText.cursorOpacityAnimates, false); }); testWidgets('Activates the text field when receives semantics focus on desktops', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final FocusNode focusNode = _focusNode(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(focusNode: focusNode), ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( id: 4, flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled], actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.didGainAccessibilityFocus, SemanticsAction.didLoseAccessibilityFocus, ], textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, )); expect(focusNode.hasFocus, isFalse); semanticsOwner.performAction(4, SemanticsAction.didGainAccessibilityFocus); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); semanticsOwner.performAction(4, SemanticsAction.didLoseAccessibilityFocus); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isFalse); semantics.dispose(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.windows, TargetPlatform.linux })); testWidgets('TextField passes onEditingComplete to EditableText', (WidgetTester tester) async { void onEditingComplete() { } await tester.pumpWidget( MaterialApp( home: Material( child: TextField( onEditingComplete: onEditingComplete, ), ), ), ); final Finder editableTextFinder = find.byType(EditableText); expect(editableTextFinder, findsOneWidget); final EditableText editableTextWidget = tester.widget(editableTextFinder); expect(editableTextWidget.onEditingComplete, onEditingComplete); }); testWidgets('TextField has consistent size', (WidgetTester tester) async { final Key textFieldKey = UniqueKey(); String? textFieldValue; await tester.pumpWidget( overlay( child: TextField( key: textFieldKey, decoration: const InputDecoration( hintText: 'Placeholder', ), onChanged: (String value) { textFieldValue = value; }, ), ), ); RenderBox findTextFieldBox() => tester.renderObject(find.byKey(textFieldKey)); final RenderBox inputBox = findTextFieldBox(); final Size emptyInputSize = inputBox.size; Future<void> checkText(String testValue) async { return TestAsyncUtils.guard(() async { expect(textFieldValue, isNull); await tester.enterText(find.byType(TextField), testValue); // Check that the onChanged event handler fired. expect(textFieldValue, equals(testValue)); textFieldValue = null; await skipPastScrollingAnimation(tester); }); } await checkText(' '); expect(findTextFieldBox(), equals(inputBox)); expect(inputBox.size, equals(emptyInputSize)); await checkText('Test'); expect(findTextFieldBox(), equals(inputBox)); expect(inputBox.size, equals(emptyInputSize)); }); testWidgets('Cursor blinks', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const TextField( decoration: InputDecoration( hintText: 'Placeholder', ), ), ), ); await tester.showKeyboard(find.byType(TextField)); final EditableTextState editableText = tester.state(find.byType(EditableText)); // Check that the cursor visibility toggles after each blink interval. Future<void> checkCursorToggle() async { final bool initialShowCursor = editableText.cursorCurrentlyVisible; await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(!initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval ~/ 10); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(!initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); } await checkCursorToggle(); await tester.showKeyboard(find.byType(TextField)); // Try the test again with a nonempty EditableText. tester.testTextInput.updateEditingValue(const TextEditingValue( text: 'X', selection: TextSelection.collapsed(offset: 1), )); await tester.idle(); expect(tester.state(find.byType(EditableText)), editableText); await checkCursorToggle(); }); // Regression test for https://github.com/flutter/flutter/issues/78918. testWidgets('RenderEditable sets correct text editing value', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(text: 'how are you'); final UniqueKey icon = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, decoration: InputDecoration( suffixIcon: IconButton( key: icon, icon: const Icon(Icons.cancel), onPressed: () => controller.clear(), ), ), ), ), ), ); await tester.tap(find.byKey(icon)); await tester.pump(); expect(controller.text, ''); expect(controller.selection, const TextSelection.collapsed(offset: 0)); }); testWidgets('Cursor radius is 2.0', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: TextField(), ), ), ); final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); final RenderEditable renderEditable = editableTextState.renderEditable; expect(renderEditable.cursorRadius, const Radius.circular(2.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('cursor has expected defaults', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const TextField(), ), ); final TextField textField = tester.firstWidget(find.byType(TextField)); expect(textField.cursorWidth, 2.0); expect(textField.cursorHeight, null); expect(textField.cursorRadius, null); }); testWidgets('cursor has expected radius value', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const TextField( cursorRadius: Radius.circular(3.0), ), ), ); final TextField textField = tester.firstWidget(find.byType(TextField)); expect(textField.cursorWidth, 2.0); expect(textField.cursorRadius, const Radius.circular(3.0)); }); testWidgets('clipBehavior has expected defaults', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const TextField(), ), ); final TextField textField = tester.firstWidget(find.byType(TextField)); expect(textField.clipBehavior, Clip.hardEdge); }); testWidgets('Overflow clipBehavior none golden', (WidgetTester tester) async { final OverflowWidgetTextEditingController controller = OverflowWidgetTextEditingController(); addTearDown(controller.dispose); final Widget widget = Theme( data: ThemeData(useMaterial3: false), child: overlay( child: RepaintBoundary( key: const ValueKey<int>(1), child: SizedBox( height: 200, width: 200, child: Center( child: SizedBox( // Make sure the input field is not high enough for the WidgetSpan. height: 50, child: TextField( controller: controller, clipBehavior: Clip.none, ), ), ), ), ), ), ); await tester.pumpWidget(widget); final TextField textField = tester.firstWidget(find.byType(TextField)); expect(textField.clipBehavior, Clip.none); final EditableText editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.clipBehavior, Clip.none); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('overflow_clipbehavior_none.material.0.png'), ); }); testWidgets('Material cursor android golden', (WidgetTester tester) async { final Widget widget = Theme( data: ThemeData(useMaterial3: false), child: overlay( child: const RepaintBoundary( key: ValueKey<int>(1), child: TextField( cursorColor: Colors.blue, cursorWidth: 15, cursorRadius: Radius.circular(3.0), ), ), ), ); await tester.pumpWidget(widget); const String testValue = 'A short phrase'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); await tester.tapAt(textOffsetToPosition(tester, testValue.length)); await tester.pump(); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('text_field_cursor_test.material.0.png'), ); }); testWidgets('Material cursor golden', (WidgetTester tester) async { final Widget widget = Theme( data: ThemeData(useMaterial3: false), child: overlay( child: const RepaintBoundary( key: ValueKey<int>(1), child: TextField( cursorColor: Colors.blue, cursorWidth: 15, cursorRadius: Radius.circular(3.0), ), ), ), ); await tester.pumpWidget(widget); const String testValue = 'A short phrase'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); await tester.tapAt(textOffsetToPosition(tester, testValue.length)); await tester.pump(); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile( 'text_field_cursor_test_${debugDefaultTargetPlatformOverride!.name.toLowerCase()}.material.1.png', ), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('TextInputFormatter gets correct selection value', (WidgetTester tester) async { late TextEditingValue actualOldValue; late TextEditingValue actualNewValue; void callBack(TextEditingValue oldValue, TextEditingValue newValue) { actualOldValue = oldValue; actualNewValue = newValue; } final FocusNode focusNode = _focusNode(); final TextEditingController controller = _textEditingController(text: '123'); await tester.pumpWidget( boilerplate( child: TextField( controller: controller, focusNode: focusNode, inputFormatters: <TextInputFormatter>[TestFormatter(callBack)], ), ), ); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pumpAndSettle(); expect( actualOldValue, const TextEditingValue( text: '123', selection: TextSelection.collapsed(offset: 3, affinity: TextAffinity.upstream), ), ); expect( actualNewValue, const TextEditingValue( text: '12', selection: TextSelection.collapsed(offset: 2), ), ); }, skip: areKeyEventsHandledByPlatform); // [intended] only applies to platforms where we handle key events. testWidgets('text field selection toolbar renders correctly inside opacity', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: const Scaffold( body: Center( child: SizedBox( width: 100, height: 100, child: Opacity( opacity: 0.5, child: TextField( decoration: InputDecoration(hintText: 'Placeholder'), ), ), ), ), ), ), ); await tester.showKeyboard(find.byType(TextField)); const String testValue = 'A B C'; tester.testTextInput.updateEditingValue( const TextEditingValue( text: testValue, ), ); await tester.pump(); // The selectWordsInRange with SelectionChangedCause.tap seems to be needed to show the toolbar. // (This is true even if we provide selection parameter to the TextEditingValue above.) final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); expect(state.showToolbar(), true); // This is needed for the AnimatedOpacity to turn from 0 to 1 so the toolbar is visible. await tester.pumpAndSettle(); await tester.pump(const Duration(seconds: 1)); // Sanity check that the toolbar widget exists. expect(find.text('Paste'), findsOneWidget); await expectLater( // The toolbar exists in the Overlay above the MaterialApp. find.byType(Overlay), matchesGoldenFile('text_field_opacity_test.0.png'), ); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('text field toolbar options correctly changes options', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, toolbarOptions: const ToolbarOptions(copy: true), ), ), ), ), ); // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(textOffsetToPosition(tester, 3)); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 8)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 8), ); await tester.tapAt(textOffsetToPosition(tester, 8)); await tester.pump(); // Second tap selects the word around the cursor. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // Selected text shows 'Copy', and not 'Paste', 'Cut', 'Select All'. expect(find.text('Paste'), findsNothing); expect(find.text('Copy'), findsOneWidget); expect(find.text('Cut'), findsNothing); expect(find.text('Select All'), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('text selection style 1', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure\nhi\nwasssup!', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: RepaintBoundary( child: Container( width: 650.0, height: 600.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: Column( children: <Widget>[ TextField( key: const Key('field0'), controller: controller, style: const TextStyle(height: 4, color: Colors.black45), toolbarOptions: const ToolbarOptions(copy: true, selectAll: true), selectionHeightStyle: ui.BoxHeightStyle.includeLineSpacingTop, selectionWidthStyle: ui.BoxWidthStyle.max, maxLines: 3, ), ], ), ), ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byKey(const Key('field0'))); await tester.longPressAt(textfieldStart + const Offset(50.0, 2.0)); await tester.pumpAndSettle(const Duration(milliseconds: 50)); await tester.tapAt(textfieldStart + const Offset(100.0, 107.0)); await tester.pump(const Duration(milliseconds: 300)); await expectLater( find.byType(MaterialApp), matchesGoldenFile('text_field_golden.TextSelectionStyle.1.png'), ); }); testWidgets('text selection style 2', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure\nhi\nwasssup!', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: RepaintBoundary( child: Container( width: 650.0, height: 600.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: Column( children: <Widget>[ TextField( key: const Key('field0'), controller: controller, style: const TextStyle(height: 4, color: Colors.black45), toolbarOptions: const ToolbarOptions(copy: true, selectAll: true), selectionHeightStyle: ui.BoxHeightStyle.includeLineSpacingBottom, maxLines: 3, ), ], ), ), ), ), ), ), ); final EditableTextState editableTextState = tester.state(find.byType(EditableText)); // Double tap to select the first word. const int index = 4; await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(editableTextState.selectionOverlay!.handlesAreVisible, isTrue); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 7); // Select all text. Use the toolbar if possible. iOS only shows the toolbar // when the selection is collapsed. if (isContextMenuProvidedByPlatform || defaultTargetPlatform == TargetPlatform.iOS) { controller.selection = TextSelection(baseOffset: 0, extentOffset: controller.text.length); expect(controller.selection.extentOffset, controller.text.length); } else { await tester.tap(find.text('Select all')); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, controller.text.length); } await expectLater( find.byType(MaterialApp), matchesGoldenFile('text_field_golden.TextSelectionStyle.2.png'), ); // Text selection styles are not fully supported on web. }, skip: isBrowser); // https://github.com/flutter/flutter/issues/93723 testWidgets( 'text field toolbar options correctly changes options', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, toolbarOptions: const ToolbarOptions(copy: true), ), ), ), ), ); final Offset pos = textOffsetToPosition(tester, 9); // Index of 'P|eel' await tester.tapAt(pos); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(pos); await tester.pump(); // Selected text shows 'Copy', and not 'Paste', 'Cut', 'Select all'. expect(find.text('Paste'), findsNothing); expect(find.text('Copy'), findsOneWidget); expect(find.text('Cut'), findsNothing); expect(find.text('Select all'), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows, }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('cursor layout has correct width', (WidgetTester tester) async { final TextEditingController controller = TextEditingController.fromValue( const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), ); addTearDown(controller.dispose); final FocusNode focusNode = _focusNode(); EditableText.debugDeterministicCursor = true; await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: RepaintBoundary( child: TextField( cursorWidth: 15.0, controller: controller, focusNode: focusNode, ), ), ), ), ); focusNode.requestFocus(); await tester.pump(); await expectLater( find.byType(TextField), matchesGoldenFile('text_field_cursor_width_test.0.png'), ); EditableText.debugDeterministicCursor = false; }); testWidgets('cursor layout has correct radius', (WidgetTester tester) async { final TextEditingController controller = TextEditingController.fromValue( const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), ); addTearDown(controller.dispose); final FocusNode focusNode = _focusNode(); EditableText.debugDeterministicCursor = true; await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: RepaintBoundary( child: TextField( cursorWidth: 15.0, cursorRadius: const Radius.circular(3.0), controller: controller, focusNode: focusNode, ), ), ), ), ); focusNode.requestFocus(); await tester.pump(); await expectLater( find.byType(TextField), matchesGoldenFile('text_field_cursor_width_test.1.png'), ); EditableText.debugDeterministicCursor = false; }); testWidgets('cursor layout has correct height', (WidgetTester tester) async { final TextEditingController controller = TextEditingController.fromValue( const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), ); addTearDown(controller.dispose); final FocusNode focusNode = _focusNode(); EditableText.debugDeterministicCursor = true; await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: RepaintBoundary( child: TextField( cursorWidth: 15.0, cursorHeight: 30.0, controller: controller, focusNode: focusNode, ), ), ), ), ); focusNode.requestFocus(); await tester.pump(); await expectLater( find.byType(TextField), matchesGoldenFile('text_field_cursor_width_test.2.png'), ); EditableText.debugDeterministicCursor = false; }); testWidgets('Overflowing a line with spaces stops the cursor at the end', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: TextField( key: textFieldKey, controller: controller, maxLines: null, ), ), ), ); expect(controller.selection.baseOffset, -1); expect(controller.selection.extentOffset, -1); const String testValueOneLine = 'enough text to be exactly at the end of the line.'; await tester.enterText(find.byType(TextField), testValueOneLine); await skipPastScrollingAnimation(tester); RenderBox findInputBox() => tester.renderObject(find.byKey(textFieldKey)); RenderBox inputBox = findInputBox(); final Size oneLineInputSize = inputBox.size; await tester.tapAt(textOffsetToPosition(tester, testValueOneLine.length)); await tester.pump(); const String testValueTwoLines = 'enough text to overflow the first line and go to the second'; await tester.enterText(find.byType(TextField), testValueTwoLines); await skipPastScrollingAnimation(tester); expect(inputBox, findInputBox()); inputBox = findInputBox(); expect(inputBox.size.height, greaterThan(oneLineInputSize.height)); final Size twoLineInputSize = inputBox.size; // Enter a string with the same number of characters as testValueTwoLines, // but where the overflowing part is all spaces. Assert that it only renders // on one line. const String testValueSpaces = '$testValueOneLine '; expect(testValueSpaces.length, testValueTwoLines.length); await tester.enterText(find.byType(TextField), testValueSpaces); await skipPastScrollingAnimation(tester); expect(inputBox, findInputBox()); inputBox = findInputBox(); expect(inputBox.size.height, oneLineInputSize.height); // Swapping the final space for a letter causes it to wrap to 2 lines. const String testValueSpacesOverflow = '$testValueOneLine a'; expect(testValueSpacesOverflow.length, testValueTwoLines.length); await tester.enterText(find.byType(TextField), testValueSpacesOverflow); await skipPastScrollingAnimation(tester); expect(inputBox, findInputBox()); inputBox = findInputBox(); expect(inputBox.size.height, twoLineInputSize.height); // Positioning the cursor at the end of a line overflowing with spaces puts // it inside the input still. await tester.enterText(find.byType(TextField), testValueSpaces); await skipPastScrollingAnimation(tester); await tester.tapAt(textOffsetToPosition(tester, testValueSpaces.length)); await tester.pump(); final double inputWidth = findRenderEditable(tester).size.width; final Offset cursorOffsetSpaces = findRenderEditable(tester).getLocalRectForCaret( const TextPosition(offset: testValueSpaces.length), ).bottomRight; expect(cursorOffsetSpaces.dx, inputWidth - kCaretGap); }); testWidgets('Overflowing a line with spaces stops the cursor at the end (rtl direction)', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const TextField( textDirection: TextDirection.rtl, maxLines: null, ), ), ); const String testValueOneLine = 'enough text to be exactly at the end of the line.'; const String testValueSpaces = '$testValueOneLine '; // Positioning the cursor at the end of a line overflowing with spaces puts // it inside the input still. await tester.enterText(find.byType(TextField), testValueSpaces); await skipPastScrollingAnimation(tester); await tester.tapAt(textOffsetToPosition(tester, testValueSpaces.length)); await tester.pump(); final Offset cursorOffsetSpaces = findRenderEditable(tester).getLocalRectForCaret( const TextPosition(offset: testValueSpaces.length), ).topLeft; expect(cursorOffsetSpaces.dx >= 0, isTrue); }); testWidgets('mobile obscureText control test', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const TextField( obscureText: true, decoration: InputDecoration( hintText: 'Placeholder', ), ), ), ); await tester.showKeyboard(find.byType(TextField)); const String testValue = 'ABC'; tester.testTextInput.updateEditingValue(const TextEditingValue( text: testValue, selection: TextSelection.collapsed(offset: testValue.length), )); await tester.pump(); // Enter a character into the obscured field and verify that the character // is temporarily shown to the user and then changed to a bullet. const String newChar = 'X'; tester.testTextInput.updateEditingValue(const TextEditingValue( text: testValue + newChar, selection: TextSelection.collapsed(offset: testValue.length + 1), )); await tester.pump(); String editText = (findRenderEditable(tester).text! as TextSpan).text!; expect(editText.substring(editText.length - 1), newChar); await tester.pump(const Duration(seconds: 2)); editText = (findRenderEditable(tester).text! as TextSpan).text!; expect(editText.substring(editText.length - 1), '\u2022'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android })); testWidgets('desktop obscureText control test', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const TextField( obscureText: true, decoration: InputDecoration( hintText: 'Placeholder', ), ), ), ); await tester.showKeyboard(find.byType(TextField)); const String testValue = 'ABC'; tester.testTextInput.updateEditingValue(const TextEditingValue( text: testValue, selection: TextSelection.collapsed(offset: testValue.length), )); await tester.pump(); // Enter a character into the obscured field and verify that the character // isn't shown to the user. const String newChar = 'X'; tester.testTextInput.updateEditingValue(const TextEditingValue( text: testValue + newChar, selection: TextSelection.collapsed(offset: testValue.length + 1), )); await tester.pump(); final String editText = (findRenderEditable(tester).text! as TextSpan).text!; expect(editText.substring(editText.length - 1), '\u2022'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.linux, TargetPlatform.windows, })); testWidgets('Caret position is updated on tap', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); expect(controller.selection.baseOffset, -1); expect(controller.selection.extentOffset, -1); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Tap to reposition the caret. final int tapIndex = testValue.indexOf('e'); final Offset ePos = textOffsetToPosition(tester, tapIndex); await tester.tapAt(ePos); await tester.pump(); expect(controller.selection.baseOffset, tapIndex); expect(controller.selection.extentOffset, tapIndex); }); testWidgets('enableInteractiveSelection = false, tap', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, enableInteractiveSelection: false, ), ), ); expect(controller.selection.baseOffset, -1); expect(controller.selection.extentOffset, -1); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Tap would ordinarily reposition the caret. final int tapIndex = testValue.indexOf('e'); final Offset ePos = textOffsetToPosition(tester, tapIndex); await tester.tapAt(ePos); await tester.pump(); expect(controller.selection.baseOffset, testValue.length); expect(controller.selection.isCollapsed, isTrue); }); testWidgets('Can long press to select', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); expect(controller.value.text, testValue); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); await tester.longPressAt(ePos, pointer: 7); await tester.pumpAndSettle(); // 'def' is selected. expect(controller.selection.baseOffset, testValue.indexOf('d')); expect(controller.selection.extentOffset, testValue.indexOf('f')+1); // Tapping elsewhere immediately collapses and moves the cursor. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('h'))); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('h')); }); testWidgets("Slight movements in longpress don't hide/show handles", (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); expect(controller.value.text, testValue); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); // Long press the 'e' to select 'def', but don't release the gesture. final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await tester.pumpAndSettle(); // Handles are shown final Finder fadeFinder = find.byType(FadeTransition); expect(fadeFinder, findsNWidgets(2)); // 2 handles, 1 toolbar FadeTransition handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(1.0)); // Move the gesture very slightly await gesture.moveBy(const Offset(1.0, 1.0)); await tester.pump(SelectionOverlay.fadeDuration * 0.5); handle = tester.widget(fadeFinder.at(0)); // The handle should still be fully opaque. expect(handle.opacity.value, equals(1.0)); }); testWidgets('Long pressing a field with selection 0,0 shows the selection menu', (WidgetTester tester) async { late final TextEditingController controller; addTearDown(() => controller.dispose()); await tester.pumpWidget(overlay( child: TextField( controller: controller = TextEditingController.fromValue( const TextEditingValue( selection: TextSelection(baseOffset: 0, extentOffset: 0), ), ), ), )); expect(find.text('Paste'), findsNothing); final Offset emptyPos = textOffsetToPosition(tester, 0); await tester.longPressAt(emptyPos, pointer: 7); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('Entering text hides selection handle caret', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); const String testValue = 'abcdefghi'; await tester.enterText(find.byType(TextField), testValue); expect(controller.value.text, testValue); await skipPastScrollingAnimation(tester); // Handle not shown. expect(controller.selection.isCollapsed, true); final Finder fadeFinder = find.byType(FadeTransition); FadeTransition handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(0.0)); // Tap on the text field to show the handle. await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(fadeFinder, findsNWidgets(1)); handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(1.0)); // Enter more text. const String testValueAddition = 'jklmni'; await tester.enterText(find.byType(TextField), testValueAddition); expect(controller.value.text, testValueAddition); await skipPastScrollingAnimation(tester); // Handle not shown. expect(controller.selection.isCollapsed, true); handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(0.0)); }); testWidgets('selection handles are excluded from the semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); const String testValue = 'abcdefghi'; await tester.enterText(find.byType(TextField), testValue); expect(controller.value.text, testValue); await skipPastScrollingAnimation(tester); // Tap on the text field to show the handle. await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); // The semantics should only have the text field. expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.setSelection, SemanticsAction.paste, SemanticsAction.setText, SemanticsAction.moveCursorBackwardByWord, ], value: 'abcdefghi', textDirection: TextDirection.ltr, textSelection: const TextSelection.collapsed(offset: 9), ), ], ), ignoreRect: true, ignoreTransform: true, )); semantics.dispose(); }); testWidgets('Mouse long press is just like a tap', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); expect(controller.value.text, testValue); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); // Long press the 'e' using a mouse device. final int eIndex = testValue.indexOf('e'); final Offset ePos = textOffsetToPosition(tester, eIndex); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); // The cursor is placed just like a regular tap. expect(controller.selection.baseOffset, eIndex); expect(controller.selection.extentOffset, eIndex); }); testWidgets('Read only text field basic', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(text: 'readonly'); await tester.pumpWidget( overlay( child: TextField( controller: controller, readOnly: true, ), ), ); // Read only text field cannot open keyboard. await tester.showKeyboard(find.byType(TextField)); // On web, we always create a client connection to the engine. expect(tester.testTextInput.hasAnyClients, isBrowser ? isTrue : isFalse); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); await tester.tap(find.byType(TextField)); await tester.pump(); // On web, we always create a client connection to the engine. expect(tester.testTextInput.hasAnyClients, isBrowser ? isTrue : isFalse); final EditableTextState editableText = tester.state(find.byType(EditableText)); // Collapse selection should not paint. expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); // Long press on the 'd' character of text 'readOnly' to show context menu. const int dIndex = 3; final Offset dPos = textOffsetToPosition(tester, dIndex); await tester.longPressAt(dPos); await tester.pumpAndSettle(); // Context menu should not have paste and cut. expect(find.text('Copy'), isContextMenuProvidedByPlatform ? findsNothing : findsOneWidget); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); }); testWidgets('does not paint toolbar when no options available', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: TextField( readOnly: true, ), ), ), ); await tester.tap(find.byType(TextField)); await tester.pump(const Duration(milliseconds: 50)); await tester.tap(find.byType(TextField)); // Wait for context menu to be built. await tester.pumpAndSettle(); expect(find.byType(CupertinoTextSelectionToolbar), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('text field build empty toolbar when no options available', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: TextField( readOnly: true, ), ), ), ); await tester.tap(find.byType(TextField)); await tester.pump(const Duration(milliseconds: 50)); await tester.tap(find.byType(TextField)); // Wait for context menu to be built. await tester.pumpAndSettle(); final RenderBox container = tester.renderObject(find.descendant( of: find.byType(SnapshotWidget), matching: find.byType(SizedBox), ).first); expect(container.size, Size.zero); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows })); testWidgets('Swapping controllers should update selection', (WidgetTester tester) async { TextEditingController controller = _textEditingController(text: 'readonly'); final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) { return Center( child: Material( child: TextField( controller: controller, readOnly: true, ), ), ); }, ); addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget(overlayWithEntry(entry)); const int dIndex = 3; final Offset dPos = textOffsetToPosition(tester, dIndex); await tester.longPressAt(dPos); await tester.pumpAndSettle(); final EditableTextState state = tester.state(find.byType(EditableText)); TextSelection currentOverlaySelection = state.selectionOverlay!.value.selection; expect(currentOverlaySelection.baseOffset, 0); expect(currentOverlaySelection.extentOffset, 8); // Update selection from [0 to 8] to [1 to 7]. controller = TextEditingController.fromValue( controller.value.copyWith(selection: const TextSelection( baseOffset: 1, extentOffset: 7, )), ); addTearDown(controller.dispose); // Mark entry to be dirty in order to trigger overlay update. entry.markNeedsBuild(); await tester.pump(); currentOverlaySelection = state.selectionOverlay!.value.selection; expect(currentOverlaySelection.baseOffset, 1); expect(currentOverlaySelection.extentOffset, 7); }); testWidgets('Read only text should not compose', (WidgetTester tester) async { final TextEditingController controller = TextEditingController.fromValue( const TextEditingValue( text: 'readonly', composing: TextRange(start: 0, end: 8), // Simulate text composing. ), ); addTearDown(controller.dispose); await tester.pumpWidget( overlay( child: TextField( controller: controller, readOnly: true, ), ), ); final RenderEditable renderEditable = findRenderEditable(tester); // There should be no composing. expect(renderEditable.text, TextSpan(text:'readonly', style: renderEditable.text!.style)); }); testWidgets('Dynamically switching between read only and not read only should hide or show collapse cursor', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(text: 'readonly'); bool readOnly = true; final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) { return Center( child: Material( child: TextField( controller: controller, readOnly: readOnly, ), ), ); }, ); addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget(overlayWithEntry(entry)); await tester.tap(find.byType(TextField)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); // Collapse selection should not paint. expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); readOnly = false; // Mark entry to be dirty in order to trigger overlay update. entry.markNeedsBuild(); await tester.pumpAndSettle(); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); readOnly = true; entry.markNeedsBuild(); await tester.pumpAndSettle(); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); }); testWidgets('Dynamically switching to read only should close input connection', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(text: 'readonly'); bool readOnly = false; final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) { return Center( child: Material( child: TextField( controller: controller, readOnly: readOnly, ), ), ); }, ); addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget(overlayWithEntry(entry)); await tester.tap(find.byType(TextField)); await tester.pump(); expect(tester.testTextInput.hasAnyClients, true); readOnly = true; // Mark entry to be dirty in order to trigger overlay update. entry.markNeedsBuild(); await tester.pump(); // On web, we always have a client connection to the engine. expect(tester.testTextInput.hasAnyClients, isBrowser ? isTrue : isFalse); }); testWidgets('Dynamically switching to non read only should open input connection', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(text: 'readonly'); bool readOnly = true; final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) { return Center( child: Material( child: TextField( controller: controller, readOnly: readOnly, ), ), ); }, ); addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget(overlayWithEntry(entry)); await tester.tap(find.byType(TextField)); await tester.pump(); // On web, we always have a client connection to the engine. expect(tester.testTextInput.hasAnyClients, isBrowser ? isTrue : isFalse); readOnly = false; // Mark entry to be dirty in order to trigger overlay update. entry.markNeedsBuild(); await tester.pump(); expect(tester.testTextInput.hasAnyClients, true); }); testWidgets('enableInteractiveSelection = false, long-press', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, enableInteractiveSelection: false, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); expect(controller.value.text, testValue); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); await tester.longPressAt(ePos, pointer: 7); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.length); }); testWidgets('Selection updates on tap down (Desktop platforms)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, 5); final Offset gPos = textOffsetToPosition(tester, 8); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 5); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); await gesture.down(gPos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); // This should do nothing. The selection is set on tap down on desktop platforms. await gesture.up(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); }, variant: TargetPlatformVariant.desktop(), ); testWidgets('Selection updates on tap up (Mobile platforms)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); final bool isTargetPlatformApple = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, 5); final Offset gPos = textOffsetToPosition(tester, 8); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); await gesture.down(gPos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 5); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); final TestGesture touchGesture = await tester.startGesture(ePos); await touchGesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); // On iOS a tap to select, selects the word edge instead of the exact tap position. expect(controller.selection.baseOffset, isTargetPlatformApple ? 7 : 5); expect(controller.selection.extentOffset, isTargetPlatformApple ? 7 : 5); // Selection should stay the same since it is set on tap up for mobile platforms. await touchGesture.down(gPos); await tester.pump(); expect(controller.selection.baseOffset, isTargetPlatformApple ? 7 : 5); expect(controller.selection.extentOffset, isTargetPlatformApple ? 7 : 5); await touchGesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); }, variant: TargetPlatformVariant.mobile(), ); testWidgets('Can select text with a mouse when wrapped in a GestureDetector with tap/double tap callbacks', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/129161. final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: GestureDetector( onTap: () {}, onDoubleTap: () {}, child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.up(); // This is to allow the GestureArena to decide a winner between TapGestureRecognizer, // DoubleTapGestureRecognizer, and BaseTapAndDragGestureRecognizer. await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); await gesture.down(ePos); await tester.pump(); await gesture.moveTo(gPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, testValue.indexOf('e')); expect(controller.selection.extentOffset, testValue.indexOf('g')); }, variant: TargetPlatformVariant.desktop()); testWidgets('Can select text by dragging with a mouse', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.moveTo(gPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, testValue.indexOf('e')); expect(controller.selection.extentOffset, testValue.indexOf('g')); }); testWidgets('Can move cursor when dragging, when tap is on collapsed selection (iOS)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset iPos = textOffsetToPosition(tester, testValue.indexOf('i')); // Tap on text field to gain focus, and set selection to '|g'. On iOS // the selection is set to the word edge closest to the tap position. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(ePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 7); // If the position we tap during a drag start is on the collapsed selection, then // we can move the cursor with a drag. // Here we tap on '|g', where our selection was previously, and move to '|i'. await gesture.down(textOffsetToPosition(tester, 7)); await tester.pump(); await gesture.moveTo(iPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('i')); // End gesture and skip the magnifier hide animation, so it can release // resources. await gesture.up(); await tester.pumpAndSettle(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Cursor should not move on a quick touch drag when touch does not begin on previous selection (iOS)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); final Offset iPos = textOffsetToPosition(tester, testValue.indexOf('i')); // Tap on text field to gain focus, and set selection to '|a'. On iOS // the selection is set to the word edge closest to the tap position. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(aPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); // The position we tap during a drag start is not on the collapsed selection, // so the cursor should not move. await gesture.down(textOffsetToPosition(tester, 7)); await gesture.moveTo(iPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Can move cursor when dragging, when tap is on collapsed selection (iOS) - multiline', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); const String testValue = 'abc\ndef\nghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); final Offset iPos = textOffsetToPosition(tester, testValue.indexOf('i')); // Tap on text field to gain focus, and set selection to '|a'. On iOS // the selection is set to the word edge closest to the tap position. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(aPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); // If the position we tap during a drag start is on the collapsed selection, then // we can move the cursor with a drag. // Here we tap on '|a', where our selection was previously, and move to '|i'. await gesture.down(aPos); await tester.pump(); await gesture.moveTo(iPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('i')); // End gesture and skip the magnifier hide animation, so it can release // resources. await gesture.up(); await tester.pumpAndSettle(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Can move cursor when dragging, when tap is on collapsed selection (iOS) - ListView', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/122519 final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: ListView( children: <Widget>[ TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ], ), ), ), ); const String testValue = 'abc\ndef\nghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); final Offset iPos = textOffsetToPosition(tester, testValue.indexOf('i')); // Tap on text field to gain focus, and set selection to '|a'. On iOS // the selection is set to the word edge closest to the tap position. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(aPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); // If the position we tap during a drag start is on the collapsed selection, then // we can move the cursor with a drag. // Here we tap on '|a', where our selection was previously, and attempt move // to '|g'. The cursor will not move because the `VerticalDragGestureRecognizer` // in the scrollable will beat the `TapAndHorizontalDragGestureRecognizer` // in the TextField. This is because moving from `|a` to `|g` is a completely // vertical movement. await gesture.down(aPos); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); // Release the pointer. await gesture.up(); await tester.pumpAndSettle(); // If the position we tap during a drag start is on the collapsed selection, then // we can move the cursor with a drag. // Here we tap on '|a', where our selection was previously, and move to '|i'. // Unlike our previous attempt to drag to `|g`, this works because moving // to `|i` includes a horizontal movement so the `TapAndHorizontalDragGestureRecognizer` // in TextField can beat the `VerticalDragGestureRecognizer` in the scrollable. await gesture.down(aPos); await tester.pump(); await gesture.moveTo(iPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('i')); // End gesture and skip the magnifier hide animation, so it can release // resources. await gesture.up(); await tester.pumpAndSettle(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Can move cursor when dragging (Android)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); // Tap on text field to gain focus, and set selection to '|e'. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(ePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); // Here we tap on '|d', and move to '|g'. await gesture.down(textOffsetToPosition(tester, testValue.indexOf('d'))); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('g')); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia }), ); testWidgets('Can move cursor when dragging (Android) - multiline', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); const String testValue = 'abc\ndef\nghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); // Tap on text field to gain focus, and set selection to '|a'. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(aPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('a')); // Here we tap on '|c', and move down to '|g'. await gesture.down(textOffsetToPosition(tester, testValue.indexOf('c'))); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('g')); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia }), ); testWidgets('Can move cursor when dragging (Android) - ListView', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/122519 final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: ListView( children: <Widget>[ TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ], ), ), ), ); const String testValue = 'abc\ndef\nghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); final Offset cPos = textOffsetToPosition(tester, testValue.indexOf('c')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); // Tap on text field to gain focus, and set selection to '|c'. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(cPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('c')); // Here we tap on '|a', and attempt move to '|g'. The cursor will not move // because the `VerticalDragGestureRecognizer` in the scrollable will beat // the `TapAndHorizontalDragGestureRecognizer` in the TextField. This is // because moving from `|a` to `|g` is a completely vertical movement. await gesture.down(aPos); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('c')); // Release the pointer. await gesture.up(); await tester.pumpAndSettle(); // Here we tap on '|c', and move to '|g'. Unlike our previous attempt to // drag to `|g`, this works because moving from `|c` to `|g` includes a // horizontal movement so the `TapAndHorizontalDragGestureRecognizer` // in TextField can beat the `VerticalDragGestureRecognizer` in the scrollable. await gesture.down(cPos); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('g')); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia }), ); testWidgets('Continuous dragging does not cause flickering', (WidgetTester tester) async { int selectionChangedCount = 0; const String testValue = 'abc def ghi'; final TextEditingController controller = _textEditingController(text: testValue); controller.addListener(() { selectionChangedCount++; }); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, style: const TextStyle(fontSize: 10.0), ), ), ), ); final Offset cPos = textOffsetToPosition(tester, 2); // Index of 'c'. final Offset gPos = textOffsetToPosition(tester, 8); // Index of 'g'. final Offset hPos = textOffsetToPosition(tester, 9); // Index of 'h'. // Drag from 'c' to 'g'. final TestGesture gesture = await tester.startGesture(cPos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(selectionChangedCount, isNonZero); selectionChangedCount = 0; expect(controller.selection.baseOffset, 2); expect(controller.selection.extentOffset, 8); // Tiny movement shouldn't cause text selection to change. await gesture.moveTo(gPos + const Offset(2.0, 0.0)); await tester.pumpAndSettle(); expect(selectionChangedCount, 0); // Now a text selection change will occur after a significant movement. await gesture.moveTo(hPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(selectionChangedCount, 1); expect(controller.selection.baseOffset, 2); expect(controller.selection.extentOffset, 9); }); testWidgets('Dragging in opposite direction also works', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); final TestGesture gesture = await tester.startGesture(gPos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.moveTo(ePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, testValue.indexOf('g')); expect(controller.selection.extentOffset, testValue.indexOf('e')); }); testWidgets('Slow mouse dragging also selects text', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(const Duration(seconds: 2)); await gesture.moveTo(gPos); await tester.pump(); await gesture.up(); expect(controller.selection.baseOffset, testValue.indexOf('e')); expect(controller.selection.extentOffset, testValue.indexOf('g')); }); testWidgets('Can drag handles to change selection on Apple platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Double tap the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); // The first tap. TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero // The second tap. await gesture.down(ePos); await tester.pump(); await gesture.up(); await tester.pump(); final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); expect(selection.extentOffset, 7); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle 2 letters to the right. // We use a small offset because the endpoint is on the very corner // of the handle. Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); Offset newHandlePos = textOffsetToPosition(tester, testValue.length); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 11); // Drag the left handle 2 letters to the left. handlePos = endpoints[0].point + const Offset(-1.0, 1.0); newHandlePos = textOffsetToPosition(tester, 2); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); switch (defaultTargetPlatform) { // On Apple platforms, dragging the base handle makes it the extent. case TargetPlatform.iOS: case TargetPlatform.macOS: expect(controller.selection.baseOffset, 11); expect(controller.selection.extentOffset, 2); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, 2); expect(controller.selection.extentOffset, 11); } // Drag the left handle 2 letters to the left again. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + const Offset(-1.0, 1.0); newHandlePos = textOffsetToPosition(tester, 0); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: // The left handle was already the extent, and it remains so. expect(controller.selection.baseOffset, 11); expect(controller.selection.extentOffset, 0); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 11); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('Can drag handles to change selection on non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); expect(selection.extentOffset, 7); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle 2 letters to the right. // We use a small offset because the endpoint is on the very corner // of the handle. Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); Offset newHandlePos = textOffsetToPosition(tester, testValue.length); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 11); // Drag the left handle 2 letters to the left. handlePos = endpoints[0].point + const Offset(-1.0, 1.0); newHandlePos = textOffsetToPosition(tester, 2); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); switch (defaultTargetPlatform) { // On Apple platforms, dragging the base handle makes it the extent. case TargetPlatform.iOS: case TargetPlatform.macOS: expect(controller.selection.baseOffset, 11); expect(controller.selection.extentOffset, 2); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, 2); expect(controller.selection.extentOffset, 11); } // Drag the left handle 2 letters to the left again. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + const Offset(-1.0, 1.0); newHandlePos = textOffsetToPosition(tester, 0); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: // The left handle was already the extent, and it remains so. expect(controller.selection.baseOffset, 11); expect(controller.selection.extentOffset, 0); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 11); } }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'Can drag the left handle while the right handle remains off-screen', (WidgetTester tester) async { // Text is longer than textfield width. const String testValue = 'aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb'; final TextEditingController controller = _textEditingController(text: testValue); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, scrollController: scrollController, ), ), ), ), ); // Double tap 'b' to show handles. final Offset bPos = textOffsetToPosition(tester, testValue.indexOf('b')); await tester.tapAt(bPos); await tester.pump(kDoubleTapTimeout ~/ 2); await tester.tapAt(bPos); await tester.pumpAndSettle(); final TextSelection selection = controller.selection; expect(selection.baseOffset, 28); expect(selection.extentOffset, testValue.length); // Move to the left edge. scrollController.jumpTo(0); await tester.pumpAndSettle(); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Left handle should appear between textfield's left and right position. final Offset textFieldLeftPosition = tester.getTopLeft(find.byType(TextField)); expect(endpoints[0].point.dx - textFieldLeftPosition.dx, isPositive); final Offset textFieldRightPosition = tester.getTopRight(find.byType(TextField)); expect(textFieldRightPosition.dx - endpoints[0].point.dx, isPositive); // Right handle should remain off-screen. expect(endpoints[1].point.dx - textFieldRightPosition.dx, isPositive); // Drag the left handle to the right by 25 offset. const int toOffset = 25; final double beforeScrollOffset = scrollController.offset; final Offset handlePos = endpoints[0].point + const Offset(-1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, toOffset); final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: // On Apple platforms, dragging the base handle makes it the extent. expect(controller.selection.baseOffset, testValue.length); expect(controller.selection.extentOffset, toOffset); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, toOffset); expect(controller.selection.extentOffset, testValue.length); } // The scroll area of text field should not move. expect(scrollController.offset, beforeScrollOffset); }, ); testWidgets( 'Can drag the right handle while the left handle remains off-screen', (WidgetTester tester) async { // Text is longer than textfield width. const String testValue = 'aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb'; final TextEditingController controller = _textEditingController(text: testValue); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, scrollController: scrollController, ), ), ), ), ); // Double tap 'a' to show handles. final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); await tester.tapAt(aPos); await tester.pump(kDoubleTapTimeout ~/ 2); await tester.tapAt(aPos); await tester.pumpAndSettle(); final TextSelection selection = controller.selection; expect(selection.baseOffset, 0); expect(selection.extentOffset, 27); // Move to the right edge. scrollController.jumpTo(800); await tester.pumpAndSettle(); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Right handle should appear between textfield's left and right position. final Offset textFieldLeftPosition = tester.getTopLeft(find.byType(TextField)); expect(endpoints[1].point.dx - textFieldLeftPosition.dx, isPositive); final Offset textFieldRightPosition = tester.getTopRight(find.byType(TextField)); expect(textFieldRightPosition.dx - endpoints[1].point.dx, isPositive); // Left handle should remain off-screen. expect(endpoints[0].point.dx, isNegative); // Drag the right handle to the left by 50 offset. const int toOffset = 50; final double beforeScrollOffset = scrollController.offset; final Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, toOffset); final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, toOffset); // The scroll area of text field should not move. expect(scrollController.offset, beforeScrollOffset); }, ); testWidgets('Drag handles trigger feedback', (WidgetTester tester) async { final FeedbackTester feedback = FeedbackTester(); addTearDown(feedback.dispose); final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); expect(feedback.hapticCount, 0); await skipPastScrollingAnimation(tester); // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); expect(selection.extentOffset, 7); expect(feedback.hapticCount, 1); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle 2 letters to the right. // Use a small offset because the endpoint is on the very corner // of the handle. final Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, testValue.length); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 11); expect(feedback.hapticCount, 2); }); testWidgets('Dragging a collapsed handle should trigger feedback.', (WidgetTester tester) async { final FeedbackTester feedback = FeedbackTester(); addTearDown(feedback.dispose); final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); expect(feedback.hapticCount, 0); await skipPastScrollingAnimation(tester); // Tap the 'e' to bring up a collapsed handle. final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 5); expect(selection.extentOffset, 5); expect(feedback.hapticCount, 0); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 1); // Drag the right handle 3 letters to the right. // Use a small offset because the endpoint is on the very corner // of the handle. final Offset handlePos = endpoints[0].point + const Offset(1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, testValue.indexOf('g')); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); expect(feedback.hapticCount, 1); }); testWidgets('Cannot drag one handle past the other', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, 5); // Position before 'e'. TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); expect(selection.extentOffset, 7); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle until there's only 1 char selected. // We use a small offset because the endpoint is on the very corner // of the handle. final Offset handlePos = endpoints[1].point + const Offset(4.0, 0.0); Offset newHandlePos = textOffsetToPosition(tester, 5); // Position before 'e'. gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 5); newHandlePos = textOffsetToPosition(tester, 2); // Position before 'c'. await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); // The selection doesn't move beyond the left handle. There's always at // least 1 char selected. expect(controller.selection.extentOffset, 5); }); testWidgets('Dragging between multiple lines keeps the contact point at the same place on the handle on Android', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( // 11 first line, 19 second line, 17 third line = length 49 text: 'a big house\njumped over a mouse\nOne more line yay', ); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: 3, minLines: 3, ), ), ); // Double tap to select 'over'. final Offset pos = textOffsetToPosition(tester, controller.text.indexOf('v')); // The first tap. TestGesture gesture = await tester.startGesture(pos, pointer: 7); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero // The second tap. await gesture.down(pos); await tester.pump(); await gesture.up(); await tester.pump(); final TextSelection selection = controller.selection; expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 23, ), ); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle 4 letters to the right. // The adjustment moves the tap from the text position to the handle. const Offset endHandleAdjustment = Offset(1.0, 6.0); Offset handlePos = endpoints[1].point + endHandleAdjustment; Offset newHandlePos = textOffsetToPosition(tester, 27) + endHandleAdjustment; await tester.pump(); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 27, ), ); // Drag the right handle 1 line down. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[1].point + endHandleAdjustment; final Offset toNextLine = Offset( 0.0, findRenderEditable(tester).preferredLineHeight + 3.0, ); newHandlePos = handlePos + toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 47, ), ); // Drag the right handle back up 1 line. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[1].point + endHandleAdjustment; newHandlePos = handlePos - toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 27, ), ); // Drag the left handle 4 letters to the left. // The adjustment moves the tap from the text position to the handle. const Offset startHandleAdjustment = Offset(-1.0, 6.0); endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = textOffsetToPosition(tester, 15) + startHandleAdjustment; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 15, extentOffset: 27, ), ); // Drag the left handle 1 line up. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = handlePos - toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 3, extentOffset: 27, ), ); // Drag the left handle 1 line back down. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = handlePos + toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 15, extentOffset: 27, ), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), ); testWidgets('Dragging between multiple lines keeps the contact point at the same place on the handle on iOS', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( // 11 first line, 19 second line, 17 third line = length 49 text: 'a big house\njumped over a mouse\nOne more line yay', ); await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: 3, minLines: 3, ), ), ), ); // Double tap to select 'over'. final Offset pos = textOffsetToPosition(tester, controller.text.indexOf('v')); // The first tap. TestGesture gesture = await tester.startGesture(pos, pointer: 7); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero // The second tap. await gesture.down(pos); await tester.pump(); await gesture.up(); await tester.pump(); final TextSelection selection = controller.selection; expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 23, ), ); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle 4 letters to the right. // The adjustment moves the tap from the text position to the handle. const Offset endHandleAdjustment = Offset(1.0, 6.0); Offset handlePos = endpoints[1].point + endHandleAdjustment; Offset newHandlePos = textOffsetToPosition(tester, 27) + endHandleAdjustment; await tester.pump(); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 27, ), ); // Drag the right handle 1 line down. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[1].point + endHandleAdjustment; final double lineHeight = findRenderEditable(tester).preferredLineHeight; final Offset toNextLine = Offset(0.0, lineHeight + 3.0); newHandlePos = handlePos + toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 47, ), ); // Drag the right handle back up 1 line. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[1].point + endHandleAdjustment; newHandlePos = handlePos - toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 27, ), ); // Drag the left handle 4 letters to the left. // The adjustment moves the tap from the text position to the handle. final Offset startHandleAdjustment = Offset(-1.0, -lineHeight + 6.0); endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = textOffsetToPosition(tester, 15) + startHandleAdjustment; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); // On Apple platforms, dragging the base handle makes it the extent. expect( controller.selection, const TextSelection( baseOffset: 27, extentOffset: 15, ), ); // Drag the left handle 1 line up. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; // Move handle a sufficient global distance so it can be considered a drag // by the selection handle's [PanGestureRecognizer]. newHandlePos = handlePos - (toNextLine * 2); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 27, extentOffset: 3, ), ); // Drag the left handle 1 line back down. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = handlePos + toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); // Move handle up a small amount before dragging it down so the total global // distance travelled can be accepted by the selection handle's [PanGestureRecognizer] as a drag. // This way it can declare itself the winner before the [TapAndDragGestureRecognizer] that // is on the selection overlay. await gesture.moveTo(handlePos - toNextLine); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 27, extentOffset: 15, ), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets("dragging caret within a word doesn't affect composing region", (WidgetTester tester) async { const String testValue = 'abc def ghi'; final TextEditingController controller = TextEditingController.fromValue( const TextEditingValue( text: testValue, selection: TextSelection( baseOffset: 4, extentOffset: 4, affinity: TextAffinity.upstream, ), composing: TextRange( start: 4, end: 7, ), ), ); addTearDown(controller.dispose); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 4); expect(controller.value.composing.start, 4); expect(controller.value.composing.end, 7); // Tap the caret to show the handle. final Offset ePos = textOffsetToPosition(tester, 4); await tester.tapAt(ePos); await tester.pumpAndSettle(); final TextSelection selection = controller.selection; expect(controller.selection.isCollapsed, true); expect(selection.baseOffset, 4); expect(controller.value.composing.start, 4); expect(controller.value.composing.end, 7); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 1); // Drag the right handle 2 letters to the right. // We use a small offset because the endpoint is on the very corner // of the handle. final Offset handlePos = endpoints[0].point + const Offset(1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, 7); final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 7); expect(controller.value.composing.start, 4); expect(controller.value.composing.end, 7); }, skip: kIsWeb, // [intended] text selection is handled by the browser variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }) ); testWidgets('Can use selection toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); // Tapping on the part of the handle's GestureDetector where it overlaps // with the text itself does not show the menu, so add a small vertical // offset to tap below the text. await tester.tapAt(endpoints[0].point + const Offset(1.0, 13.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero // Select all should select all the text. await tester.tap(find.text('Select all')); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, testValue.length); // Copy should reset the selection. await tester.tap(find.text('Copy')); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); // Tap again to bring back the menu. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(); // Allow time for handle to appear and double tap to time out. await tester.pump(const Duration(milliseconds: 300)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); expect(controller.selection.extentOffset, testValue.indexOf('e')); renderEditable = findRenderEditable(tester); endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); await tester.tapAt(endpoints[0].point + const Offset(1.0, 1.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); expect(controller.selection.extentOffset, testValue.indexOf('e')); // Paste right before the 'e'. await tester.tap(find.text('Paste')); await tester.pump(); expect(controller.text, 'abc d${testValue}ef ghi'); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. // Show the selection menu at the given index into the text by tapping to // place the cursor and then tapping on the handle. Future<void> showSelectionMenuAt(WidgetTester tester, TextEditingController controller, int index) async { await tester.tapAt(tester.getCenter(find.byType(EditableText))); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero expect(find.text('Select all'), findsNothing); // Tap the selection handle to bring up the "paste / select all" menu for // the last line of text. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); // Tapping on the part of the handle's GestureDetector where it overlaps // with the text itself does not show the menu, so add a small vertical // offset to tap below the text. await tester.tapAt(endpoints[0].point + const Offset(1.0, 13.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero } testWidgets( 'Check the toolbar appears below the TextField when there is not enough space above the TextField to show it', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/29808 final TextEditingController controller = _textEditingController(); await tester.pumpWidget(MaterialApp( home: Scaffold( body: Padding( padding: const EdgeInsets.all(30.0), child: TextField( controller: controller, ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); await showSelectionMenuAt(tester, controller, testValue.indexOf('e')); // Verify the selection toolbar position is below the text. Offset toolbarTopLeft = tester.getTopLeft(find.text('Select all')); Offset textFieldTopLeft = tester.getTopLeft(find.byType(TextField)); expect(textFieldTopLeft.dy, lessThan(toolbarTopLeft.dy)); await tester.pumpWidget(MaterialApp( home: Scaffold( body: Padding( padding: const EdgeInsets.all(150.0), child: TextField( controller: controller, ), ), ), )); await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); await showSelectionMenuAt(tester, controller, testValue.indexOf('e')); // Verify the selection toolbar position toolbarTopLeft = tester.getTopLeft(find.text('Select all')); textFieldTopLeft = tester.getTopLeft(find.byType(TextField)); expect(toolbarTopLeft.dy, lessThan(textFieldTopLeft.dy)); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets( 'the toolbar adjusts its position above/below when bottom inset changes', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 48.0, ), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ IntrinsicHeight( child: TextField( controller: controller, expands: true, maxLines: null, ), ), const SizedBox(height: 325.0), ], ), ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); await showSelectionMenuAt(tester, controller, testValue.indexOf('e')); // Verify the selection toolbar position is above the text. expect(find.text('Select all'), findsOneWidget); Offset toolbarTopLeft = tester.getTopLeft(find.text('Select all')); Offset textFieldTopLeft = tester.getTopLeft(find.byType(TextField)); expect(toolbarTopLeft.dy, lessThan(textFieldTopLeft.dy)); // Add a viewInset tall enough to push the field to the top, where there // is no room to display the toolbar above. This is similar to when the // keyboard is shown. tester.view.viewInsets = const FakeViewPadding(bottom: 500.0); addTearDown(tester.view.reset); await tester.pumpAndSettle(); // Verify the selection toolbar position is below the text. toolbarTopLeft = tester.getTopLeft(find.text('Select all')); textFieldTopLeft = tester.getTopLeft(find.byType(TextField)); expect(toolbarTopLeft.dy, greaterThan(textFieldTopLeft.dy)); // Remove the viewInset, as if the keyboard were hidden. tester.view.resetViewInsets(); await tester.pumpAndSettle(); // Verify the selection toolbar position is below the text. toolbarTopLeft = tester.getTopLeft(find.text('Select all')); textFieldTopLeft = tester.getTopLeft(find.byType(TextField)); expect(toolbarTopLeft.dy, lessThan(textFieldTopLeft.dy)); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets( 'Toolbar appears in the right places in multiline inputs', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/36749 final TextEditingController controller = _textEditingController(); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Padding( padding: const EdgeInsets.all(30.0), child: TextField( controller: controller, minLines: 6, maxLines: 6, ), ), ), )); expect(find.text('Select all'), findsNothing); const String testValue = 'abc\ndef\nghi\njkl\nmno\npqr'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Show the selection menu on the first line and verify the selection // toolbar position is below the first line. await showSelectionMenuAt(tester, controller, testValue.indexOf('c')); expect(find.text('Select all'), findsOneWidget); final Offset firstLineToolbarTopLeft = tester.getTopLeft(find.text('Select all')); final Offset firstLineTopLeft = textOffsetToPosition(tester, testValue.indexOf('a')); expect(firstLineTopLeft.dy, lessThan(firstLineToolbarTopLeft.dy)); // Show the selection menu on the second to last line and verify the // selection toolbar position is above that line and above the first // line's toolbar. await showSelectionMenuAt(tester, controller, testValue.indexOf('o')); expect(find.text('Select all'), findsOneWidget); final Offset penultimateLineToolbarTopLeft = tester.getTopLeft(find.text('Select all')); final Offset penultimateLineTopLeft = textOffsetToPosition(tester, testValue.indexOf('p')); expect(penultimateLineToolbarTopLeft.dy, lessThan(penultimateLineTopLeft.dy)); expect(penultimateLineToolbarTopLeft.dy, lessThan(firstLineToolbarTopLeft.dy)); // Show the selection menu on the last line and verify the selection // toolbar position is above that line and below the position of the // second to last line's toolbar. await showSelectionMenuAt(tester, controller, testValue.indexOf('r')); expect(find.text('Select all'), findsOneWidget); final Offset lastLineToolbarTopLeft = tester.getTopLeft(find.text('Select all')); final Offset lastLineTopLeft = textOffsetToPosition(tester, testValue.indexOf('p')); expect(lastLineToolbarTopLeft.dy, lessThan(lastLineTopLeft.dy)); expect(lastLineToolbarTopLeft.dy, greaterThan(penultimateLineToolbarTopLeft.dy)); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Selection toolbar fades in', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(); // Allow time for the handle to appear and for a double tap to time out. await tester.pump(const Duration(milliseconds: 600)); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); await tester.tapAt(endpoints[0].point + const Offset(1.0, 1.0)); // Pump an extra frame to allow the selection menu to read the clipboard. await tester.pump(); await tester.pump(); // Toolbar should fade in. Starting at 0% opacity. expect(find.text('Select all'), findsOneWidget); final Element target = tester.element(find.text('Select all')); final FadeTransition opacity = target.findAncestorWidgetOfExactType<FadeTransition>()!; expect(opacity.opacity.value, equals(0.0)); // Still fading in. await tester.pump(const Duration(milliseconds: 50)); final FadeTransition opacity2 = target.findAncestorWidgetOfExactType<FadeTransition>()!; expect(opacity, same(opacity2)); expect(opacity.opacity.value, greaterThan(0.0)); expect(opacity.opacity.value, lessThan(1.0)); // End the test here to ensure the animation is properly disposed of. }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('An obscured TextField is selectable by default', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/32845 final TextEditingController controller = _textEditingController(); Widget buildFrame(bool obscureText) { return overlay( child: TextField( controller: controller, obscureText: obscureText, ), ); } // Obscure text and don't enable or disable selection. await tester.pumpWidget(buildFrame(true)); await tester.enterText(find.byType(TextField), 'abcdefghi'); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); // Long press does select text. final Offset ePos = textOffsetToPosition(tester, 1); await tester.longPressAt(ePos, pointer: 7); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, false); }); testWidgets('An obscured TextField is not selectable when disabled', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/32845 final TextEditingController controller = _textEditingController(); Widget buildFrame(bool obscureText, bool enableInteractiveSelection) { return overlay( child: TextField( controller: controller, obscureText: obscureText, enableInteractiveSelection: enableInteractiveSelection, ), ); } // Explicitly disabled selection on obscured text. await tester.pumpWidget(buildFrame(true, false)); await tester.enterText(find.byType(TextField), 'abcdefghi'); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); // Long press doesn't select text. final Offset ePos2 = textOffsetToPosition(tester, 1); await tester.longPressAt(ePos2, pointer: 7); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); }); testWidgets('An obscured TextField is not selectable when read-only', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/32845 final TextEditingController controller = _textEditingController(); Widget buildFrame(bool obscureText, bool readOnly) { return overlay( child: TextField( controller: controller, obscureText: obscureText, readOnly: readOnly, ), ); } // Explicitly disabled selection on obscured text that is read-only. await tester.pumpWidget(buildFrame(true, true)); await tester.enterText(find.byType(TextField), 'abcdefghi'); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); // Long press doesn't select text. final Offset ePos2 = textOffsetToPosition(tester, 1); await tester.longPressAt(ePos2, pointer: 7); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); }); testWidgets('An obscured TextField is selected as one word', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget(overlay( child: TextField( controller: controller, obscureText: true, ), )); await tester.enterText(find.byType(TextField), 'abcde fghi'); await skipPastScrollingAnimation(tester); // Long press does select text. final Offset bPos = textOffsetToPosition(tester, 1); await tester.longPressAt(bPos, pointer: 7); await tester.pumpAndSettle(); final TextSelection selection = controller.selection; expect(selection.isCollapsed, false); expect(selection.baseOffset, 0); expect(selection.extentOffset, 10); }); testWidgets('An obscured TextField has correct default context menu', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget(overlay( child: TextField( controller: controller, obscureText: true, ), )); await tester.enterText(find.byType(TextField), 'abcde fghi'); await skipPastScrollingAnimation(tester); // Long press to select text. final Offset bPos = textOffsetToPosition(tester, 1); await tester.longPressAt(bPos, pointer: 7); await tester.pumpAndSettle(); // Should only have paste option when whole obscure text is selected. expect(find.text('Paste'), findsOneWidget); expect(find.text('Copy'), findsNothing); expect(find.text('Cut'), findsNothing); expect(find.text('Select all'), findsNothing); // Long press at the end final Offset iPos = textOffsetToPosition(tester, 10); final Offset slightRight = iPos + const Offset(30.0, 0.0); await tester.longPressAt(slightRight, pointer: 7); await tester.pumpAndSettle(); // Should have paste and select all options when collapse. expect(find.text('Paste'), findsOneWidget); expect(find.text('Select all'), findsOneWidget); expect(find.text('Copy'), findsNothing); expect(find.text('Cut'), findsNothing); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('create selection overlay if none exists when toggleToolbar is called', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/111660 final Widget testWidget = MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Test'), actions: <Widget>[ PopupMenuButton<String>( itemBuilder: (BuildContext context) { return <String>{'About'}.map((String value) { return PopupMenuItem<String>( value: value, child: Text(value), ); }).toList(); }, ), ], ), body: const TextField(), ), ); await tester.pumpWidget(testWidget); // Tap on TextField. final Offset textFieldStart = tester.getTopLeft(find.byType(TextField)); final TestGesture gesture = await tester.startGesture(textFieldStart); await tester.pump(const Duration(milliseconds: 300)); await gesture.up(); await tester.pumpAndSettle(); // Tap on 3 dot menu. await tester.tap(find.byType(PopupMenuButton<String>)); await tester.pumpAndSettle(); // Tap on TextField. await gesture.down(textFieldStart); await tester.pump(const Duration(milliseconds: 300)); await gesture.up(); await tester.pumpAndSettle(); // Tap on TextField again. await tester.tapAt(textFieldStart); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS})); testWidgets('TextField height with minLines unset', (WidgetTester tester) async { await tester.pumpWidget(textFieldBuilder()); RenderBox findInputBox() => tester.renderObject(find.byKey(textFieldKey)); final RenderBox inputBox = findInputBox(); final Size emptyInputSize = inputBox.size; await tester.enterText(find.byType(TextField), 'No wrapping here.'); await tester.pumpWidget(textFieldBuilder()); expect(findInputBox(), equals(inputBox)); expect(inputBox.size, equals(emptyInputSize)); // Even when entering multiline text, TextField doesn't grow. It's a single // line input. await tester.enterText(find.byType(TextField), kThreeLines); await tester.pumpWidget(textFieldBuilder()); expect(findInputBox(), equals(inputBox)); expect(inputBox.size, equals(emptyInputSize)); // maxLines: 3 makes the TextField 3 lines tall await tester.enterText(find.byType(TextField), ''); await tester.pumpWidget(textFieldBuilder(maxLines: 3)); expect(findInputBox(), equals(inputBox)); expect(inputBox.size.height, greaterThan(emptyInputSize.height)); expect(inputBox.size.width, emptyInputSize.width); final Size threeLineInputSize = inputBox.size; // Filling with 3 lines of text stays the same size await tester.enterText(find.byType(TextField), kThreeLines); await tester.pumpWidget(textFieldBuilder(maxLines: 3)); expect(findInputBox(), equals(inputBox)); expect(inputBox.size, threeLineInputSize); // An extra line won't increase the size because we max at 3. await tester.enterText(find.byType(TextField), kMoreThanFourLines); await tester.pumpWidget(textFieldBuilder(maxLines: 3)); expect(findInputBox(), equals(inputBox)); expect(inputBox.size, threeLineInputSize); // But now it will... but it will max at four await tester.enterText(find.byType(TextField), kMoreThanFourLines); await tester.pumpWidget(textFieldBuilder(maxLines: 4)); expect(findInputBox(), equals(inputBox)); expect(inputBox.size.height, greaterThan(threeLineInputSize.height)); expect(inputBox.size.width, threeLineInputSize.width); final Size fourLineInputSize = inputBox.size; // Now it won't max out until the end await tester.enterText(find.byType(TextField), ''); await tester.pumpWidget(textFieldBuilder(maxLines: null)); expect(findInputBox(), equals(inputBox)); expect(inputBox.size, equals(emptyInputSize)); await tester.enterText(find.byType(TextField), kThreeLines); await tester.pump(); expect(inputBox.size, equals(threeLineInputSize)); await tester.enterText(find.byType(TextField), kMoreThanFourLines); await tester.pump(); expect(inputBox.size.height, greaterThan(fourLineInputSize.height)); expect(inputBox.size.width, fourLineInputSize.width); }); testWidgets('TextField height with minLines and maxLines', (WidgetTester tester) async { await tester.pumpWidget(textFieldBuilder()); RenderBox findInputBox() => tester.renderObject(find.byKey(textFieldKey)); final RenderBox inputBox = findInputBox(); final Size emptyInputSize = inputBox.size; await tester.enterText(find.byType(TextField), 'No wrapping here.'); await tester.pumpWidget(textFieldBuilder()); expect(findInputBox(), equals(inputBox)); expect(inputBox.size, equals(emptyInputSize)); // min and max set to same value locks height to value. await tester.pumpWidget(textFieldBuilder(minLines: 3, maxLines: 3)); expect(findInputBox(), equals(inputBox)); expect(inputBox.size.height, greaterThan(emptyInputSize.height)); expect(inputBox.size.width, emptyInputSize.width); final Size threeLineInputSize = inputBox.size; // maxLines: null with minLines set grows beyond minLines await tester.pumpWidget(textFieldBuilder(minLines: 3, maxLines: null)); expect(findInputBox(), equals(inputBox)); expect(inputBox.size, threeLineInputSize); await tester.enterText(find.byType(TextField), kMoreThanFourLines); await tester.pump(); expect(inputBox.size.height, greaterThan(threeLineInputSize.height)); expect(inputBox.size.width, threeLineInputSize.width); // With minLines and maxLines set, input will expand through the range await tester.enterText(find.byType(TextField), ''); await tester.pumpWidget(textFieldBuilder(minLines: 3, maxLines: 4)); expect(findInputBox(), equals(inputBox)); expect(inputBox.size, equals(threeLineInputSize)); await tester.enterText(find.byType(TextField), kMoreThanFourLines); await tester.pump(); expect(inputBox.size.height, greaterThan(threeLineInputSize.height)); expect(inputBox.size.width, threeLineInputSize.width); // minLines can't be greater than maxLines. expect(() async { await tester.pumpWidget(textFieldBuilder(minLines: 3, maxLines: 2)); }, throwsAssertionError); // maxLines defaults to 1 and can't be less than minLines expect(() async { await tester.pumpWidget(textFieldBuilder(minLines: 3)); }, throwsAssertionError); }); testWidgets('Multiline text when wrapped in Expanded', (WidgetTester tester) async { Widget expandedTextFieldBuilder({ int? maxLines = 1, int? minLines, bool expands = false, }) { return boilerplate( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Expanded( child: TextField( key: textFieldKey, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: maxLines, minLines: minLines, expands: expands, decoration: const InputDecoration( hintText: 'Placeholder', ), ), ), ], ), ); } await tester.pumpWidget(expandedTextFieldBuilder()); RenderBox findBorder() { return tester.renderObject(find.descendant( of: find.byType(InputDecorator), matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_BorderContainer'), )); } final RenderBox border = findBorder(); // Without expanded: true and maxLines: null, the TextField does not expand // to fill its parent when wrapped in an Expanded widget. final Size unexpandedInputSize = border.size; // It does expand to fill its parent when expands: true, maxLines: null, and // it's wrapped in an Expanded widget. await tester.pumpWidget(expandedTextFieldBuilder(expands: true, maxLines: null)); expect(border.size.height, greaterThan(unexpandedInputSize.height)); expect(border.size.width, unexpandedInputSize.width); // min/maxLines that is not null and expands: true contradict each other. expect(() async { await tester.pumpWidget(expandedTextFieldBuilder(expands: true, maxLines: 4)); }, throwsAssertionError); expect(() async { await tester.pumpWidget(expandedTextFieldBuilder(expands: true, minLines: 1, maxLines: null)); }, throwsAssertionError); }); // Regression test for https://github.com/flutter/flutter/pull/29093 testWidgets('Multiline text when wrapped in IntrinsicHeight', (WidgetTester tester) async { final Key intrinsicHeightKey = UniqueKey(); Widget intrinsicTextFieldBuilder(bool wrapInIntrinsic) { final TextFormField textField = TextFormField( key: textFieldKey, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: null, decoration: const InputDecoration( counterText: 'I am counter', ), ); final Widget widget = wrapInIntrinsic ? IntrinsicHeight(key: intrinsicHeightKey, child: textField) : textField; return boilerplate( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[widget], ), ); } await tester.pumpWidget(intrinsicTextFieldBuilder(false)); expect(find.byKey(intrinsicHeightKey), findsNothing); RenderBox findEditableText() => tester.renderObject(find.byType(EditableText)); RenderBox editableText = findEditableText(); final Size unwrappedEditableTextSize = editableText.size; // Wrapping in IntrinsicHeight should not affect the height of the input await tester.pumpWidget(intrinsicTextFieldBuilder(true)); editableText = findEditableText(); expect(editableText.size.height, unwrappedEditableTextSize.height); expect(editableText.size.width, unwrappedEditableTextSize.width); }); // Regression test for https://github.com/flutter/flutter/pull/29093 testWidgets('errorText empty string', (WidgetTester tester) async { Widget textFormFieldBuilder(String? errorText) { return boilerplate( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextFormField( key: textFieldKey, maxLength: 3, maxLengthEnforcement: MaxLengthEnforcement.none, decoration: InputDecoration( counterText: '', errorText: errorText, ), ), ], ), ); } await tester.pumpWidget(textFormFieldBuilder(null)); RenderBox findInputBox() => tester.renderObject(find.byKey(textFieldKey)); final RenderBox inputBox = findInputBox(); final Size errorNullInputSize = inputBox.size; // Setting errorText causes the input's height to increase to accommodate it await tester.pumpWidget(textFormFieldBuilder('im errorText')); expect(inputBox, findInputBox()); expect(inputBox.size.height, greaterThan(errorNullInputSize.height)); expect(inputBox.size.width, errorNullInputSize.width); final Size errorInputSize = inputBox.size; // Setting errorText to an empty string causes the input's height to // increase to accommodate it, even though it's not displayed. // This may or may not be ideal behavior, but it is legacy behavior and // there are visual tests that rely on it (see Github issue referenced at // the top of this test). A counterText of empty string does not affect // input height, however. await tester.pumpWidget(textFormFieldBuilder('')); expect(inputBox, findInputBox()); expect(inputBox.size.height, errorInputSize.height); expect(inputBox.size.width, errorNullInputSize.width); }); testWidgets('Growable TextField when content height exceeds parent', (WidgetTester tester) async { const double height = 200.0; const double padding = 24.0; Widget containedTextFieldBuilder({ Widget? counter, String? helperText, String? labelText, Widget? prefix, }) { return boilerplate( theme: ThemeData(useMaterial3: false), child: SizedBox( height: height, child: TextField( key: textFieldKey, maxLines: null, decoration: InputDecoration( counter: counter, helperText: helperText, labelText: labelText, prefix: prefix, ), ), ), ); } await tester.pumpWidget(containedTextFieldBuilder()); RenderBox findEditableText() => tester.renderObject(find.byType(EditableText)); final RenderBox inputBox = findEditableText(); // With no decoration and when overflowing with content, the EditableText // takes up the full height minus the padding, so the input fits perfectly // inside the parent. await tester.enterText(find.byType(TextField), 'a\n' * 11); await tester.pump(); expect(findEditableText(), equals(inputBox)); expect(inputBox.size.height, height - padding); // Adding a counter causes the EditableText to shrink to fit the counter // inside the parent as well. const double counterHeight = 40.0; const double subtextGap = 8.0; const double counterSpace = counterHeight + subtextGap; await tester.pumpWidget(containedTextFieldBuilder( counter: Container(height: counterHeight), )); expect(findEditableText(), equals(inputBox)); expect(inputBox.size.height, height - padding - counterSpace); // Including helperText causes the EditableText to shrink to fit the text // inside the parent as well. await tester.pumpWidget(containedTextFieldBuilder( helperText: 'I am helperText', )); expect(findEditableText(), equals(inputBox)); const double helperTextSpace = 12.0; expect(inputBox.size.height, height - padding - helperTextSpace - subtextGap); // When both helperText and counter are present, EditableText shrinks by the // height of the taller of the two in order to fit both within the parent. await tester.pumpWidget(containedTextFieldBuilder( counter: Container(height: counterHeight), helperText: 'I am helperText', )); expect(findEditableText(), equals(inputBox)); expect(inputBox.size.height, height - padding - counterSpace); // When a label is present, EditableText shrinks to fit it at the top so // that the bottom of the input still lines up perfectly with the parent. await tester.pumpWidget(containedTextFieldBuilder( labelText: 'I am labelText', )); const double labelSpace = 16.0; expect(findEditableText(), equals(inputBox)); expect(inputBox.size.height, height - padding - labelSpace); // When decoration is present on the top and bottom, EditableText shrinks to // fit both inside the parent independently. await tester.pumpWidget(containedTextFieldBuilder( counter: Container(height: counterHeight), labelText: 'I am labelText', )); expect(findEditableText(), equals(inputBox)); expect(inputBox.size.height, height - padding - counterSpace - labelSpace); // When a prefix or suffix is present in an input that's full of content, // it is ignored and allowed to expand beyond the top of the input. Other // top and bottom decoration is still respected. await tester.pumpWidget(containedTextFieldBuilder( counter: Container(height: counterHeight), labelText: 'I am labelText', prefix: const SizedBox( width: 10, height: 60, ), )); expect(findEditableText(), equals(inputBox)); expect( inputBox.size.height, height - padding - labelSpace - counterSpace, ); }); testWidgets('Multiline hint text will wrap up to maxLines', (WidgetTester tester) async { final Key textFieldKey = UniqueKey(); Widget builder(int? maxLines, final String hintMsg) { return boilerplate( child: TextField( key: textFieldKey, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: maxLines, decoration: InputDecoration( hintText: hintMsg, ), ), ); } const String hintPlaceholder = 'Placeholder'; const String multipleLineText = "Here's a text, which is more than one line, to demonstrate the multiple line hint text"; await tester.pumpWidget(builder(null, hintPlaceholder)); RenderBox findHintText(String hint) => tester.renderObject(find.text(hint)); final RenderBox hintTextBox = findHintText(hintPlaceholder); final Size oneLineHintSize = hintTextBox.size; await tester.pumpWidget(builder(null, hintPlaceholder)); expect(findHintText(hintPlaceholder), equals(hintTextBox)); expect(hintTextBox.size, equals(oneLineHintSize)); const int maxLines = 3; await tester.pumpWidget(builder(maxLines, multipleLineText)); final Text hintTextWidget = tester.widget(find.text(multipleLineText)); expect(hintTextWidget.maxLines, equals(maxLines)); expect(findHintText(multipleLineText).size.width, greaterThanOrEqualTo(oneLineHintSize.width)); expect(findHintText(multipleLineText).size.height, greaterThanOrEqualTo(oneLineHintSize.height)); }); testWidgets('Can drag handles to change selection in multiline', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: 3, ), ), ), ); const String testValue = kThreeLines; const String cutValue = 'First line of stuff'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Check that the text spans multiple lines. final Offset firstPos = textOffsetToPosition(tester, testValue.indexOf('First')); final Offset secondPos = textOffsetToPosition(tester, testValue.indexOf('Second')); final Offset thirdPos = textOffsetToPosition(tester, testValue.indexOf('Third')); final Offset middleStringPos = textOffsetToPosition(tester, testValue.indexOf('irst')); expect(firstPos.dx, lessThan(middleStringPos.dx)); expect(firstPos.dx, secondPos.dx); expect(firstPos.dx, thirdPos.dx); expect(firstPos.dy, lessThan(secondPos.dy)); expect(secondPos.dy, lessThan(thirdPos.dy)); // Long press the 'n' in 'until' to select the word. final Offset untilPos = textOffsetToPosition(tester, testValue.indexOf('until')+1); TestGesture gesture = await tester.startGesture(untilPos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero expect( controller.selection, const TextSelection( baseOffset: 39, extentOffset: 44, ), ); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle to the third line, just after 'Third'. Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); // The distance below the y value returned by textOffsetToPosition required // to register a full vertical line drag. const Offset downLineOffset = Offset(0.0, 3.0); Offset newHandlePos = textOffsetToPosition(tester, testValue.indexOf('Third') + 5) + downLineOffset; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 39, extentOffset: 50, ), ); // Drag the left handle to the first line, just after 'First'. handlePos = endpoints[0].point + const Offset(-1.0, 1.0); newHandlePos = textOffsetToPosition(tester, testValue.indexOf('First') + 5); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 50); if (!isContextMenuProvidedByPlatform) { await tester.tap(find.text('Cut')); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.text, cutValue); } }); testWidgets('Can scroll multiline input', (WidgetTester tester) async { final Key textFieldKey = UniqueKey(); final TextEditingController controller = _textEditingController( text: kMoreThanFourLines, ); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, key: textFieldKey, controller: controller, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: 2, ), ), ); RenderBox findInputBox() => tester.renderObject(find.byKey(textFieldKey)); final RenderBox inputBox = findInputBox(); // Check that the last line of text is not displayed. final Offset firstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); final Offset fourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(firstPos.dx, fourthPos.dx); expect(firstPos.dy, lessThan(fourthPos.dy)); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(firstPos)), isTrue); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(fourthPos)), isFalse); TestGesture gesture = await tester.startGesture(firstPos, pointer: 7); await tester.pump(); await gesture.moveBy(const Offset(0.0, -1000.0)); await tester.pump(const Duration(seconds: 1)); // Wait and drag again to trigger https://github.com/flutter/flutter/issues/6329 // (No idea why this is necessary, but the bug wouldn't repro without it.) await gesture.moveBy(const Offset(0.0, -1000.0)); await tester.pump(const Duration(seconds: 1)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); // Now the first line is scrolled up, and the fourth line is visible. Offset newFirstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); Offset newFourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(newFirstPos.dy, lessThan(firstPos.dy)); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFirstPos)), isFalse); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), isTrue); // Now try scrolling by dragging the selection handle. // Long press the middle of the word "won't" in the fourth line. final Offset selectedWordPos = textOffsetToPosition( tester, kMoreThanFourLines.indexOf('Fourth line') + 14, ); gesture = await tester.startGesture(selectedWordPos, pointer: 7); await tester.pump(const Duration(seconds: 1)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.selection.base.offset, 77); expect(controller.selection.extent.offset, 82); // Sanity check for the word selected is the intended one. expect( controller.text.substring(controller.selection.baseOffset, controller.selection.extentOffset), "won't", ); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.length, 2); // Drag the left handle to the first line, just after 'First'. final Offset handlePos = endpoints[0].point + const Offset(-1, 1); final Offset newHandlePos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First') + 5); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(const Duration(seconds: 1)); await gesture.moveTo(newHandlePos + const Offset(0.0, -10.0)); await tester.pump(const Duration(seconds: 1)); await gesture.up(); await tester.pump(const Duration(seconds: 1)); // The text should have scrolled up with the handle to keep the active // cursor visible, back to its original position. newFirstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); newFourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(newFirstPos.dy, firstPos.dy); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFirstPos)), isTrue); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), isFalse); }); testWidgets('TextField smoke test', (WidgetTester tester) async { late String textFieldValue; await tester.pumpWidget( overlay( child: TextField( decoration: null, onChanged: (String value) { textFieldValue = value; }, ), ), ); Future<void> checkText(String testValue) { return TestAsyncUtils.guard(() async { await tester.enterText(find.byType(TextField), testValue); // Check that the onChanged event handler fired. expect(textFieldValue, equals(testValue)); await tester.pump(); }); } await checkText('Hello World'); }); testWidgets('TextField with global key', (WidgetTester tester) async { final GlobalKey textFieldKey = GlobalKey(debugLabel: 'textFieldKey'); late String textFieldValue; await tester.pumpWidget( overlay( child: TextField( key: textFieldKey, decoration: const InputDecoration( hintText: 'Placeholder', ), onChanged: (String value) { textFieldValue = value; }, ), ), ); Future<void> checkText(String testValue) async { return TestAsyncUtils.guard(() async { await tester.enterText(find.byType(TextField), testValue); // Check that the onChanged event handler fired. expect(textFieldValue, equals(testValue)); await tester.pump(); }); } await checkText('Hello World'); }); testWidgets('TextField errorText trumps helperText', (WidgetTester tester) async { await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: const TextField( decoration: InputDecoration( errorText: 'error text', helperText: 'helper text', ), ), ), ), ); expect(find.text('helper text'), findsNothing); expect(find.text('error text'), findsOneWidget); }); testWidgets('TextField with default helperStyle', (WidgetTester tester) async { final ThemeData themeData = ThemeData(hintColor: Colors.blue[500], useMaterial3: false); await tester.pumpWidget( overlay( child: Theme( data: themeData, child: const TextField( decoration: InputDecoration( helperText: 'helper text', ), ), ), ), ); final Text helperText = tester.widget(find.text('helper text')); expect(helperText.style!.color, themeData.hintColor); expect(helperText.style!.fontSize, Typography.englishLike2014.bodySmall!.fontSize); }); testWidgets('TextField with specified helperStyle', (WidgetTester tester) async { final TextStyle style = TextStyle( inherit: false, color: Colors.pink[500], fontSize: 10.0, ); await tester.pumpWidget( overlay( child: TextField( decoration: InputDecoration( helperText: 'helper text', helperStyle: style, ), ), ), ); final Text helperText = tester.widget(find.text('helper text')); expect(helperText.style, style); }); testWidgets('TextField with default hintStyle', (WidgetTester tester) async { final TextStyle style = TextStyle( color: Colors.pink[500], fontSize: 10.0, ); final ThemeData themeData = ThemeData( hintColor: Colors.blue[500], ); await tester.pumpWidget( overlay( child: Theme( data: themeData, child: TextField( decoration: const InputDecoration( hintText: 'Placeholder', ), style: style, ), ), ), ); final Text hintText = tester.widget(find.text('Placeholder')); expect(hintText.style!.color, themeData.hintColor); expect(hintText.style!.fontSize, style.fontSize); }); testWidgets('TextField with specified hintStyle', (WidgetTester tester) async { final TextStyle hintStyle = TextStyle( inherit: false, color: Colors.pink[500], fontSize: 10.0, ); await tester.pumpWidget( overlay( child: TextField( decoration: InputDecoration( hintText: 'Placeholder', hintStyle: hintStyle, ), ), ), ); final Text hintText = tester.widget(find.text('Placeholder')); expect(hintText.style, hintStyle); }); testWidgets('TextField with specified prefixStyle', (WidgetTester tester) async { final TextStyle prefixStyle = TextStyle( inherit: false, color: Colors.pink[500], fontSize: 10.0, ); await tester.pumpWidget( overlay( child: TextField( decoration: InputDecoration( prefixText: 'Prefix:', prefixStyle: prefixStyle, ), ), ), ); final Text prefixText = tester.widget(find.text('Prefix:')); expect(prefixText.style, prefixStyle); }); testWidgets('TextField prefix and suffix create a sibling node', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( overlay( child: TextField( controller: _textEditingController(text: 'some text'), decoration: const InputDecoration( prefixText: 'Prefix', suffixText: 'Suffix', ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 2, textDirection: TextDirection.ltr, label: 'Prefix', ), TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, value: 'some text', actions: <SemanticsAction>[ SemanticsAction.tap, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], ), TestSemantics.rootChild( id: 3, textDirection: TextDirection.ltr, label: 'Suffix', ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('TextField with specified suffixStyle', (WidgetTester tester) async { final TextStyle suffixStyle = TextStyle( color: Colors.pink[500], fontSize: 10.0, ); await tester.pumpWidget( overlay( child: TextField( decoration: InputDecoration( suffixText: '.com', suffixStyle: suffixStyle, ), ), ), ); final Text suffixText = tester.widget(find.text('.com')); expect(suffixText.style, suffixStyle); }); testWidgets('TextField prefix and suffix appear correctly with no hint or label', (WidgetTester tester) async { final Key secondKey = UniqueKey(); await tester.pumpWidget( overlay( child: Column( children: <Widget>[ const TextField( decoration: InputDecoration( labelText: 'First', ), ), TextField( key: secondKey, decoration: const InputDecoration( prefixText: 'Prefix', suffixText: 'Suffix', ), ), ], ), ), ); expect(find.text('Prefix'), findsOneWidget); expect(find.text('Suffix'), findsOneWidget); // Focus the Input. The prefix should still display. await tester.tap(find.byKey(secondKey)); await tester.pump(); expect(find.text('Prefix'), findsOneWidget); expect(find.text('Suffix'), findsOneWidget); // Enter some text, and the prefix should still display. await tester.enterText(find.byKey(secondKey), 'Hi'); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Prefix'), findsOneWidget); expect(find.text('Suffix'), findsOneWidget); }); testWidgets('TextField prefix and suffix appear correctly with hint text', (WidgetTester tester) async { final TextStyle hintStyle = TextStyle( inherit: false, color: Colors.pink[500], fontSize: 10.0, ); final Key secondKey = UniqueKey(); await tester.pumpWidget( overlay( child: Column( children: <Widget>[ const TextField( decoration: InputDecoration( labelText: 'First', ), ), TextField( key: secondKey, decoration: InputDecoration( hintText: 'Hint', hintStyle: hintStyle, prefixText: 'Prefix', suffixText: 'Suffix', ), ), ], ), ), ); // Neither the prefix or the suffix should initially be visible, only the hint. expect(getOpacity(tester, find.text('Prefix')), 0.0); expect(getOpacity(tester, find.text('Suffix')), 0.0); expect(getOpacity(tester, find.text('Hint')), 1.0); await tester.tap(find.byKey(secondKey)); await tester.pumpAndSettle(); // Focus the Input. The hint, prefix, and suffix should appear expect(getOpacity(tester, find.text('Prefix')), 1.0); expect(getOpacity(tester, find.text('Suffix')), 1.0); expect(getOpacity(tester, find.text('Hint')), 1.0); // Enter some text, and the hint should disappear and the prefix and suffix // should continue to be visible await tester.enterText(find.byKey(secondKey), 'Hi'); await tester.pumpAndSettle(); expect(getOpacity(tester, find.text('Prefix')), 1.0); expect(getOpacity(tester, find.text('Suffix')), 1.0); expect(getOpacity(tester, find.text('Hint')), 0.0); // Check and make sure that the right styles were applied. final Text prefixText = tester.widget(find.text('Prefix')); expect(prefixText.style, hintStyle); final Text suffixText = tester.widget(find.text('Suffix')); expect(suffixText.style, hintStyle); }); testWidgets('TextField prefix and suffix appear correctly with label text', (WidgetTester tester) async { final TextStyle prefixStyle = TextStyle( color: Colors.pink[500], fontSize: 10.0, ); final TextStyle suffixStyle = TextStyle( color: Colors.green[500], fontSize: 12.0, ); final Key secondKey = UniqueKey(); await tester.pumpWidget( overlay( child: Column( children: <Widget>[ const TextField( decoration: InputDecoration( labelText: 'First', ), ), TextField( key: secondKey, decoration: InputDecoration( labelText: 'Label', prefixText: 'Prefix', prefixStyle: prefixStyle, suffixText: 'Suffix', suffixStyle: suffixStyle, ), ), ], ), ), ); // Not focused. The prefix and suffix should not appear, but the label should. expect(getOpacity(tester, find.text('Prefix')), 0.0); expect(getOpacity(tester, find.text('Suffix')), 0.0); expect(find.text('Label'), findsOneWidget); // Focus the input. The label, prefix, and suffix should appear. await tester.tap(find.byKey(secondKey)); await tester.pumpAndSettle(); expect(getOpacity(tester, find.text('Prefix')), 1.0); expect(getOpacity(tester, find.text('Suffix')), 1.0); expect(find.text('Label'), findsOneWidget); // Enter some text. The label, prefix, and suffix should remain visible. await tester.enterText(find.byKey(secondKey), 'Hi'); await tester.pumpAndSettle(); expect(getOpacity(tester, find.text('Prefix')), 1.0); expect(getOpacity(tester, find.text('Suffix')), 1.0); expect(find.text('Label'), findsOneWidget); // Check and make sure that the right styles were applied. final Text prefixText = tester.widget(find.text('Prefix')); expect(prefixText.style, prefixStyle); final Text suffixText = tester.widget(find.text('Suffix')); expect(suffixText.style, suffixStyle); }); testWidgets('TextField label text animates', (WidgetTester tester) async { final Key secondKey = UniqueKey(); await tester.pumpWidget( overlay( child: Column( children: <Widget>[ const TextField( decoration: InputDecoration( labelText: 'First', ), ), TextField( key: secondKey, decoration: const InputDecoration( labelText: 'Second', ), ), ], ), ), ); Offset pos = tester.getTopLeft(find.text('Second')); // Focus the Input. The label should start animating upwards. await tester.tap(find.byKey(secondKey)); await tester.idle(); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); Offset newPos = tester.getTopLeft(find.text('Second')); expect(newPos.dy, lessThan(pos.dy)); // Label should still be sliding upward. await tester.pump(const Duration(milliseconds: 50)); pos = newPos; newPos = tester.getTopLeft(find.text('Second')); expect(newPos.dy, lessThan(pos.dy)); }); testWidgets('Icon is separated from input/label by 16+12', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const TextField( decoration: InputDecoration( icon: Icon(Icons.phone), labelText: 'label', filled: true, ), ), ), ); final double iconRight = tester.getTopRight(find.byType(Icon)).dx; // Per https://material.io/go/design-text-fields#text-fields-layout // There's a 16 dps gap between the right edge of the icon and the text field's // container, and the 12dps more padding between the left edge of the container // and the left edge of the input and label. expect(iconRight + 28.0, equals(tester.getTopLeft(find.text('label')).dx)); expect(iconRight + 28.0, equals(tester.getTopLeft(find.byType(EditableText)).dx)); }); testWidgets('Collapsed hint text placement', (WidgetTester tester) async { await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: const TextField( decoration: InputDecoration.collapsed( hintText: 'hint', ), strutStyle: StrutStyle.disabled, ), ), ), ); expect(tester.getTopLeft(find.text('hint')), equals(tester.getTopLeft(find.byType(EditableText)))); }); testWidgets('Can align to center', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SizedBox( width: 300.0, child: TextField( textAlign: TextAlign.center, decoration: null, ), ), ), ); final RenderEditable editable = findRenderEditable(tester); assert(editable.size.width == 300); Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 0)).topLeft, ); // The overlay() function centers its child within a 800x600 view. // Default cursorWidth is 2.0, test viewWidth is 800 // Centered cursor topLeft.dx: 399 == viewWidth/2 - cursorWidth/2 expect(topLeft.dx, equals(399.0)); await tester.enterText(find.byType(TextField), 'abcd'); await tester.pump(); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 2)).topLeft, ); // TextPosition(offset: 2) - center of 'abcd' expect(topLeft.dx, equals(399.0)); }); testWidgets('Can align to center within center', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SizedBox( width: 300.0, child: Center( child: TextField( textAlign: TextAlign.center, decoration: null, ), ), ), ), ); final RenderEditable editable = findRenderEditable(tester); Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 0)).topLeft, ); // The overlay() function centers its child within a 800x600 view. // Default cursorWidth is 2.0, test viewWidth is 800 // Centered cursor topLeft.dx: 399 == viewWidth/2 - cursorWidth/2 expect(topLeft.dx, equals(399.0)); await tester.enterText(find.byType(TextField), 'abcd'); await tester.pump(); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 2)).topLeft, ); // TextPosition(offset: 2) - center of 'abcd' expect(topLeft.dx, equals(399.0)); }); testWidgets('Controller can update server', (WidgetTester tester) async { final TextEditingController controller1 = _textEditingController( text: 'Initial Text', ); final TextEditingController controller2 = _textEditingController( text: 'More Text', ); TextEditingController? currentController; late StateSetter setState; await tester.pumpWidget( overlay( child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return TextField(controller: currentController); }, ), ), ); expect(tester.testTextInput.editingState, isNull); // Initial state with null controller. await tester.tap(find.byType(TextField)); await tester.pump(); expect(tester.testTextInput.editingState!['text'], isEmpty); // Update the controller from null to controller1. setState(() { currentController = controller1; }); await tester.pump(); expect(tester.testTextInput.editingState!['text'], equals('Initial Text')); // Verify that updates to controller1 are handled. controller1.text = 'Updated Text'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('Updated Text')); // Verify that switching from controller1 to controller2 is handled. setState(() { currentController = controller2; }); await tester.pump(); expect(tester.testTextInput.editingState!['text'], equals('More Text')); // Verify that updates to controller1 are ignored. controller1.text = 'Ignored Text'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('More Text')); // Verify that updates to controller text are handled. controller2.text = 'Additional Text'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('Additional Text')); // Verify that updates to controller selection are handled. controller2.selection = const TextSelection(baseOffset: 0, extentOffset: 5); await tester.idle(); expect(tester.testTextInput.editingState!['selectionBase'], equals(0)); expect(tester.testTextInput.editingState!['selectionExtent'], equals(5)); // Verify that calling clear() clears the text. controller2.clear(); await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('')); // Verify that switching from controller2 to null preserves current text. controller2.text = 'The Final Cut'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('The Final Cut')); setState(() { currentController = null; }); await tester.pump(); expect(tester.testTextInput.editingState!['text'], equals('The Final Cut')); // Verify that changes to controller2 are ignored. controller2.text = 'Goodbye Cruel World'; expect(tester.testTextInput.editingState!['text'], equals('The Final Cut')); }); testWidgets('Cannot enter new lines onto single line TextField', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField(controller: textController, decoration: null), )); await tester.enterText(find.byType(TextField), 'abc\ndef'); expect(textController.text, 'abcdef'); }); testWidgets('Injected formatters are chained', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, decoration: null, inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.deny( RegExp(r'[a-z]'), replacementString: '#', ), ], ), )); await tester.enterText(find.byType(TextField), 'a一b二c三\nd四e五f六'); // The default single line formatter replaces \n with empty string. expect(textController.text, '#一#二#三#四#五#六'); }); testWidgets('Injected formatters are chained (deprecated names)', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, decoration: null, inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.deny( RegExp(r'[a-z]'), replacementString: '#', ), ], ), )); await tester.enterText(find.byType(TextField), 'a一b二c三\nd四e五f六'); // The default single line formatter replaces \n with empty string. expect(textController.text, '#一#二#三#四#五#六'); }); testWidgets('Chained formatters are in sequence', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, decoration: null, maxLines: 2, inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.deny( RegExp(r'[a-z]'), replacementString: '12\n', ), FilteringTextInputFormatter.allow(RegExp(r'\n[0-9]')), ], ), )); await tester.enterText(find.byType(TextField), 'a1b2c3'); // The first formatter turns it into // 12\n112\n212\n3 // The second formatter turns it into // \n1\n2\n3 // Multiline is allowed since maxLine != 1. expect(textController.text, '\n1\n2\n3'); }); testWidgets('Chained formatters are in sequence (deprecated names)', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, decoration: null, maxLines: 2, inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.deny( RegExp(r'[a-z]'), replacementString: '12\n', ), FilteringTextInputFormatter.allow(RegExp(r'\n[0-9]')), ], ), )); await tester.enterText(find.byType(TextField), 'a1b2c3'); // The first formatter turns it into // 12\n112\n212\n3 // The second formatter turns it into // \n1\n2\n3 // Multiline is allowed since maxLine != 1. expect(textController.text, '\n1\n2\n3'); }); testWidgets('Pasted values are formatted', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: textController, decoration: null, inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.digitsOnly, ], ), ), ); await tester.enterText(find.byType(TextField), 'a1b\n2c3'); expect(textController.text, '123'); await skipPastScrollingAnimation(tester); await tester.tapAt(textOffsetToPosition(tester, '123'.indexOf('2'))); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(textController.selection), renderEditable, ); await tester.tapAt(endpoints[0].point + const Offset(1.0, 1.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero Clipboard.setData(const ClipboardData(text: '一4二\n5三6')); await tester.tap(find.text('Paste')); await tester.pump(); // Puts 456 before the 2 in 123. expect(textController.text, '145623'); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('Pasted values are formatted (deprecated names)', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: textController, decoration: null, inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.digitsOnly, ], ), ), ); await tester.enterText(find.byType(TextField), 'a1b\n2c3'); expect(textController.text, '123'); await skipPastScrollingAnimation(tester); await tester.tapAt(textOffsetToPosition(tester, '123'.indexOf('2'))); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(textController.selection), renderEditable, ); await tester.tapAt(endpoints[0].point + const Offset(1.0, 1.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero Clipboard.setData(const ClipboardData(text: '一4二\n5三6')); await tester.tap(find.text('Paste')); await tester.pump(); // Puts 456 before the 2 in 123. expect(textController.text, '145623'); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('Do not add LengthLimiting formatter to the user supplied list', (WidgetTester tester) async { final List<TextInputFormatter> formatters = <TextInputFormatter>[]; await tester.pumpWidget( overlay( child: TextField( decoration: null, maxLength: 5, inputFormatters: formatters, ), ), ); expect(formatters.isEmpty, isTrue); }); testWidgets('Text field scrolls the caret into view', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: SizedBox( width: 100.0, child: TextField( controller: controller, ), ), ), ), ); final String longText = 'a' * 20; await tester.enterText(find.byType(TextField), longText); await skipPastScrollingAnimation(tester); ScrollableState scrollableState = tester.firstState(find.byType(Scrollable)); expect(scrollableState.position.pixels, equals(0.0)); // Move the caret to the end of the text and check that the text field // scrolls to make the caret visible. scrollableState = tester.firstState(find.byType(Scrollable)); final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); editableTextState.userUpdateTextEditingValue( editableTextState.textEditingValue.copyWith( selection: TextSelection.collapsed(offset: longText.length), ), null, ); await tester.pump(); // TODO(ianh): Figure out why this extra pump is needed. await skipPastScrollingAnimation(tester); scrollableState = tester.firstState(find.byType(Scrollable)); // For a horizontal input, scrolls to the exact position of the caret. expect(scrollableState.position.pixels, equals(222.0)); }); testWidgets('Multiline text field scrolls the caret into view', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, maxLines: 6, ), ), ); const String tallText = 'a\nb\nc\nd\ne\nf\ng'; // One line over max await tester.enterText(find.byType(TextField), tallText); await skipPastScrollingAnimation(tester); ScrollableState scrollableState = tester.firstState(find.byType(Scrollable)); expect(scrollableState.position.pixels, equals(0.0)); // Move the caret to the end of the text and check that the text field // scrolls to make the caret visible. final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); editableTextState.userUpdateTextEditingValue( editableTextState.textEditingValue.copyWith( selection: const TextSelection.collapsed(offset: tallText.length), ), null, ); await tester.pump(); await skipPastScrollingAnimation(tester); // Should have scrolled down exactly one line height (7 lines of text in 6 // line text field). final double lineHeight = findRenderEditable(tester).preferredLineHeight; scrollableState = tester.firstState(find.byType(Scrollable)); expect(scrollableState.position.pixels, moreOrLessEquals(lineHeight, epsilon: 0.1)); }); testWidgets('haptic feedback', (WidgetTester tester) async { final FeedbackTester feedback = FeedbackTester(); addTearDown(feedback.dispose); final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: SizedBox( width: 100.0, child: TextField( controller: controller, ), ), ), ); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 0); expect(feedback.hapticCount, 0); await tester.longPress(find.byType(TextField)); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 0); expect(feedback.hapticCount, 1); }); testWidgets('Text field drops selection color when losing focus', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/103341. final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); final TextEditingController controller1 = _textEditingController(); const Color selectionColor = Colors.orange; const Color cursorColor = Colors.red; await tester.pumpWidget( overlay( child: DefaultSelectionStyle( selectionColor: selectionColor, cursorColor: cursorColor, child: Column( children: <Widget>[ TextField( key: key1, controller: controller1, ), TextField(key: key2), ], ), ), ), ); const TextSelection selection = TextSelection(baseOffset: 0, extentOffset: 4); final EditableTextState state1 = tester.state<EditableTextState>(find.byType(EditableText).first); final EditableTextState state2 = tester.state<EditableTextState>(find.byType(EditableText).last); await tester.tap(find.byKey(key1)); await tester.enterText(find.byKey(key1), 'abcd'); await tester.pump(); await tester.tap(find.byKey(key2)); await tester.enterText(find.byKey(key2), 'dcba'); await tester.pump(); // Focus and selection is active on first TextField, so the second TextFields // selectionColor should be dropped. await tester.tap(find.byKey(key1)); controller1.selection = const TextSelection(baseOffset: 0, extentOffset: 4); await tester.pump(); expect(controller1.selection, selection); expect(state1.widget.selectionColor, selectionColor); expect(state2.widget.selectionColor, null); // Focus and selection is active on second TextField, so the first TextFields // selectionColor should be dropped. await tester.tap(find.byKey(key2)); await tester.pump(); expect(state1.widget.selectionColor, null); expect(state2.widget.selectionColor, selectionColor); }); testWidgets('Selection is consistent with text length', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); controller.text = 'abcde'; controller.selection = const TextSelection.collapsed(offset: 5); controller.text = ''; expect(controller.selection.start, lessThanOrEqualTo(0)); expect(controller.selection.end, lessThanOrEqualTo(0)); late FlutterError error; try { controller.selection = const TextSelection.collapsed(offset: 10); } on FlutterError catch (e) { error = e; } finally { expect(error.diagnostics.length, 1); expect( error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' invalid text selection: TextSelection.collapsed(offset: 10,\n' ' affinity: TextAffinity.downstream, isDirectional: false)\n', ), ); } }); // Regression test for https://github.com/flutter/flutter/issues/35848 testWidgets('Clearing text field with suffixIcon does not cause text selection exception', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Prefilled text.', ); await tester.pumpWidget( boilerplate( child: TextField( controller: controller, decoration: InputDecoration( suffixIcon: IconButton( icon: const Icon(Icons.close), onPressed: controller.clear, ), ), ), ), ); await tester.tap(find.byType(IconButton)); expect(controller.text, ''); }); testWidgets('maxLength limits input.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, ), )); await tester.enterText(find.byType(TextField), '0123456789101112'); expect(textController.text, '0123456789'); }); testWidgets('maxLength limits input with surrogate pairs.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, ), )); const String surrogatePair = '😆'; await tester.enterText(find.byType(TextField), '${surrogatePair}0123456789101112'); expect(textController.text, '${surrogatePair}012345678'); }); testWidgets('maxLength limits input with grapheme clusters.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, ), )); const String graphemeCluster = '👨‍👩‍👦'; await tester.enterText(find.byType(TextField), '${graphemeCluster}0123456789101112'); expect(textController.text, '${graphemeCluster}012345678'); }); testWidgets('maxLength limits input in the center of a maxed-out field.', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/37420. final TextEditingController textController = _textEditingController(); const String testValue = '0123456789'; await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, ), )); // Max out the character limit in the field. await tester.enterText(find.byType(TextField), testValue); expect(textController.text, testValue); // Entering more characters at the end does nothing. await tester.enterText(find.byType(TextField), '${testValue}9999999'); expect(textController.text, testValue); // Entering text in the middle of the field also does nothing. await tester.enterText(find.byType(TextField), '0123455555555556789'); expect(textController.text, testValue); }); testWidgets( 'maxLength limits input in the center of a maxed-out field, with collapsed selection', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); const String testValue = '0123456789'; await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, ), )); // Max out the character limit in the field. await tester.showKeyboard(find.byType(TextField)); tester.testTextInput.updateEditingValue(const TextEditingValue( text: testValue, selection: TextSelection.collapsed(offset: 10), )); await tester.pump(); expect(textController.text, testValue); // Entering more characters at the end does nothing. await tester.showKeyboard(find.byType(TextField)); tester.testTextInput.updateEditingValue(const TextEditingValue( text: '${testValue}9999999', selection: TextSelection.collapsed(offset: 10 + 7), )); await tester.pump(); expect(textController.text, testValue); // Entering text in the middle of the field also does nothing. // Entering more characters at the end does nothing. await tester.showKeyboard(find.byType(TextField)); tester.testTextInput.updateEditingValue(const TextEditingValue( text: '0123455555555556789', selection: TextSelection.collapsed(offset: 19), )); await tester.pump(); expect(textController.text, testValue); }, ); testWidgets( 'maxLength limits input in the center of a maxed-out field, with non-collapsed selection', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); const String testValue = '0123456789'; await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, maxLengthEnforcement: MaxLengthEnforcement.enforced, ), )); // Max out the character limit in the field. await tester.showKeyboard(find.byType(TextField)); tester.testTextInput.updateEditingValue(const TextEditingValue( text: testValue, selection: TextSelection(baseOffset: 8, extentOffset: 10), )); await tester.pump(); expect(textController.text, testValue); // Entering more characters at the end does nothing. await tester.showKeyboard(find.byType(TextField)); tester.testTextInput.updateEditingValue(const TextEditingValue( text: '01234569999999', selection: TextSelection.collapsed(offset: 14), )); await tester.pump(); expect(textController.text, '0123456999'); }, ); testWidgets('maxLength limits input length even if decoration is null.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, decoration: null, maxLength: 10, ), )); await tester.enterText(find.byType(TextField), '0123456789101112'); expect(textController.text, '0123456789'); }); testWidgets('maxLength still works with other formatters', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.deny( RegExp(r'[a-z]'), replacementString: '#', ), ], ), )); await tester.enterText(find.byType(TextField), 'a一b二c三\nd四e五f六'); // The default single line formatter replaces \n with empty string. expect(textController.text, '#一#二#三#四#五'); }); testWidgets('maxLength still works with other formatters (deprecated names)', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.deny( RegExp(r'[a-z]'), replacementString: '#', ), ], ), )); await tester.enterText(find.byType(TextField), 'a一b二c三\nd四e五f六'); // The default single line formatter replaces \n with empty string. expect(textController.text, '#一#二#三#四#五'); }); testWidgets("maxLength isn't enforced when maxLengthEnforcement.none.", (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, maxLengthEnforcement: MaxLengthEnforcement.none, ), )); await tester.enterText(find.byType(TextField), '0123456789101112'); expect(textController.text, '0123456789101112'); }); testWidgets('maxLength shows warning when maxLengthEnforcement.none.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); const TextStyle testStyle = TextStyle(color: Colors.deepPurpleAccent); await tester.pumpWidget(boilerplate( child: TextField( decoration: const InputDecoration(errorStyle: testStyle), controller: textController, maxLength: 10, maxLengthEnforcement: MaxLengthEnforcement.none, ), )); await tester.enterText(find.byType(TextField), '0123456789101112'); await tester.pump(); expect(textController.text, '0123456789101112'); expect(find.text('16/10'), findsOneWidget); Text counterTextWidget = tester.widget(find.text('16/10')); expect(counterTextWidget.style!.color, equals(Colors.deepPurpleAccent)); await tester.enterText(find.byType(TextField), '0123456789'); await tester.pump(); expect(textController.text, '0123456789'); expect(find.text('10/10'), findsOneWidget); counterTextWidget = tester.widget(find.text('10/10')); expect(counterTextWidget.style!.color, isNot(equals(Colors.deepPurpleAccent))); }); testWidgets('maxLength shows warning in Material 3', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); final ThemeData theme = ThemeData.from( colorScheme: const ColorScheme.light().copyWith(error: Colors.deepPurpleAccent), useMaterial3: true, ); await tester.pumpWidget(boilerplate( theme: theme, child: TextField( controller: textController, maxLength: 10, maxLengthEnforcement: MaxLengthEnforcement.none, ), )); await tester.enterText(find.byType(TextField), '0123456789101112'); await tester.pump(); expect(textController.text, '0123456789101112'); expect(find.text('16/10'), findsOneWidget); Text counterTextWidget = tester.widget(find.text('16/10')); expect(counterTextWidget.style!.color, equals(Colors.deepPurpleAccent)); await tester.enterText(find.byType(TextField), '0123456789'); await tester.pump(); expect(textController.text, '0123456789'); expect(find.text('10/10'), findsOneWidget); counterTextWidget = tester.widget(find.text('10/10')); expect(counterTextWidget.style!.color, isNot(equals(Colors.deepPurpleAccent))); }); testWidgets('maxLength shows warning when maxLengthEnforcement.none with surrogate pairs.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); const TextStyle testStyle = TextStyle(color: Colors.deepPurpleAccent); await tester.pumpWidget(boilerplate( child: TextField( decoration: const InputDecoration(errorStyle: testStyle), controller: textController, maxLength: 10, maxLengthEnforcement: MaxLengthEnforcement.none, ), )); await tester.enterText(find.byType(TextField), '😆012345678910111'); await tester.pump(); expect(textController.text, '😆012345678910111'); expect(find.text('16/10'), findsOneWidget); Text counterTextWidget = tester.widget(find.text('16/10')); expect(counterTextWidget.style!.color, equals(Colors.deepPurpleAccent)); await tester.enterText(find.byType(TextField), '😆012345678'); await tester.pump(); expect(textController.text, '😆012345678'); expect(find.text('10/10'), findsOneWidget); counterTextWidget = tester.widget(find.text('10/10')); expect(counterTextWidget.style!.color, isNot(equals(Colors.deepPurpleAccent))); }); testWidgets('maxLength shows warning when maxLengthEnforcement.none with grapheme clusters.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); const TextStyle testStyle = TextStyle(color: Colors.deepPurpleAccent); await tester.pumpWidget(boilerplate( child: TextField( decoration: const InputDecoration(errorStyle: testStyle), controller: textController, maxLength: 10, maxLengthEnforcement: MaxLengthEnforcement.none, ), )); await tester.enterText(find.byType(TextField), '👨‍👩‍👦012345678910111'); await tester.pump(); expect(textController.text, '👨‍👩‍👦012345678910111'); expect(find.text('16/10'), findsOneWidget); Text counterTextWidget = tester.widget(find.text('16/10')); expect(counterTextWidget.style!.color, equals(Colors.deepPurpleAccent)); await tester.enterText(find.byType(TextField), '👨‍👩‍👦012345678'); await tester.pump(); expect(textController.text, '👨‍👩‍👦012345678'); expect(find.text('10/10'), findsOneWidget); counterTextWidget = tester.widget(find.text('10/10')); expect(counterTextWidget.style!.color, isNot(equals(Colors.deepPurpleAccent))); }); testWidgets('maxLength limits input with surrogate pairs.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, ), )); const String surrogatePair = '😆'; await tester.enterText(find.byType(TextField), '${surrogatePair}0123456789101112'); expect(textController.text, '${surrogatePair}012345678'); }); testWidgets('maxLength limits input with grapheme clusters.', (WidgetTester tester) async { final TextEditingController textController = _textEditingController(); await tester.pumpWidget(boilerplate( child: TextField( controller: textController, maxLength: 10, ), )); const String graphemeCluster = '👨‍👩‍👦'; await tester.enterText(find.byType(TextField), '${graphemeCluster}0123456789101112'); expect(textController.text, '${graphemeCluster}012345678'); }); testWidgets('setting maxLength shows counter', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: TextField( maxLength: 10, ), ), ), ), ); expect(find.text('0/10'), findsOneWidget); await tester.enterText(find.byType(TextField), '01234'); await tester.pump(); expect(find.text('5/10'), findsOneWidget); }); testWidgets('maxLength counter measures surrogate pairs as one character', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: TextField( maxLength: 10, ), ), ), ), ); expect(find.text('0/10'), findsOneWidget); const String surrogatePair = '😆'; await tester.enterText(find.byType(TextField), surrogatePair); await tester.pump(); expect(find.text('1/10'), findsOneWidget); }); testWidgets('maxLength counter measures grapheme clusters as one character', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: TextField( maxLength: 10, ), ), ), ), ); expect(find.text('0/10'), findsOneWidget); const String familyEmoji = '👨‍👩‍👦'; await tester.enterText(find.byType(TextField), familyEmoji); await tester.pump(); expect(find.text('1/10'), findsOneWidget); }); testWidgets('setting maxLength to TextField.noMaxLength shows only entered length', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: TextField( maxLength: TextField.noMaxLength, ), ), ), ), ); expect(find.text('0'), findsOneWidget); await tester.enterText(find.byType(TextField), '01234'); await tester.pump(); expect(find.text('5'), findsOneWidget); }); testWidgets('passing a buildCounter shows returned widget', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: Center( child: TextField( buildCounter: (BuildContext context, { required int currentLength, int? maxLength, required bool isFocused }) { return Text('$currentLength of $maxLength'); }, maxLength: 10, ), ), ), ), ); expect(find.text('0 of 10'), findsOneWidget); await tester.enterText(find.byType(TextField), '01234'); await tester.pump(); expect(find.text('5 of 10'), findsOneWidget); }); testWidgets('TextField identifies as text field in semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: TextField( maxLength: 10, ), ), ), ), ); expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled])); semantics.dispose(); }); testWidgets('Can scroll multiline input when disabled', (WidgetTester tester) async { final Key textFieldKey = UniqueKey(); final TextEditingController controller = _textEditingController( text: kMoreThanFourLines, ); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, key: textFieldKey, controller: controller, ignorePointers: false, enabled: false, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: 2, ), ), ); RenderBox findInputBox() => tester.renderObject(find.byKey(textFieldKey)); final RenderBox inputBox = findInputBox(); // Check that the last line of text is not displayed. final Offset firstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); final Offset fourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(firstPos.dx, fourthPos.dx); expect(firstPos.dy, lessThan(fourthPos.dy)); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(firstPos)), isTrue); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(fourthPos)), isFalse); final TestGesture gesture = await tester.startGesture(firstPos, pointer: 7); await tester.pump(); await gesture.moveBy(const Offset(0.0, -1000.0)); await tester.pumpAndSettle(); await gesture.moveBy(const Offset(0.0, -1000.0)); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); // Now the first line is scrolled up, and the fourth line is visible. final Offset finalFirstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); final Offset finalFourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(finalFirstPos.dy, lessThan(firstPos.dy)); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(finalFirstPos)), isFalse); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(finalFourthPos)), isTrue); }); testWidgets('Disabled text field does not have tap action', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: TextField( maxLength: 10, enabled: false, ), ), ), ), ); expect(semantics, isNot(includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap]))); semantics.dispose(); }); testWidgets('Disabled text field semantics node still contains value', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: _textEditingController(text: 'text'), maxLength: 10, enabled: false, ), ), ), ), ); expect(semantics, includesNodeWith(actions: <SemanticsAction>[], value: 'text')); semantics.dispose(); }); testWidgets('Readonly text field does not have tap action', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: TextField( maxLength: 10, readOnly: true, ), ), ), ), ); expect(semantics, isNot(includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap]))); semantics.dispose(); }); testWidgets('Disabled text field hides helper and counter', (WidgetTester tester) async { const String helperText = 'helper text'; const String counterText = 'counter text'; const String errorText = 'error text'; Widget buildFrame(bool enabled, bool hasError) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( decoration: InputDecoration( labelText: 'label text', helperText: helperText, counterText: counterText, errorText: hasError ? errorText : null, enabled: enabled, ), ), ), ), ); } await tester.pumpWidget(buildFrame(true, false)); Text helperWidget = tester.widget(find.text(helperText)); Text counterWidget = tester.widget(find.text(counterText)); expect(helperWidget.style!.color, isNot(equals(Colors.transparent))); expect(counterWidget.style!.color, isNot(equals(Colors.transparent))); await tester.pumpWidget(buildFrame(true, true)); counterWidget = tester.widget(find.text(counterText)); Text errorWidget = tester.widget(find.text(errorText)); expect(helperWidget.style!.color, isNot(equals(Colors.transparent))); expect(errorWidget.style!.color, isNot(equals(Colors.transparent))); // When enabled is false, the helper/error and counter are not visible. await tester.pumpWidget(buildFrame(false, false)); helperWidget = tester.widget(find.text(helperText)); counterWidget = tester.widget(find.text(counterText)); expect(helperWidget.style!.color, equals(Colors.transparent)); expect(counterWidget.style!.color, equals(Colors.transparent)); await tester.pumpWidget(buildFrame(false, true)); errorWidget = tester.widget(find.text(errorText)); counterWidget = tester.widget(find.text(counterText)); expect(counterWidget.style!.color, equals(Colors.transparent)); expect(errorWidget.style!.color, equals(Colors.transparent)); }); testWidgets('Disabled text field has default M2 disabled text style for the input text', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( controller: controller, enabled: false, ), ), ), ), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, Colors.black38); // Colors.black38 is the default disabled color for ThemeData.light(). }); testWidgets('Disabled text field has default M3 disabled text style for the input text', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); final ThemeData theme = ThemeData.light(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: Material( child: Center( child: TextField( controller: controller, enabled: false, ), ), ), ), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, theme.textTheme.bodyLarge!.color!.withOpacity(0.38)); }); testWidgets('Enabled TextField statesController', (WidgetTester tester) async { final TextEditingController textEditingController = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(textEditingController.dispose); int count = 0; void valueChanged() { count += 1; } final MaterialStatesController statesController = MaterialStatesController(); addTearDown(statesController.dispose); statesController.addListener(valueChanged); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( statesController: statesController, controller: textEditingController, ), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); final Offset center = tester.getCenter(find.byType(EditableText).first); await gesture.moveTo(center); await tester.pump(); expect(statesController.value, <MaterialState>{MaterialState.hovered}); expect(count, 1); await gesture.moveTo(Offset.zero); await tester.pump(); expect(statesController.value, <MaterialState>{}); expect(count, 2); await gesture.down(center); await tester.pump(); await gesture.up(); await tester.pump(); expect(statesController.value, <MaterialState>{MaterialState.hovered, MaterialState.focused}); expect(count, 4); // adds hovered and pressed - two changes. await gesture.moveTo(Offset.zero); await tester.pump(); expect(statesController.value, <MaterialState>{MaterialState.focused}); expect(count, 5); await gesture.down(Offset.zero); await tester.pump(); expect(statesController.value, <MaterialState>{}); expect(count, 6); await gesture.up(); await tester.pump(); await gesture.down(center); await tester.pump(); await gesture.up(); await tester.pump(); expect(statesController.value, <MaterialState>{MaterialState.hovered, MaterialState.focused}); expect(count, 8); // adds hovered and pressed - two changes. // If the text field is rebuilt disabled, then the focused state is // removed. await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( statesController: statesController, controller: textEditingController, enabled: false, ), ), ), ), ); await tester.pumpAndSettle(); expect(statesController.value, <MaterialState>{MaterialState.hovered, MaterialState.disabled}); expect(count, 10); // removes focused and adds disabled - two changes. await gesture.moveTo(Offset.zero); await tester.pump(); expect(statesController.value, <MaterialState>{MaterialState.disabled}); expect(count, 11); // If the text field is rebuilt enabled and in an error state, then the error // state is added. await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( statesController: statesController, controller: textEditingController, decoration: const InputDecoration( errorText: 'error', ), ), ), ), ), ); await tester.pumpAndSettle(); expect(statesController.value, <MaterialState>{MaterialState.error}); expect(count, 13); // removes disabled and adds error - two changes. // If the text field is rebuilt without an error, then the error // state is removed. await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( statesController: statesController, controller: textEditingController, ), ), ), ), ); await tester.pumpAndSettle(); expect(statesController.value, <MaterialState>{}); expect(count, 14); }); testWidgets('Disabled TextField statesController', (WidgetTester tester) async { int count = 0; void valueChanged() { count += 1; } final MaterialStatesController controller = MaterialStatesController(); addTearDown(controller.dispose); controller.addListener(valueChanged); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( statesController: controller, enabled: false, ), ), ), ), ); expect(controller.value, <MaterialState>{MaterialState.disabled}); expect(count, 1); }); testWidgets('Provided style correctly resolves for material states', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); final ThemeData theme = ThemeData.light(useMaterial3: true); Widget buildFrame(bool enabled) { return MaterialApp( theme: theme, home: Material( child: Center( child: TextField( controller: controller, enabled: enabled, style: MaterialStateTextStyle.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return const TextStyle(color: Colors.red); } return const TextStyle(color: Colors.blue); }), ), ), ), ); } await tester.pumpWidget(buildFrame(false)); EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, Colors.red); await tester.pumpWidget(buildFrame(true)); editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, Colors.blue); }); testWidgets('currentValueLength/maxValueLength are in the tree', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, maxLength: 10, ), ), ), ), ); expect(semantics, includesNodeWith( flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled], maxValueLength: 10, currentValueLength: 0, )); await tester.showKeyboard(find.byType(TextField)); const String testValue = '123'; tester.testTextInput.updateEditingValue(const TextEditingValue( text: testValue, selection: TextSelection.collapsed(offset: 3), composing: TextRange(start: 0, end: testValue.length), )); await tester.pump(); expect(semantics, includesNodeWith( flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], maxValueLength: 10, currentValueLength: 3, )); semantics.dispose(); }); testWidgets('Read only TextField identifies as read only text field in semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: TextField( maxLength: 10, readOnly: true, ), ), ), ), ); expect( semantics, includesNodeWith(flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isReadOnly, ]), ); semantics.dispose(); }); testWidgets("Disabled TextField can't be traversed to.", (WidgetTester tester) async { final FocusNode focusNode1 = FocusNode(debugLabel: 'TextField 1'); addTearDown(focusNode1.dispose); final FocusNode focusNode2 = FocusNode(debugLabel: 'TextField 2'); addTearDown(focusNode2.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: FocusScope( child: Center( child: Column( children: <Widget>[ TextField( focusNode: focusNode1, autofocus: true, maxLength: 10, enabled: true, ), TextField( focusNode: focusNode2, maxLength: 10, enabled: false, ), ], ), ), ), ), ), ); await tester.pump(); expect(focusNode1.hasPrimaryFocus, isTrue); expect(focusNode2.hasPrimaryFocus, isFalse); expect(focusNode1.nextFocus(), isFalse); await tester.pump(); expect(focusNode1.hasPrimaryFocus, isTrue); expect(focusNode2.hasPrimaryFocus, isFalse); }); group('Keyboard Tests', () { late TextEditingController controller; setUp( () { controller = _textEditingController(); }); Future<void> setupWidget(WidgetTester tester) async { final FocusNode focusNode = _focusNode(); controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, child: TextField( controller: controller, maxLines: 3, ), ), ), ), ); await tester.pump(); } testWidgets('Shift test 1', (WidgetTester tester) async { await setupWidget(tester); const String testValue = 'a big house'; await tester.enterText(find.byType(TextField), testValue); await tester.idle(); // Need to wait for selection to catch up. await tester.pump(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.extentOffset - controller.selection.baseOffset, -1); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Shift test 2', (WidgetTester tester) async { await setupWidget(tester); const String testValue = 'abcdefghi'; await tester.showKeyboard(find.byType(TextField)); tester.testTextInput.updateEditingValue(const TextEditingValue( text: testValue, selection: TextSelection.collapsed(offset: 3), composing: TextRange(start: 0, end: testValue.length), )); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 1); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Control Shift test', (WidgetTester tester) async { await setupWidget(tester); const String testValue = 'their big house'; await tester.enterText(find.byType(TextField), testValue); await tester.idle(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.control); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 5); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Down and up test', (WidgetTester tester) async { await setupWidget(tester); const String testValue = 'a big house'; await tester.enterText(find.byType(TextField), testValue); await tester.idle(); // Need to wait for selection to catch up. await tester.pump(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, -11); await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 0); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Down and up test 2', (WidgetTester tester) async { await setupWidget(tester); const String testValue = 'a big house\njumped over a mouse\nOne more line yay'; // 11 \n 19 await tester.enterText(find.byType(TextField), testValue); await tester.idle(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); for (int i = 0; i < 5; i += 1) { await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); } await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 12); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 32); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 12); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, -5); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Read only keyboard selection test', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(text: 'readonly'); await tester.pumpWidget( overlay( child: TextField( controller: controller, readOnly: true, ), ), ); await tester.idle(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowLeft); expect(controller.selection.extentOffset - controller.selection.baseOffset, -1); }, variant: KeySimulatorTransitModeVariant.all()); }, skip: areKeyEventsHandledByPlatform); // [intended] only applies to platforms where we handle key events. testWidgets('Copy paste test', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); final TextEditingController controller = _textEditingController(); final TextField textField = TextField( controller: controller, maxLines: 3, ); String clipboardContent = ''; tester.binding.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'Clipboard.setData') { // ignore: avoid_dynamic_calls clipboardContent = methodCall.arguments['text'] as String; } else if (methodCall.method == 'Clipboard.getData') { return <String, dynamic>{'text': clipboardContent}; } return null; }); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, child: textField, ), ), ), ); focusNode.requestFocus(); await tester.pump(); const String testValue = 'a big house\njumped over a mouse'; // 11 \n 19 await tester.enterText(find.byType(TextField), testValue); await tester.idle(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); // Select the first 5 characters await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); // Copy them await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); await tester.sendKeyEvent(LogicalKeyboardKey.keyC); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); await tester.pumpAndSettle(); expect(clipboardContent, 'a big'); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); // Paste them await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyV); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 200)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyV); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); await tester.pumpAndSettle(); const String expected = 'a biga big house\njumped over a mouse'; expect(find.text(expected), findsOneWidget, reason: 'Because text contains ${controller.text}'); }, skip: areKeyEventsHandledByPlatform, // [intended] only applies to platforms where we handle key events. variant: KeySimulatorTransitModeVariant.all() ); // Regression test for https://github.com/flutter/flutter/issues/78219 testWidgets('Paste does not crash after calling TextController.text setter', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); final TextEditingController controller = _textEditingController(); final TextField textField = TextField( controller: controller, obscureText: true, ); const String clipboardContent = 'I love Flutter!'; tester.binding.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'Clipboard.getData') { return <String, dynamic>{'text': clipboardContent}; } return null; }); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, child: textField, ), ), ), ); focusNode.requestFocus(); await tester.pump(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); // Clear the text. controller.text = ''; // Paste clipboardContent to the text field. await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyV); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 200)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyV); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); await tester.pumpAndSettle(); // Clipboard content is correctly pasted. expect(find.text(clipboardContent), findsOneWidget); }, skip: areKeyEventsHandledByPlatform, // [intended] only applies to platforms where we handle key events. variant: KeySimulatorTransitModeVariant.all(), ); testWidgets('Cut test', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); final TextEditingController controller = _textEditingController(); final TextField textField = TextField( controller: controller, maxLines: 3, ); String clipboardContent = ''; tester.binding.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'Clipboard.setData') { // ignore: avoid_dynamic_calls clipboardContent = methodCall.arguments['text'] as String; } else if (methodCall.method == 'Clipboard.getData') { return <String, dynamic>{'text': clipboardContent}; } return null; }); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, child: textField, ), ), ), ); focusNode.requestFocus(); await tester.pump(); const String testValue = 'a big house\njumped over a mouse'; // 11 \n 19 await tester.enterText(find.byType(TextField), testValue); await tester.idle(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); // Select the first 5 characters for (int i = 0; i < 5; i += 1) { await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); } // Cut them await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); await tester.sendKeyEvent(LogicalKeyboardKey.keyX); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); await tester.pumpAndSettle(); expect(clipboardContent, 'a big'); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); } // Paste them await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyV); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 200)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyV); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); await tester.pumpAndSettle(); const String expected = ' housa bige\njumped over a mouse'; expect(find.text(expected), findsOneWidget); }, skip: areKeyEventsHandledByPlatform, // [intended] only applies to platforms where we handle key events. variant: KeySimulatorTransitModeVariant.all() ); testWidgets('Select all test', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); final TextEditingController controller = _textEditingController(); final TextField textField = TextField( controller: controller, maxLines: 3, ); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, child: textField, ), ), ), ); focusNode.requestFocus(); await tester.pump(); const String testValue = 'a big house\njumped over a mouse'; // 11 \n 19 await tester.enterText(find.byType(TextField), testValue); await tester.idle(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); // Select All await tester.sendKeyDownEvent(LogicalKeyboardKey.control); await tester.sendKeyEvent(LogicalKeyboardKey.keyA); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.control); await tester.pumpAndSettle(); // Delete them await tester.sendKeyDownEvent(LogicalKeyboardKey.delete); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 200)); await tester.sendKeyUpEvent(LogicalKeyboardKey.delete); await tester.pumpAndSettle(); const String expected = ''; expect(find.text(expected), findsOneWidget); }, skip: areKeyEventsHandledByPlatform, // [intended] only applies to platforms where we handle key events. variant: KeySimulatorTransitModeVariant.all() ); testWidgets('Delete test', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); final TextEditingController controller = _textEditingController(); final TextField textField = TextField( controller: controller, maxLines: 3, ); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, child: textField, ), ), ), ); focusNode.requestFocus(); await tester.pump(); const String testValue = 'a big house\njumped over a mouse'; // 11 \n 19 await tester.enterText(find.byType(TextField), testValue); await tester.idle(); await tester.tap(find.byType(TextField)); await tester.pumpAndSettle(); // Delete for (int i = 0; i < 6; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.delete); await tester.pumpAndSettle(); } const String expected = 'house\njumped over a mouse'; expect(find.text(expected), findsOneWidget); await tester.sendKeyDownEvent(LogicalKeyboardKey.control); await tester.sendKeyEvent(LogicalKeyboardKey.keyA); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.control); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.delete); await tester.pumpAndSettle(); const String expected2 = ''; expect(find.text(expected2), findsOneWidget); }, skip: areKeyEventsHandledByPlatform, // [intended] only applies to platforms where we handle key events. variant: KeySimulatorTransitModeVariant.all(), ); testWidgets('Changing positions of text fields', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); final List<KeyEvent> events = <KeyEvent>[]; final TextEditingController c1 = _textEditingController(); final TextEditingController c2 = _textEditingController(); final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ TextField( key: key1, controller: c1, maxLines: 3, ), TextField( key: key2, controller: c2, maxLines: 3, ), ], ), ), ), ), ); const String testValue = 'a big house'; await tester.enterText(find.byType(TextField).first, testValue); await tester.idle(); // Need to wait for selection to catch up. await tester.pump(); await tester.tap(find.byType(TextField).first); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(c1.selection.extentOffset - c1.selection.baseOffset, -5); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ TextField( key: key2, controller: c2, maxLines: 3, ), TextField( key: key1, controller: c1, maxLines: 3, ), ], ), ), ), ), ); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(c1.selection.extentOffset - c1.selection.baseOffset, -10); }, skip: areKeyEventsHandledByPlatform, // [intended] only applies to platforms where we handle key events. variant: KeySimulatorTransitModeVariant.all() ); testWidgets('Changing focus test', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); final List<KeyEvent> events = <KeyEvent>[]; final TextEditingController c1 = _textEditingController(); final TextEditingController c2 = _textEditingController(); final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ TextField( key: key1, controller: c1, maxLines: 3, ), TextField( key: key2, controller: c2, maxLines: 3, ), ], ), ), ), ), ); const String testValue = 'a big house'; await tester.enterText(find.byType(TextField).first, testValue); await tester.idle(); await tester.pump(); await tester.idle(); await tester.tap(find.byType(TextField).first); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(c1.selection.extentOffset - c1.selection.baseOffset, -5); expect(c2.selection.extentOffset - c2.selection.baseOffset, 0); await tester.enterText(find.byType(TextField).last, testValue); await tester.idle(); await tester.pump(); await tester.idle(); await tester.tap(find.byType(TextField).last); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(c1.selection.extentOffset - c1.selection.baseOffset, -5); expect(c2.selection.extentOffset - c2.selection.baseOffset, -5); }, skip: areKeyEventsHandledByPlatform, // [intended] only applies to platforms where we handle key events. variant: KeySimulatorTransitModeVariant.all() ); testWidgets('Caret works when maxLines is null', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( controller: controller, maxLines: null, ), ), ); const String testValue = 'x'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.length); // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is // Confirm that the selection was updated. expect(controller.selection.baseOffset, 0); }); testWidgets('TextField baseline alignment no-strut', (WidgetTester tester) async { final TextEditingController controllerA = _textEditingController(text: 'A'); final TextEditingController controllerB = _textEditingController(text: 'B'); final Key keyA = UniqueKey(); final Key keyB = UniqueKey(); await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Expanded( child: TextField( key: keyA, decoration: null, controller: controllerA, // The point size of the font must be a multiple of 4 until // https://github.com/flutter/flutter/issues/122066 is resolved. style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 12.0), strutStyle: StrutStyle.disabled, ), ), const Text( 'abc', // The point size of the font must be a multiple of 4 until // https://github.com/flutter/flutter/issues/122066 is resolved. style: TextStyle(fontFamily: 'FlutterTest', fontSize: 24.0), ), Expanded( child: TextField( key: keyB, decoration: null, controller: controllerB, // The point size of the font must be a multiple of 4 until // https://github.com/flutter/flutter/issues/122066 is resolved. style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 36.0), strutStyle: StrutStyle.disabled, ), ), ], ), ), ), ); // The test font extends 0.25 * fontSize below the baseline. // So the three row elements line up like this: // // A abc B // --------- baseline // 3 6 9 space below the baseline = 0.25 * fontSize // --------- rowBottomY final double rowBottomY = tester.getBottomLeft(find.byType(Row)).dy; expect(tester.getBottomLeft(find.byKey(keyA)).dy, rowBottomY - 6.0); expect(tester.getBottomLeft(find.text('abc')).dy, rowBottomY - 3.0); expect(tester.getBottomLeft(find.byKey(keyB)).dy, rowBottomY); }); testWidgets('TextField baseline alignment', (WidgetTester tester) async { final TextEditingController controllerA = _textEditingController(text: 'A'); final TextEditingController controllerB = _textEditingController(text: 'B'); final Key keyA = UniqueKey(); final Key keyB = UniqueKey(); await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: overlay( child: Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Expanded( child: TextField( key: keyA, decoration: null, controller: controllerA, // The point size of the font must be a multiple of 4 until // https://github.com/flutter/flutter/issues/122066 is resolved. style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 12.0), ), ), const Text( 'abc', // The point size of the font must be a multiple of 4 until // https://github.com/flutter/flutter/issues/122066 is resolved. style: TextStyle(fontFamily: 'FlutterTest', fontSize: 24.0), ), Expanded( child: TextField( key: keyB, decoration: null, controller: controllerB, // The point size of the font must be a multiple of 4 until // https://github.com/flutter/flutter/issues/122066 is resolved. style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 36.0), ), ), ], ), ), ), ); // The test font extends 0.25 * fontSize below the baseline. // So the three row elements line up like this: // // A abc B // --------- baseline // 3 6 9 space below the baseline = 0.25 * fontSize // --------- rowBottomY final double rowBottomY = tester.getBottomLeft(find.byType(Row)).dy; // The values here should match the version with strut disabled ('TextField baseline alignment no-strut') expect(tester.getBottomLeft(find.byKey(keyA)).dy, rowBottomY - 6.0); expect(tester.getBottomLeft(find.text('abc')).dy, rowBottomY - 3.0); expect(tester.getBottomLeft(find.byKey(keyB)).dy, rowBottomY); }); testWidgets('TextField semantics include label when unfocused and label/hint when focused if input is empty', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, decoration: const InputDecoration( hintText: 'hint', labelText: 'label', ), ), ), ); final SemanticsNode node = tester.getSemantics(find.byKey(key)); expect(node.label, 'label'); expect(node.value, ''); // Focus text field. await tester.tap(find.byKey(key)); await tester.pump(); expect(node.label, 'label'); expect(node.value, ''); semantics.dispose(); }); testWidgets('TextField semantics always include label and not hint when input value is not empty', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(text: 'value'); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, decoration: const InputDecoration( hintText: 'hint', labelText: 'label', ), ), ), ); final SemanticsNode node = tester.getSemantics(find.byKey(key)); expect(node.label, 'label'); expect(node.value, 'value'); // Focus text field. await tester.tap(find.byKey(key)); await tester.pump(); expect(node.label, 'label'); expect(node.value, 'value'); semantics.dispose(); }); testWidgets('TextField semantics always include label when no hint is given', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(text: 'value'); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, decoration: const InputDecoration( labelText: 'label', ), ), ), ); final SemanticsNode node = tester.getSemantics(find.byKey(key)); expect(node.label, 'label'); expect(node.value, 'value'); // Focus text field. await tester.tap(find.byKey(key)); await tester.pump(); expect(node.label, 'label'); expect(node.value, 'value'); semantics.dispose(); }); testWidgets('TextField semantics only include hint when it is visible', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(text: 'value'); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, decoration: const InputDecoration( hintText: 'hint', ), ), ), ); final SemanticsNode node = tester.getSemantics(find.byKey(key)); expect(node.label, ''); expect(node.value, 'value'); // Focus text field. await tester.tap(find.byKey(key)); await tester.pump(); expect(node.label, ''); expect(node.value, 'value'); // Clear the Text. await tester.enterText(find.byType(TextField), ''); await tester.pumpAndSettle(); expect(node.value, ''); expect(node.label, 'hint'); semantics.dispose(); }); testWidgets('TextField semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], ), ], ), ignoreTransform: true, ignoreRect: true)); controller.text = 'Guten Tag'; await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, value: 'Guten Tag', actions: <SemanticsAction>[ SemanticsAction.tap, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], ), ], ), ignoreTransform: true, ignoreRect: true)); await tester.tap(find.byKey(key)); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, value: 'Guten Tag', textSelection: const TextSelection.collapsed(offset: 9), actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); controller.selection = const TextSelection.collapsed(offset: 4); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, textSelection: const TextSelection.collapsed(offset: 4), value: 'Guten Tag', actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); controller.text = 'Schönen Feierabend'; controller.selection = const TextSelection.collapsed(offset: 0); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, textSelection: const TextSelection.collapsed(offset: 0), value: 'Schönen Feierabend', actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorForwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); // Regressing test for https://github.com/flutter/flutter/issues/99763 testWidgets('Update textField semantics when obscureText changes', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); await tester.pumpWidget(_ObscureTextTestWidget(controller: controller)); controller.text = 'Hello'; await tester.pump(); expect( semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], value: 'Hello', ) ); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect( semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isObscured, ], ) ); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect( semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], textDirection: TextDirection.ltr, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], value: 'Hello', ) ); semantics.dispose(); }); testWidgets('TextField semantics, enableInteractiveSelection = false', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, enableInteractiveSelection: false, ), ), ); await tester.tap(find.byKey(key)); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.setText, // Absent the following because enableInteractiveSelection: false // SemanticsAction.moveCursorBackwardByCharacter, // SemanticsAction.moveCursorBackwardByWord, // SemanticsAction.setSelection, // SemanticsAction.paste, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('TextField semantics for selections', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController() ..text = 'Hello'; final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, value: 'Hello', textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], ), ], ), ignoreTransform: true, ignoreRect: true)); // Focus the text field await tester.tap(find.byKey(key)); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, value: 'Hello', textSelection: const TextSelection.collapsed(offset: 5), textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); controller.selection = const TextSelection(baseOffset: 5, extentOffset: 3); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, value: 'Hello', textSelection: const TextSelection(baseOffset: 5, extentOffset: 3), textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, SemanticsAction.cut, SemanticsAction.copy, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('TextField change selection with semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final TextEditingController controller = _textEditingController() ..text = 'Hello'; final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, ), ), ); // Focus the text field await tester.tap(find.byKey(key)); await tester.pump(); const int inputFieldId = 1; expect(controller.selection, const TextSelection.collapsed(offset: 5, affinity: TextAffinity.upstream)); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: inputFieldId, value: 'Hello', textSelection: const TextSelection.collapsed(offset: 5), textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); // move cursor back once semanticsOwner.performAction(inputFieldId, SemanticsAction.setSelection, <dynamic, dynamic>{ 'base': 4, 'extent': 4, }); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 4)); // move cursor to front semanticsOwner.performAction(inputFieldId, SemanticsAction.setSelection, <dynamic, dynamic>{ 'base': 0, 'extent': 0, }); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 0)); // select all semanticsOwner.performAction(inputFieldId, SemanticsAction.setSelection, <dynamic, dynamic>{ 'base': 0, 'extent': 5, }); await tester.pump(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: inputFieldId, value: 'Hello', textSelection: const TextSelection(baseOffset: 0, extentOffset: 5), textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, SemanticsAction.cut, SemanticsAction.copy, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('Can activate TextField with explicit controller via semantics ', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/17801 const String textInTextField = 'Hello'; final SemanticsTester semantics = SemanticsTester(tester); final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final TextEditingController controller = _textEditingController() ..text = textInTextField; final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, ), ), ); const int inputFieldId = 1; expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: inputFieldId, flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled], actions: <SemanticsAction>[SemanticsAction.tap], value: textInTextField, textDirection: TextDirection.ltr, ), ], ), ignoreRect: true, ignoreTransform: true, )); semanticsOwner.performAction(inputFieldId, SemanticsAction.tap); await tester.pump(); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: inputFieldId, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, ], value: textInTextField, textDirection: TextDirection.ltr, textSelection: const TextSelection( baseOffset: textInTextField.length, extentOffset: textInTextField.length, ), ), ], ), ignoreRect: true, ignoreTransform: true, )); semantics.dispose(); }); testWidgets('When clipboard empty, no semantics paste option', (WidgetTester tester) async { const String textInTextField = 'Hello'; final SemanticsTester semantics = SemanticsTester(tester); final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final TextEditingController controller = _textEditingController() ..text = textInTextField; final Key key = UniqueKey(); // Clear the clipboard. await Clipboard.setData(const ClipboardData(text: '')); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, ), ), ); const int inputFieldId = 1; expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: inputFieldId, flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled], actions: <SemanticsAction>[SemanticsAction.tap], value: textInTextField, textDirection: TextDirection.ltr, ), ], ), ignoreRect: true, ignoreTransform: true, )); semanticsOwner.performAction(inputFieldId, SemanticsAction.tap); await tester.pump(); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: inputFieldId, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, // No paste option. ], value: textInTextField, textDirection: TextDirection.ltr, textSelection: const TextSelection( baseOffset: textInTextField.length, extentOffset: textInTextField.length, ), ), ], ), ignoreRect: true, ignoreTransform: true, )); semantics.dispose(); // On web, we don't check for pasteability because that triggers a // permission dialog in the browser. // https://github.com/flutter/flutter/pull/57139#issuecomment-629048058 }, skip: isBrowser); // [intended] see above. testWidgets('TextField throws when not descended from a Material widget', (WidgetTester tester) async { const Widget textField = TextField(); await tester.pumpWidget(textField); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect(exception.toString(), startsWith('No Material widget found.')); }); testWidgets('TextField loses focus when disabled', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'TextField Focus Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( boilerplate( child: TextField( focusNode: focusNode, autofocus: true, enabled: true, ), ), ); expect(focusNode.hasFocus, isTrue); await tester.pumpWidget( boilerplate( child: TextField( focusNode: focusNode, autofocus: true, enabled: false, ), ), ); expect(focusNode.hasFocus, isFalse); await tester.pumpWidget( boilerplate( child: Builder(builder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith( navigationMode: NavigationMode.directional, ), child: TextField( focusNode: focusNode, autofocus: true, enabled: true, ), ); }), ), ); focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasFocus, isTrue); await tester.pumpWidget( boilerplate( child: Builder(builder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith( navigationMode: NavigationMode.directional, ), child: TextField( focusNode: focusNode, autofocus: true, enabled: false, ), ); }), ), ); await tester.pump(); expect(focusNode.hasFocus, isTrue); }); testWidgets('TextField displays text with text direction', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: const Material( child: TextField( textDirection: TextDirection.rtl, ), ), ), ); RenderEditable editable = findRenderEditable(tester); await tester.enterText(find.byType(TextField), '0123456789101112'); await tester.pumpAndSettle(); Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 10)).topLeft, ); expect(topLeft.dx, equals(701)); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: const Material( child: TextField( textDirection: TextDirection.ltr, ), ), ), ); editable = findRenderEditable(tester); await tester.enterText(find.byType(TextField), '0123456789101112'); await tester.pumpAndSettle(); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 10)).topLeft, ); expect(topLeft.dx, equals(160.0)); }); testWidgets('TextField semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, maxLength: 10, decoration: const InputDecoration( labelText: 'label', hintText: 'hint', helperText: 'helper', ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( label: 'label', id: 1, textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], children: <TestSemantics>[ TestSemantics( id: 2, label: 'helper', textDirection: TextDirection.ltr, ), TestSemantics( id: 3, label: '10 characters remaining', textDirection: TextDirection.ltr, ), ], ), ], ), ignoreTransform: true, ignoreRect: true)); await tester.tap(find.byType(TextField)); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( label: 'label', id: 1, textDirection: TextDirection.ltr, textSelection: const TextSelection(baseOffset: 0, extentOffset: 0), actions: <SemanticsAction>[ SemanticsAction.tap, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocused, ], children: <TestSemantics>[ TestSemantics( id: 2, label: 'helper', textDirection: TextDirection.ltr, ), TestSemantics( id: 3, label: '10 characters remaining', flags: <SemanticsFlag>[ SemanticsFlag.isLiveRegion, ], textDirection: TextDirection.ltr, ), ], ), ], ), ignoreTransform: true, ignoreRect: true)); controller.text = 'hello'; await tester.pump(); semantics.dispose(); }); testWidgets('InputDecoration counterText can have a semanticCounterText', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, decoration: const InputDecoration( labelText: 'label', hintText: 'hint', helperText: 'helper', counterText: '0/10', semanticCounterText: '0 out of 10', ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( label: 'label', textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], children: <TestSemantics>[ TestSemantics( label: 'helper', textDirection: TextDirection.ltr, ), TestSemantics( label: '0 out of 10', textDirection: TextDirection.ltr, ), ], ), ], ), ignoreTransform: true, ignoreRect: true, ignoreId: true)); semantics.dispose(); }); testWidgets('InputDecoration errorText semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = _textEditingController(); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: TextField( key: key, controller: controller, decoration: const InputDecoration( labelText: 'label', hintText: 'hint', errorText: 'oh no!', ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( label: 'label', textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.tap, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], children: <TestSemantics>[ TestSemantics( label: 'oh no!', textDirection: TextDirection.ltr, ), ], ), ], ), ignoreTransform: true, ignoreRect: true, ignoreId: true)); semantics.dispose(); }); testWidgets('floating label does not overlap with value at large textScaleFactors', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(text: 'Just some text'); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: MediaQuery( data: const MediaQueryData(textScaler: TextScaler.linear(4.0)), child: Center( child: TextField( decoration: const InputDecoration(labelText: 'Label', border: UnderlineInputBorder()), controller: controller, ), ), ), ), ), ); await tester.tap(find.byType(TextField)); final Rect labelRect = tester.getRect(find.text('Label')); final Rect fieldRect = tester.getRect(find.text('Just some text')); expect(labelRect.bottom, lessThanOrEqualTo(fieldRect.top)); }); testWidgets('TextField scrolls into view but does not bounce (SingleChildScrollView)', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/20485 final Key textField1 = UniqueKey(); final Key textField2 = UniqueKey(); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); double? minOffset; double? maxOffset; scrollController.addListener(() { final double offset = scrollController.offset; minOffset = math.min(minOffset ?? offset, offset); maxOffset = math.max(maxOffset ?? offset, offset); }); Widget buildFrame(Axis scrollDirection) { return MaterialApp( home: Scaffold( body: SafeArea( child: SingleChildScrollView( physics: const BouncingScrollPhysics(), controller: scrollController, child: Column( children: <Widget>[ SizedBox( // visible when scrollOffset is 0.0 height: 100.0, width: 100.0, child: TextField(key: textField1, scrollPadding: const EdgeInsets.all(200.0)), ), const SizedBox( height: 600.0, // Same size as the frame. Initially width: 800.0, // textField2 is not visible ), SizedBox( // visible when scrollOffset is 200.0 height: 100.0, width: 100.0, child: TextField(key: textField2, scrollPadding: const EdgeInsets.all(200.0)), ), ], ), ), ), ), ); } await tester.pumpWidget(buildFrame(Axis.vertical)); await tester.enterText(find.byKey(textField1), '1'); await tester.pumpAndSettle(); await tester.enterText(find.byKey(textField2), '2'); //scroll textField2 into view await tester.pumpAndSettle(); await tester.enterText(find.byKey(textField1), '3'); //scroll textField1 back into view await tester.pumpAndSettle(); expect(minOffset, 0.0); expect(maxOffset, 200.0); minOffset = null; maxOffset = null; await tester.pumpWidget(buildFrame(Axis.horizontal)); await tester.enterText(find.byKey(textField1), '1'); await tester.pumpAndSettle(); await tester.enterText(find.byKey(textField2), '2'); //scroll textField2 into view await tester.pumpAndSettle(); await tester.enterText(find.byKey(textField1), '3'); //scroll textField1 back into view await tester.pumpAndSettle(); expect(minOffset, 0.0); expect(maxOffset, 200.0); }); testWidgets('TextField scrolls into view but does not bounce (ListView)', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/20485 final Key textField1 = UniqueKey(); final Key textField2 = UniqueKey(); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); double? minOffset; double? maxOffset; scrollController.addListener(() { final double offset = scrollController.offset; minOffset = math.min(minOffset ?? offset, offset); maxOffset = math.max(maxOffset ?? offset, offset); }); Widget buildFrame(Axis scrollDirection) { return MaterialApp( home: Scaffold( body: SafeArea( child: ListView( physics: const BouncingScrollPhysics(), controller: scrollController, children: <Widget>[ SizedBox( // visible when scrollOffset is 0.0 height: 100.0, width: 100.0, child: TextField(key: textField1, scrollPadding: const EdgeInsets.all(200.0)), ), const SizedBox( height: 450.0, // 50.0 smaller than the overall frame so that both width: 650.0, // textfields are always partially visible. ), SizedBox( // visible when scrollOffset = 50.0 height: 100.0, width: 100.0, child: TextField(key: textField2, scrollPadding: const EdgeInsets.all(200.0)), ), ], ), ), ), ); } await tester.pumpWidget(buildFrame(Axis.vertical)); await tester.enterText(find.byKey(textField1), '1'); // textfield1 is visible await tester.pumpAndSettle(); await tester.enterText(find.byKey(textField2), '2'); //scroll textField2 into view await tester.pumpAndSettle(); await tester.enterText(find.byKey(textField1), '3'); //scroll textField1 back into view await tester.pumpAndSettle(); expect(minOffset, 0.0); expect(maxOffset, 50.0); minOffset = null; maxOffset = null; await tester.pumpWidget(buildFrame(Axis.horizontal)); await tester.enterText(find.byKey(textField1), '1'); // textfield1 is visible await tester.pumpAndSettle(); await tester.enterText(find.byKey(textField2), '2'); //scroll textField2 into view await tester.pumpAndSettle(); await tester.enterText(find.byKey(textField1), '3'); //scroll textField1 back into view await tester.pumpAndSettle(); expect(minOffset, 0.0); expect(maxOffset, 50.0); }); testWidgets('onTap is called upon tap', (WidgetTester tester) async { int tapCount = 0; await tester.pumpWidget( overlay( child: TextField( onTap: () { tapCount += 1; }, ), ), ); expect(tapCount, 0); await tester.tap(find.byType(TextField)); // Wait a bit so they're all single taps and not double taps. await tester.pump(const Duration(milliseconds: 300)); await tester.tap(find.byType(TextField)); await tester.pump(const Duration(milliseconds: 300)); await tester.tap(find.byType(TextField)); await tester.pump(const Duration(milliseconds: 300)); expect(tapCount, 3); }); testWidgets('onTap is not called, field is disabled', (WidgetTester tester) async { int tapCount = 0; await tester.pumpWidget( overlay( child: TextField( enabled: false, onTap: () { tapCount += 1; }, ), ), ); expect(tapCount, 0); await tester.tap(find.byType(TextField)); await tester.tap(find.byType(TextField)); await tester.tap(find.byType(TextField)); expect(tapCount, 0); }); testWidgets('Includes cursor for TextField', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/24612 Widget buildFrame({ double? stepWidth, required double cursorWidth, required TextAlign textAlign, }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ IntrinsicWidth( stepWidth: stepWidth, child: TextField( textAlign: textAlign, cursorWidth: cursorWidth, ), ), ], ), ), ), ); } // A cursor of default size doesn't cause the TextField to increase its // width. const String text = '1234'; double? stepWidth = 80.0; await tester.pumpWidget(buildFrame( stepWidth: 80.0, cursorWidth: 2.0, textAlign: TextAlign.left, )); await tester.enterText(find.byType(TextField), text); await tester.pumpAndSettle(); expect(tester.getSize(find.byType(TextField)).width, stepWidth); // A wide cursor is counted in the width of the text and causes the // TextField to increase to twice the stepWidth. await tester.pumpWidget(buildFrame( stepWidth: stepWidth, cursorWidth: 18.0, textAlign: TextAlign.left, )); await tester.enterText(find.byType(TextField), text); await tester.pumpAndSettle(); expect(tester.getSize(find.byType(TextField)).width, 2 * stepWidth); // A null stepWidth causes the TextField to perfectly wrap the text plus // the cursor regardless of alignment. stepWidth = null; const double WIDTH_OF_CHAR = 16.0; const double CARET_GAP = 1.0; await tester.pumpWidget(buildFrame( stepWidth: stepWidth, cursorWidth: 18.0, textAlign: TextAlign.left, )); await tester.enterText(find.byType(TextField), text); await tester.pumpAndSettle(); expect(tester.getSize(find.byType(TextField)).width, WIDTH_OF_CHAR * text.length + 18.0 + CARET_GAP); await tester.pumpWidget(buildFrame( stepWidth: stepWidth, cursorWidth: 18.0, textAlign: TextAlign.right, )); await tester.enterText(find.byType(TextField), text); await tester.pumpAndSettle(); expect(tester.getSize(find.byType(TextField)).width, WIDTH_OF_CHAR * text.length + 18.0 + CARET_GAP); }); testWidgets('TextField style is merged with theme', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/23994 final ThemeData themeData = ThemeData( useMaterial3: false, textTheme: TextTheme( titleMedium: TextStyle( color: Colors.blue[500], ), ), ); Widget buildFrame(TextStyle style) { return MaterialApp( theme: themeData, home: Material( child: Center( child: TextField( style: style, ), ), ), ); } // Empty TextStyle is overridden by theme await tester.pumpWidget(buildFrame(const TextStyle())); EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, themeData.textTheme.titleMedium!.color); expect(editableText.style.background, themeData.textTheme.titleMedium!.background); expect(editableText.style.shadows, themeData.textTheme.titleMedium!.shadows); expect(editableText.style.decoration, themeData.textTheme.titleMedium!.decoration); expect(editableText.style.locale, themeData.textTheme.titleMedium!.locale); expect(editableText.style.wordSpacing, themeData.textTheme.titleMedium!.wordSpacing); // Properties set on TextStyle override theme const Color setColor = Colors.red; await tester.pumpWidget(buildFrame(const TextStyle(color: setColor))); editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, setColor); // inherit: false causes nothing to be merged in from theme await tester.pumpWidget(buildFrame(const TextStyle( fontSize: 24.0, textBaseline: TextBaseline.alphabetic, inherit: false, ))); editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, isNull); }); testWidgets('TextField style is merged with theme in Material 3', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/23994 final ThemeData themeData = ThemeData( useMaterial3: true, textTheme: TextTheme( bodyLarge: TextStyle( color: Colors.blue[500], ), ), ); Widget buildFrame(TextStyle style) { return MaterialApp( theme: themeData, home: Material( child: Center( child: TextField( style: style, ), ), ), ); } // Empty TextStyle is overridden by theme await tester.pumpWidget(buildFrame(const TextStyle())); EditableText editableText = tester.widget(find.byType(EditableText)); // According to material 3 spec, the input text should be the color of onSurface. // https://github.com/flutter/flutter/issues/107686 is tracking this issue. expect(editableText.style.color, themeData.textTheme.bodyLarge!.color); expect(editableText.style.background, themeData.textTheme.bodyLarge!.background); expect(editableText.style.shadows, themeData.textTheme.bodyLarge!.shadows); expect(editableText.style.decoration, themeData.textTheme.bodyLarge!.decoration); expect(editableText.style.locale, themeData.textTheme.bodyLarge!.locale); expect(editableText.style.wordSpacing, themeData.textTheme.bodyLarge!.wordSpacing); // Properties set on TextStyle override theme const Color setColor = Colors.red; await tester.pumpWidget(buildFrame(const TextStyle(color: setColor))); editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, setColor); // inherit: false causes nothing to be merged in from theme await tester.pumpWidget(buildFrame(const TextStyle( fontSize: 24.0, textBaseline: TextBaseline.alphabetic, inherit: false, ))); editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, isNull); }); testWidgets('selection handles color respects Theme', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/74890. const Color expectedSelectionHandleColor = Color.fromARGB(255, 10, 200, 255); final TextEditingController controller = TextEditingController(text: 'Some text.'); addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( theme: ThemeData( textSelectionTheme: const TextSelectionThemeData( selectionHandleColor: Colors.red, ), ), home: Material( child: Theme( data: ThemeData( textSelectionTheme: const TextSelectionThemeData( selectionHandleColor: expectedSelectionHandleColor, ), ), child: TextField(controller: controller), ), ), ), ); await tester.longPressAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); final Iterable<RenderBox> boxes = tester.renderObjectList<RenderBox>( find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(CustomPaint), ), ); expect(boxes.length, 2); for (final RenderBox box in boxes) { expect(box, paints..path(color: expectedSelectionHandleColor)); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia }), ); testWidgets('style enforces required fields', (WidgetTester tester) async { Widget buildFrame(TextStyle style) { return MaterialApp( home: Material( child: TextField( style: style, ), ), ); } await tester.pumpWidget(buildFrame(const TextStyle( inherit: false, fontSize: 12.0, textBaseline: TextBaseline.alphabetic, ))); expect(tester.takeException(), isNull); // With inherit not set to false, will pickup required fields from theme await tester.pumpWidget(buildFrame(const TextStyle( fontSize: 12.0, ))); expect(tester.takeException(), isNull); await tester.pumpWidget(buildFrame(const TextStyle( inherit: false, fontSize: 12.0, ))); expect(tester.takeException(), isNotNull); }); testWidgets( 'tap moves cursor to the edge of the word it tapped', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(); // We moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); // But don't trigger the toolbar. expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'tap with a mouse does not move cursor to the edge of the word', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); final TestGesture gesture = await tester.startGesture( textfieldStart + const Offset(50.0, 9.0), pointer: 1, kind: PointerDeviceKind.mouse, ); await gesture.up(); // Cursor at tap position, not at word edge. expect( controller.selection, const TextSelection.collapsed(offset: 3), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('tap moves cursor to the position tapped', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(); // We moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 3), ); // But don't trigger the toolbar. expectNoMaterialToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows })); testWidgets( 'two slow taps do not trigger a word selection', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset pos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r'. await tester.tapAt(pos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(pos); await tester.pump(); // Plain collapsed selection. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformMobile ? 7 : 6); // Toolbar shows on mobile only. if (isTargetPlatformMobile) { expectCupertinoToolbarForCollapsedSelection(); } else { // After a tap, macOS does not show a selection toolbar for a collapsed selection. expectNoCupertinoToolbar(); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'Tapping on a collapsed selection toggles the toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neigse Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, maxLines: 2, ), ), ), ), ); final double lineHeight = findRenderEditable(tester).preferredLineHeight; final Offset begPos = textOffsetToPosition(tester, 0); final Offset endPos = textOffsetToPosition(tester, 35) + const Offset(200.0, 0.0); // Index of 'Bonaventure|' + Offset(200.0,0), which is at the end of the first line. final Offset vPos = textOffsetToPosition(tester, 29); // Index of 'Bonav|enture'. final Offset wPos = textOffsetToPosition(tester, 3); // Index of 'Atw|ater'. // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(wPos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(vPos); await tester.pump(const Duration(milliseconds: 500)); // First tap moved the cursor. Here we tap the position where 'v' is located. // On iOS this will select the closest word edge, in this case the cursor is placed // at the end of the word 'Bonaventure|'. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 35); expectNoCupertinoToolbar(); await tester.tapAt(vPos); await tester.pumpAndSettle(const Duration(milliseconds: 500)); // Second tap toggles the toolbar. Here we tap on 'v' again, and select the word edge. Since // the selection has not changed we toggle the toolbar. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 35); expectCupertinoToolbarForCollapsedSelection(); // Tap the 'v' position again to hide the toolbar. await tester.tapAt(vPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 35); expectNoCupertinoToolbar(); // Long press at the end of the first line to move the cursor to the end of the first line // where the word wrap is. Since there is a word wrap here, and the direction of the text is LTR, // the TextAffinity will be upstream and against the natural direction. The toolbar is also // shown after a long press. await tester.longPressAt(endPos); await tester.pumpAndSettle(const Duration(milliseconds: 500)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 46); expect(controller.selection.affinity, TextAffinity.upstream); expectCupertinoToolbarForCollapsedSelection(); // Tap at the same position to toggle the toolbar. await tester.tapAt(endPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 46); expect(controller.selection.affinity, TextAffinity.upstream); expectNoCupertinoToolbar(); // Tap at the beginning of the second line to move the cursor to the front of the first word on the // second line, where the word wrap is. Since there is a word wrap here, and the direction of the text is LTR, // the TextAffinity will be downstream and following the natural direction. The toolbar will be hidden after this tap. await tester.tapAt(begPos + Offset(0.0, lineHeight)); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 46); expect(controller.selection.affinity, TextAffinity.downstream); expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'Tapping on a non-collapsed selection toggles the toolbar and retains the selection', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset vPos = textOffsetToPosition(tester, 29); // Index of 'Bonav|enture'. final Offset ePos = textOffsetToPosition(tester, 35) + const Offset(7.0, 0.0); // Index of 'Bonaventure|' + Offset(7.0,0), which taps slightly to the right of the end of the text. final Offset wPos = textOffsetToPosition(tester, 3); // Index of 'Atw|ater'. // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(wPos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(vPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect(controller.selection.isCollapsed, true); expect( controller.selection.baseOffset, 35, ); await tester.tapAt(vPos); await tester.pumpAndSettle(const Duration(milliseconds: 500)); // Second tap selects the word around the cursor. expect( controller.selection, const TextSelection(baseOffset: 24, extentOffset: 35), ); // The toolbar shows up. expectCupertinoToolbarForPartialSelection(); // Tap the selected word to hide the toolbar and retain the selection. await tester.tapAt(vPos); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 24, extentOffset: 35), ); expectNoCupertinoToolbar(); // Tap the selected word to show the toolbar and retain the selection. await tester.tapAt(vPos); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 24, extentOffset: 35), ); expectCupertinoToolbarForPartialSelection(); // Tap past the selected word to move the cursor and hide the toolbar. await tester.tapAt(ePos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 35); expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'double tap selects word and first tap of double tap moves cursor (iOS)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset pPos = textOffsetToPosition(tester, 9); // Index of 'P|eel'. final Offset wPos = textOffsetToPosition(tester, 3); // Index of 'Atw|ater'. // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(wPos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.tapAt(pPos); await tester.pumpAndSettle(); // Second tap selects the word around the cursor. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // The toolbar shows up. expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('iOS selectWordEdge works correctly', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'blah1 blah2', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Initially, the menu is not shown and there is no selection. expect(controller.selection, const TextSelection(baseOffset: -1, extentOffset: -1)); final Offset pos1 = textOffsetToPosition(tester, 1); TestGesture gesture = await tester.startGesture(pos1); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection.collapsed(offset: 5, affinity: TextAffinity.upstream)); final Offset pos0 = textOffsetToPosition(tester, 0); gesture = await tester.startGesture(pos0); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection.collapsed(offset: 0)); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets( 'double tap does not select word on read-only obscured field', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( obscureText: true, readOnly: true, controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 35), ); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pumpAndSettle(); // Second tap doesn't select anything. expect( controller.selection, const TextSelection.collapsed(offset: 35), ); // Selected text shows no toolbar. expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'double tap selects word and first tap of double tap moves cursor and shows toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 9), ); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pumpAndSettle(); // Second tap selects the word around the cursor. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // The toolbar shows up. expectMaterialToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows }), ); testWidgets( 'Custom toolbar test - Android text selection controls', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, selectionControls: materialTextSelectionControls, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pumpAndSettle(); // Selected text shows 4 toolbar buttons: cut, copy, paste, select all expect(find.byType(TextButton), findsNWidgets(4)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); expect(find.text('Select all'), findsOneWidget); }, variant: TargetPlatformVariant.all(), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu., ); testWidgets( 'Custom toolbar test - Cupertino text selection controls', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, selectionControls: cupertinoTextSelectionControls, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pumpAndSettle(); // Selected text shows 3 toolbar buttons: cut, copy, paste expect(find.byType(CupertinoButton), findsNWidgets(3)); }, variant: TargetPlatformVariant.all(), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu., ); testWidgets('selectionControls is passed to EditableText', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Scaffold( body: TextField( selectionControls: materialTextSelectionControls, ), ), ), ), ); final EditableText widget = tester.widget(find.byType(EditableText)); expect(widget.selectionControls, equals(materialTextSelectionControls)); }); testWidgets( 'Can double click + drag with a mouse to select word by word', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset hPos = textOffsetToPosition(tester, testValue.indexOf('h')); // Tap on text field to gain focus, and set selection to '|e'. final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); // Here we tap on '|e' again, to register a double tap. This will select // the word at the tapped position. await gesture.down(ePos); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 7); // Drag, right after the double tap, to select word by word. // Moving to the position of 'h', will extend the selection to 'ghi'. await gesture.moveTo(hPos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, testValue.indexOf('d')); expect(controller.selection.extentOffset, testValue.indexOf('i') + 1); }, ); testWidgets( 'Can double tap + drag to select word by word', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset hPos = textOffsetToPosition(tester, testValue.indexOf('h')); // Tap on text field to gain focus, and set selection to '|e'. final TestGesture gesture = await tester.startGesture(ePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); // Here we tap on '|e' again, to register a double tap. This will select // the word at the tapped position. await gesture.down(ePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 7); // Drag, right after the double tap, to select word by word. // Moving to the position of 'h', will extend the selection to 'ghi'. await gesture.moveTo(hPos); await tester.pumpAndSettle(); // Toolbar should be hidden during a drag. expectNoMaterialToolbar(); expect(controller.selection.baseOffset, testValue.indexOf('d')); expect(controller.selection.extentOffset, testValue.indexOf('i') + 1); // Toolbar should re-appear after a drag. await gesture.up(); await tester.pump(); expectMaterialToolbarForPartialSelection(); }, ); group('Triple tap/click', () { const String testValueA = 'Now is the time for\n' // 20 'all good people\n' // 20 + 16 => 36 'to come to the aid\n' // 36 + 19 => 55 'of their country.'; // 55 + 17 => 72 const String testValueB = 'Today is the time for\n' // 22 'all good people\n' // 22 + 16 => 38 'to come to the aid\n' // 38 + 19 => 57 'of their country.'; // 57 + 17 => 74 testWidgets( 'Can triple tap to select a paragraph on mobile platforms when tapping at a word edge', (WidgetTester tester) async { // TODO(Renzo-Olivares): Enable for iOS, currently broken because selection overlay blocks the TextSelectionGestureDetector https://github.com/flutter/flutter/issues/123415. final TextEditingController controller = _textEditingController(); final bool isTargetPlatformApple = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(TextField), testValueA); await skipPastScrollingAnimation(tester); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 6); // Tap on text field to gain focus, and set selection to 'is|' on the first line. final TestGesture gesture = await tester.startGesture(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 6); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, isTargetPlatformApple ? 4 : 6); expect(controller.selection.extentOffset, isTargetPlatformApple ? 6 : 7); // Here we tap on same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 20); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia }), ); testWidgets( 'Can triple tap to select a paragraph on mobile platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); final bool isTargetPlatformApple = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(TextField), testValueB); await skipPastScrollingAnimation(tester); expect(controller.value.text, testValueB); final Offset firstLinePos = tester.getTopLeft(find.byType(TextField)) + const Offset(50.0, 9.0); // Tap on text field to gain focus, and move the selection. final TestGesture gesture = await tester.startGesture(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, isTargetPlatformApple ? 5 : 3); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 5); // Here we tap on same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 22); }, variant: TargetPlatformVariant.mobile(), ); testWidgets( 'Triple click at the beginning of a line should not select the previous paragraph', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/132126 final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(TextField), testValueB); await skipPastScrollingAnimation(tester); expect(controller.value.text, testValueB); final Offset thirdLinePos = textOffsetToPosition(tester, 38); // Click on text field to gain focus, and move the selection. final TestGesture gesture = await tester.startGesture(thirdLinePos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 38); // Here we click on same position again, to register a double click. This will select // the word at the clicked position. await gesture.down(thirdLinePos); await gesture.up(); expect(controller.selection.baseOffset, 38); expect(controller.selection.extentOffset, 40); // Here we click on same position again, to register a triple click. This will select // the paragraph at the clicked position. await gesture.down(thirdLinePos); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 38); expect(controller.selection.extentOffset, 57); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.linux }), ); testWidgets( 'Triple click at the end of text should select the previous paragraph', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/132126. final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(TextField), testValueB); await skipPastScrollingAnimation(tester); expect(controller.value.text, testValueB); final Offset endOfTextPos = textOffsetToPosition(tester, 74); // Click on text field to gain focus, and move the selection. final TestGesture gesture = await tester.startGesture(endOfTextPos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 74); // Here we click on same position again, to register a double click. await gesture.down(endOfTextPos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 74); expect(controller.selection.extentOffset, 74); // Here we click on same position again, to register a triple click. This will select // the paragraph at the clicked position. await gesture.down(endOfTextPos); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 57); expect(controller.selection.extentOffset, 74); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.linux }), ); testWidgets( 'triple tap chains work on Non-Apple mobile platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 3); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectMaterialToolbarForPartialSelection(); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 35), ); // Triple tap selecting the same paragraph somewhere else is fine. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap hides the toolbar and moves the selection. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 6); expectNoMaterialToolbar(); // Second tap shows the toolbar and selects the word. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectMaterialToolbarForPartialSelection(); // Third tap shows the toolbar and selects the paragraph. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 35), ); expectMaterialToolbarForFullSelection(); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor and hid the toolbar. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 9); expectNoMaterialToolbar(); // Second tap selects the word. await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectMaterialToolbarForPartialSelection(); // Third tap selects the paragraph and shows the toolbar. await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 35), ); expectMaterialToolbarForFullSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia }), ); testWidgets( 'triple tap chains work on Apple platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure\nThe fox jumped over the fence.', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 7); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 36), ); // Triple tap selecting the same paragraph somewhere else is fine. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap hides the toolbar and retains the selection. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 36), ); expectNoCupertinoToolbar(); // Second tap shows the toolbar and selects the word. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); // Third tap shows the toolbar and selects the paragraph. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 36), ); expectCupertinoToolbarForPartialSelection(); await tester.tapAt(textfieldStart + const Offset(150.0, 50.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor and hid the toolbar. expect( controller.selection, const TextSelection.collapsed(offset: 50, affinity: TextAffinity.upstream), ); expectNoCupertinoToolbar(); // Second tap selects the word. await tester.tapAt(textfieldStart + const Offset(150.0, 50.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 44, extentOffset: 50), ); expectCupertinoToolbarForPartialSelection(); // Third tap selects the paragraph and shows the toolbar. await tester.tapAt(textfieldStart + const Offset(150.0, 50.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 36, extentOffset: 66), ); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'triple click chains work', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: testValueA, ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(TextField)); final bool platformSelectsByLine = defaultTargetPlatform == TargetPlatform.linux; // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(210.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 13); // Second click selects the word. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); // Triple click selects the paragraph. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); // Wait for the consecutive tap timer to timeout so the next // tap is not detected as a triple tap. await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); // Triple click selecting the same paragraph somewhere else is fine. await gesture.down(textFieldStart + const Offset(100.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // First click moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 6), ); await gesture.down(textFieldStart + const Offset(100.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Second click selected the word. expect( controller.selection, const TextSelection(baseOffset: 6, extentOffset: 7), ); await gesture.down(textFieldStart + const Offset(100.0, 9.0)); await tester.pump(); await gesture.up(); // Wait for the consecutive tap timer to timeout so the tap count // is reset. await tester.pumpAndSettle(kDoubleTapTimeout); // Third click selected the paragraph. expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // First click moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 9), ); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Second click selected the word. expect( controller.selection, const TextSelection(baseOffset: 7, extentOffset: 10), ); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Third click selects the paragraph. expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); }, variant: TargetPlatformVariant.desktop(), ); testWidgets( 'triple click after a click on desktop platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: testValueA, ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(TextField)); final bool platformSelectsByLine = defaultTargetPlatform == TargetPlatform.linux; final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(50.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection.collapsed(offset: 3), ); // First click moves the selection. await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection.collapsed(offset: 9), ); // Double click selection to select a word. await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 7, extentOffset: 10), ); // Triple click selection to select a paragraph. await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); }, variant: TargetPlatformVariant.desktop(), ); testWidgets( 'Can triple tap to select all on a single-line textfield on mobile platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: testValueB, ); final bool isTargetPlatformApple = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final Offset firstLinePos = tester.getTopLeft(find.byType(TextField)) + const Offset(50.0, 9.0); // Tap on text field to gain focus, and set selection somewhere on the first word. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, isTargetPlatformApple ? 5 : 3); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 5); // Here we tap on same position again, to register a triple tap. This will select // the entire text field if it is a single-line field. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 74); }, variant: TargetPlatformVariant.mobile(), ); testWidgets( 'Can triple click to select all on a single-line textfield on desktop platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: testValueA, ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); final Offset firstLinePos = textOffsetToPosition(tester, 5); // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on same position again, to register a triple tap. This will select // the entire text field if it is a single-line field. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 72); }, variant: TargetPlatformVariant.desktop(), ); testWidgets( 'Can triple click to select a line on Linux', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(TextField), testValueA); await skipPastScrollingAnimation(tester); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 5); // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 19); }, variant: TargetPlatformVariant.only(TargetPlatform.linux), ); testWidgets( 'Can triple click to select a paragraph', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(TextField), testValueA); await skipPastScrollingAnimation(tester); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 5); // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 20); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.linux }), ); testWidgets( 'Can triple click + drag to select line by line on Linux', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(TextField), testValueA); await skipPastScrollingAnimation(tester); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 5); final double lineHeight = findRenderEditable(tester).preferredLineHeight; // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on the same position again, to register a triple tap. This will select // the line at the tapped position. await gesture.down(firstLinePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 19); // Drag, down after the triple tap, to select line by line. // Moving down will extend the selection to the second line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 35); // Moving down will extend the selection to the third line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight * 2)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 54); // Moving down will extend the selection to the last line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight * 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 72); // Moving up will extend the selection to the third line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight * 2)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 54); // Moving up will extend the selection to the second line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight * 1)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 35); // Moving up will extend the selection to the first line. await gesture.moveTo(firstLinePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 19); }, variant: TargetPlatformVariant.only(TargetPlatform.linux), ); testWidgets( 'Can triple click + drag to select paragraph by paragraph', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(TextField), testValueA); await skipPastScrollingAnimation(tester); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 5); final double lineHeight = findRenderEditable(tester).preferredLineHeight; // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on the same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 20); // Drag, down after the triple tap, to select paragraph by paragraph. // Moving down will extend the selection to the second line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 36); // Moving down will extend the selection to the third line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight * 2)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 55); // Moving down will extend the selection to the last line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight * 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 72); // Moving up will extend the selection to the third line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight * 2)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 55); // Moving up will extend the selection to the second line. await gesture.moveTo(firstLinePos + Offset(0, lineHeight)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 36); // Moving up will extend the selection to the first line. await gesture.moveTo(firstLinePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 20); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.linux }), ); testWidgets( 'Going past triple click retains the selection on Apple platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: testValueA, ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(TextField)); // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(210.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 13); // Second click selects the word. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); // Triple click selects the paragraph. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); // Clicking again retains the selection. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again retains the selection. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again retains the selection. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'Tap count resets when going past a triple tap on Android, Fuchsia, and Linux', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: testValueA, ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(TextField)); final bool platformSelectsByLine = defaultTargetPlatform == TargetPlatform.linux; // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(210.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 13); // Second click selects the word. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); // Triple click selects the paragraph. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); // Clicking again moves the caret to the tapped position. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 13); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again selects the word. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again selects the paragraph. expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // Clicking again moves the caret to the tapped position. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 13); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again selects the word. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again selects the paragraph. expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux }), ); testWidgets( 'Double click and triple click alternate on Windows', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: testValueA, ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(TextField)); // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(210.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 13); // Second click selects the word. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); // Triple click selects the paragraph. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); // Clicking again selects the word. await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again selects the paragraph. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again selects the word. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // Clicking again selects the paragraph. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again selects the word. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(210.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again selects the paragraph. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); }, variant: TargetPlatformVariant.only(TargetPlatform.windows), ); }); testWidgets( 'double tap on top of cursor also selects word', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); // Tap to put the cursor after the "w". const int index = 3; await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 500)); expect( controller.selection, const TextSelection.collapsed(offset: index), ); // Double tap on the same location. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); // First tap doesn't change the selection expect( controller.selection, const TextSelection.collapsed(offset: index), ); // Second tap selects the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); // The toolbar shows up. expectMaterialToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows }), ); testWidgets( 'double double tap just shows the selection menu', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); // Double tap on the same location shows the selection menu. await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); // Double tap again keeps the selection menu visible. await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu., ); testWidgets( 'double long press just shows the selection menu', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); // Long press shows the selection menu. await tester.longPressAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); // Long press again keeps the selection menu visible. await tester.longPressAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu., ); testWidgets( 'A single tap hides the selection menu', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); // Long press shows the selection menu. await tester.longPress(find.byType(TextField)); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); // Tap hides the selection menu. await tester.tap(find.byType(TextField)); await tester.pump(); expect(find.text('Paste'), findsNothing); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu., ); testWidgets('Drag selection hides the selection menu', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'blah1 blah2', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Initially, the menu is not shown and there is no selection. expect(controller.selection, const TextSelection(baseOffset: -1, extentOffset: -1)); final Offset midBlah1 = textOffsetToPosition(tester, 2); final Offset midBlah2 = textOffsetToPosition(tester, 8); // Right click the second word. final TestGesture gesture = await tester.startGesture( midBlah2, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // The toolbar is shown. expect(find.text('Paste'), findsOneWidget); // Drag the mouse to the first word. final TestGesture gesture2 = await tester.startGesture( midBlah1, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture2.moveTo(midBlah2); await tester.pump(); await gesture2.up(); await tester.pumpAndSettle(); // The toolbar is hidden. expect(find.text('Paste'), findsNothing); }, variant: TargetPlatformVariant.desktop(), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets( 'Long press on an autofocused field shows the selection menu', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( autofocus: true, controller: controller, ), ), ), ), ); // This extra pump allows the selection set by autofocus to propagate to // the RenderEditable. await tester.pump(); // Long press shows the selection menu. expect(find.text('Paste'), findsNothing); await tester.longPress(find.byType(TextField)); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu., ); testWidgets( 'double tap hold selects word', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); final TestGesture gesture = await tester.startGesture(textfieldStart + const Offset(150.0, 9.0)); // Hold the press. await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // The toolbar shows up. expectCupertinoToolbarForPartialSelection(); await gesture.up(); await tester.pump(); // Still selected. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // The toolbar is still showing. expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'tap after a double tap select is not affected', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset pPos = textOffsetToPosition(tester, 9); // Index of 'P|eel'. final Offset ePos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r' await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, isTargetPlatformMobile ? const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream) : const TextSelection.collapsed(offset: 9), ); await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(ePos); await tester.pump(); // Plain collapsed selection at the edge of first word on iOS. In iOS 12, // the first tap after a double tap ends up putting the cursor at where // you tapped instead of the edge like every other single tap. This is // likely a bug in iOS 12 and not present in other versions. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformMobile ? 7 : 6); // No toolbar. expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press moves cursor to the exact long press position and shows toolbar when the field is focused', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( autofocus: true, controller: controller, ), ), ), ), ); // This extra pump allows the selection set by autofocus to propagate to // the RenderEditable. await tester.pump(); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.longPressAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); // Collapsed cursor for iOS long press. expect( controller.selection, const TextSelection.collapsed(offset: 3), ); expectCupertinoToolbarForCollapsedSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press that starts on an unfocused TextField selects the word at the exact long press position and shows toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.longPressAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); // Collapsed cursor for iOS long press. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); // The toolbar shows up. expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press selects word and shows toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.longPressAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); // The toolbar shows up. expectMaterialToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows }), ); testWidgets( 'Toolbar hides on scroll start and re-appears on scroll end on Android and iOS', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure ' * 20, ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.longPressAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); // Long press should select word at position and show toolbar. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); final bool targetPlatformIsiOS = defaultTargetPlatform == TargetPlatform.iOS; final Finder contextMenuButtonFinder = targetPlatformIsiOS ? find.byType(CupertinoButton) : find.byType(TextButton); // Context menu shows 5 buttons: cut, copy, paste, select all, share on Android. // Context menu shows 6 buttons: cut, copy, paste, select all, lookup, share on iOS. final int numberOfContextMenuButtons = targetPlatformIsiOS ? 6 : 5; expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); // Scroll to the left, the toolbar should be hidden since we are scrolling. final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(TextField))); await tester.pump(); await gesture.moveTo(tester.getBottomLeft(find.byType(TextField))); await tester.pumpAndSettle(); expect(contextMenuButtonFinder, findsNothing); // Scroll back to center, the toolbar should still be hidden since // we are still scrolling. await gesture.moveTo(tester.getCenter(find.byType(TextField))); await tester.pumpAndSettle(); expect(contextMenuButtonFinder, findsNothing); // Release finger to end scroll, toolbar should now be visible. await gesture.up(); await tester.pumpAndSettle(); expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); expect(renderEditable.selectionStartInViewport.value, true); expect(renderEditable.selectionEndInViewport.value, true); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }), ); testWidgets( 'Toolbar hides on parent scrollable scroll start and re-appears on scroll end on Android and iOS', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure ' * 20, ); final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: ListView( children: <Widget>[ Container( height: 400, key: key1, ), TextField(controller: controller), Container( height: 1000, key: key2, ), ], ), ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.longPressAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); // Long press should select word at position and show toolbar. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); final bool targetPlatformIsiOS = defaultTargetPlatform == TargetPlatform.iOS; final Finder contextMenuButtonFinder = targetPlatformIsiOS ? find.byType(CupertinoButton) : find.byType(TextButton); // Context menu shows 5 buttons: cut, copy, paste, select all, share on Android. // Context menu shows 6 buttons: cut, copy, paste, select all, lookup, share on iOS. final int numberOfContextMenuButtons = targetPlatformIsiOS ? 6 : 5; expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); // Scroll down, the toolbar should be hidden since we are scrolling. final TestGesture gesture = await tester.startGesture(tester.getBottomLeft(find.byKey(key1))); await tester.pump(); await gesture.moveTo(tester.getTopLeft(find.byKey(key1))); await tester.pumpAndSettle(); expect(contextMenuButtonFinder, findsNothing); // Release finger to end scroll, toolbar should now be visible. await gesture.up(); await tester.pumpAndSettle(); expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); expect(renderEditable.selectionStartInViewport.value, true); expect(renderEditable.selectionEndInViewport.value, true); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }), ); testWidgets( 'Toolbar can re-appear after being scrolled out of view on Android and iOS', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure ' * 20, ); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, scrollController: scrollController, ), ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); expect(renderEditable.selectionStartInViewport.value, false); expect(renderEditable.selectionEndInViewport.value, false); await tester.longPressAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); // Long press should select word at position and show toolbar. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); final bool targetPlatformIsiOS = defaultTargetPlatform == TargetPlatform.iOS; final Finder contextMenuButtonFinder = targetPlatformIsiOS ? find.byType(CupertinoButton) : find.byType(TextButton); // Context menu shows 5 buttons: cut, copy, paste, select all, share on Android. // Context menu shows 6 buttons: cut, copy, paste, select all, lookup, share on iOS. final int numberOfContextMenuButtons = targetPlatformIsiOS ? 6 : 5; expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); expect(renderEditable.selectionStartInViewport.value, true); expect(renderEditable.selectionEndInViewport.value, true); // Scroll to the end so the selection is no longer visible. This should // hide the toolbar, but schedule it to be shown once the selection is // visible again. scrollController.animateTo( 500.0, duration: const Duration(milliseconds: 100), curve: Curves.linear, ); await tester.pumpAndSettle(); expect(contextMenuButtonFinder, findsNothing); expect(renderEditable.selectionStartInViewport.value, false); expect(renderEditable.selectionEndInViewport.value, false); // Scroll to the beginning where the selection is in view // and the toolbar should show again. scrollController.animateTo( 0.0, duration: const Duration(milliseconds: 100), curve: Curves.linear, ); await tester.pumpAndSettle(); expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); expect(renderEditable.selectionStartInViewport.value, true); expect(renderEditable.selectionEndInViewport.value, true); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 0)); await tester.pump(); await gesture.up(); await gesture.down(textOffsetToPosition(tester, 0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Double tap should select word at position and show toolbar. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); expect(renderEditable.selectionStartInViewport.value, true); expect(renderEditable.selectionEndInViewport.value, true); // Scroll to the end so the selection is no longer visible. This should // hide the toolbar, but schedule it to be shown once the selection is // visible again. scrollController.animateTo( 500.0, duration: const Duration(milliseconds: 100), curve: Curves.linear, ); await tester.pumpAndSettle(); expect(contextMenuButtonFinder, findsNothing); expect(renderEditable.selectionStartInViewport.value, false); expect(renderEditable.selectionEndInViewport.value, false); // Tap to change the selection. This will invalidate the scheduled // toolbar. await gesture.down(tester.getCenter(find.byType(TextField))); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Scroll to the beginning where the selection was previously // and the toolbar should not show because it was invalidated. scrollController.animateTo( 0.0, duration: const Duration(milliseconds: 100), curve: Curves.linear, ); await tester.pumpAndSettle(); expect(contextMenuButtonFinder, findsNothing); expect(renderEditable.selectionStartInViewport.value, false); expect(renderEditable.selectionEndInViewport.value, false); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }), ); testWidgets( 'Toolbar can re-appear after parent scrollable scrolls selection out of view on Android and iOS', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final Key key1 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: ListView( controller: scrollController, children: <Widget>[ TextField(controller: controller), Container( height: 1500.0, key: key1, ), ], ), ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.longPressAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); // Long press should select word at position and show toolbar. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); final bool targetPlatformIsiOS = defaultTargetPlatform == TargetPlatform.iOS; final Finder contextMenuButtonFinder = targetPlatformIsiOS ? find.byType(CupertinoButton) : find.byType(TextButton); // Context menu shows 5 buttons: cut, copy, paste, select all, share on Android. // Context menu shows 6 buttons: cut, copy, paste, select all, lookup, share on iOS. final int numberOfContextMenuButtons = targetPlatformIsiOS ? 6 : 5; expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); // Scroll down, the TextField should no longer be in the viewport. scrollController.animateTo( scrollController.position.maxScrollExtent, duration: const Duration(milliseconds: 100), curve: Curves.linear, ); await tester.pumpAndSettle(); expect(find.byType(TextField), findsNothing); expect(contextMenuButtonFinder, findsNothing); // Scroll back up so the TextField is inside the viewport. scrollController.animateTo( 0.0, duration: const Duration(milliseconds: 100), curve: Curves.linear, ); await tester.pumpAndSettle(); expect(find.byType(TextField), findsOneWidget); expect( contextMenuButtonFinder, isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(numberOfContextMenuButtons), ); expect(renderEditable.selectionStartInViewport.value, true); expect(renderEditable.selectionEndInViewport.value, true); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }), ); testWidgets( 'long press tap cannot initiate a double tap', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( autofocus: true, controller: controller, ), ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final Offset ePos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r' await tester.longPressAt(ePos); await tester.pumpAndSettle(const Duration(milliseconds: 50)); // Tap slightly behind the previous tap to avoid tapping the context menu // on desktop. final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.iOS; final Offset secondTapPos = isTargetPlatformMobile ? ePos : ePos + const Offset(-1.0, 0.0); await tester.tapAt(secondTapPos); await tester.pump(); // The cursor does not move and the toolbar is toggled. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 6); // The toolbar from the long press is now dismissed by the second tap. expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press drag extends the selection to the word under the drag and shows toolbar on lift on non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 18)); await tester.pump(const Duration(milliseconds: 500)); // Long press selects the word at the long presses position. expect( controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23), ); // Cursor move doesn't trigger a toolbar initially. expectNoMaterialToolbar(); await gesture.moveBy(const Offset(100, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection(baseOffset: 13, extentOffset: 35), ); // Still no toolbar. expectNoMaterialToolbar(); // The selection is moved on a backwards drag. await gesture.moveBy(const Offset(-200, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection(baseOffset: 23, extentOffset: 8), ); // Still no toolbar. expectNoMaterialToolbar(); await gesture.moveBy(const Offset(-100, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection(baseOffset: 23, extentOffset: 0), ); // Still no toolbar. expectNoMaterialToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection(baseOffset: 23, extentOffset: 0), ); // The toolbar now shows up. expectMaterialToolbarForPartialSelection(); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press drag on a focused TextField moves the cursor under the drag and shows toolbar on lift', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( autofocus: true, controller: controller, ), ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); final TestGesture gesture = await tester.startGesture(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 500)); // Long press on iOS shows collapsed selection cursor. expect( controller.selection, const TextSelection.collapsed(offset: 3), ); // Cursor move doesn't trigger a toolbar initially. expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(50, 0)); await tester.pump(); // The selection position is now moved with the drag. expect( controller.selection, const TextSelection.collapsed(offset: 6), ); // Still no toolbar. expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(50, 0)); await tester.pump(); // The selection position is now moved with the drag. expect( controller.selection, const TextSelection.collapsed(offset: 9), ); // Still no toolbar. expectNoCupertinoToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection.collapsed(offset: 9), ); // The toolbar now shows up. expectCupertinoToolbarForCollapsedSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press drag on an unfocused TextField selects word-by-word and shows toolbar on lift', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); final TestGesture gesture = await tester.startGesture(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 500)); // Long press on iOS shows collapsed selection cursor. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); // Cursor move doesn't trigger a toolbar initially. expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(100, 0)); await tester.pump(); // The selection position is now moved with the drag. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 12), ); // Still no toolbar. expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(100, 0)); await tester.pump(); // The selection position is now moved with the drag. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 23), ); // Still no toolbar. expectNoCupertinoToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 23), ); // The toolbar now shows up. expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('long press drag can edge scroll on non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // Just testing the text and making sure that the last character is off // the right side of the screen. expect(lastCharEndpoint[0].point.dx, 1056); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); final TestGesture gesture = await tester.startGesture(textfieldStart); await tester.pump(const Duration(milliseconds: 500)); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7, affinity: TextAffinity.upstream), ); expectNoMaterialToolbar(); await gesture.moveBy(const Offset(900, 5)); // To the edge of the screen basically. await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 59), ); // Keep moving out. await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66), ); await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66, affinity: TextAffinity.upstream), ); // We're at the edge now. expectNoMaterialToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66, affinity: TextAffinity.upstream), ); // The toolbar now shows up. expectMaterialToolbarForFullSelection(); lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // The last character is now on screen near the right edge. expect(lastCharEndpoint[0].point.dx, moreOrLessEquals(798, epsilon: 1)); final List<TextSelectionPoint> firstCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 0), // First character's position. ); expect(firstCharEndpoint.length, 1); // The first character is now offscreen to the left. expect(firstCharEndpoint[0].point.dx, moreOrLessEquals(-257.0, epsilon: 1)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows })); testWidgets('long press drag can edge scroll on Apple platforms - unfocused TextField', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // Just testing the test and making sure that the last character is off // the right side of the screen. expect(lastCharEndpoint[0].point.dx, 1056); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); final TestGesture gesture = await tester.startGesture(textfieldStart); await tester.pump(const Duration(milliseconds: 500)); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7, affinity: TextAffinity.upstream), ); expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(900, 5)); // To the edge of the screen basically. await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 59), ); // Keep moving out. await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66), ); await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66, affinity: TextAffinity.upstream), ); // We're at the edge now. expectNoCupertinoToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66, affinity: TextAffinity.upstream), ); // The toolbar now shows up. expectCupertinoToolbarForFullSelection(); lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // The last character is now on screen near the right edge. expect(lastCharEndpoint[0].point.dx, moreOrLessEquals(798, epsilon: 1)); final List<TextSelectionPoint> firstCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 0), // First character's position. ); expect(firstCharEndpoint.length, 1); // The first character is now offscreen to the left. expect(firstCharEndpoint[0].point.dx, moreOrLessEquals(-257.0, epsilon: 1)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('long press drag can edge scroll on Apple platforms - focused TextField', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( autofocus: true, controller: controller, ), ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // Just testing the test and making sure that the last character is off // the right side of the screen. expect(lastCharEndpoint[0].point.dx, 1056); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); final TestGesture gesture = await tester.startGesture(textfieldStart + const Offset(300, 5)); await tester.pump(const Duration(milliseconds: 500)); expect( controller.selection, const TextSelection.collapsed(offset: 19, affinity: TextAffinity.upstream), ); expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(600, 0)); // To the edge of the screen basically. await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 56), ); // Keep moving out. await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 62), ); await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 66, affinity: TextAffinity.upstream), ); // We're at the edge now. expectNoCupertinoToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection.collapsed(offset: 66, affinity: TextAffinity.upstream), ); // The toolbar now shows up. expectCupertinoToolbarForCollapsedSelection(); lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // The last character is now on screen near the right edge. expect(lastCharEndpoint[0].point.dx, moreOrLessEquals(798, epsilon: 1)); final List<TextSelectionPoint> firstCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 0), // First character's position. ); expect(firstCharEndpoint.length, 1); // The first character is now offscreen to the left. expect(firstCharEndpoint[0].point.dx, moreOrLessEquals(-257.0, epsilon: 1)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('mouse click and drag can edge scroll', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Size screenSize = MediaQuery.of(tester.element(find.byType(TextField))).size; // Just testing the test and making sure that the last character is off // the right side of the screen. expect(textOffsetToPosition(tester, 66).dx, greaterThan(screenSize.width)); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 19), pointer: 7, kind: PointerDeviceKind.mouse, ); await gesture.moveTo(textOffsetToPosition(tester, 56)); // To the edge of the screen basically. await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 19, extentOffset: 56), ); // Keep moving out. await gesture.moveTo(textOffsetToPosition(tester, 62)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 19, extentOffset: 62), ); await gesture.moveTo(textOffsetToPosition(tester, 66)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 19, extentOffset: 66), ); // We're at the edge now. expectNoCupertinoToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection(baseOffset: 19, extentOffset: 66), ); // The last character is now on screen near the right edge. expect( textOffsetToPosition(tester, 66).dx, moreOrLessEquals(TestSemantics.fullScreen.width, epsilon: 2.0), ); // The first character is now offscreen to the left. expect(textOffsetToPosition(tester, 0).dx, lessThan(-100.0)); }, variant: TargetPlatformVariant.all()); testWidgets('keyboard selection change scrolls the field', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); // Just testing the test and making sure that the last character is off // the right side of the screen. expect(textOffsetToPosition(tester, 66).dx, 1056); await tester.tapAt(textOffsetToPosition(tester, 13)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 13), ); // Move to position 56 with the right arrow (near the edge of the screen). for (int i = 0; i < (56 - 13); i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); } await tester.pumpAndSettle(); expect( controller.selection, // arrowRight always sets the affinity to downstream. const TextSelection.collapsed(offset: 56), ); // Keep moving out. for (int i = 0; i < (62 - 56); i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); } await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 62), ); for (int i = 0; i < (66 - 62); i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); } await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 66), ); // We're at the edge now. await tester.pumpAndSettle(); // The last character is now on screen near the right edge. expect( textOffsetToPosition(tester, 66).dx, moreOrLessEquals(TestSemantics.fullScreen.width, epsilon: 2.0), ); // The first character is now offscreen to the left. expect(textOffsetToPosition(tester, 0).dx, moreOrLessEquals(-257.0, epsilon: 1)); }, variant: TargetPlatformVariant.all(), skip: isBrowser, // [intended] Browser handles arrow keys differently. ); testWidgets('long press drag can edge scroll vertically', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neigse Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( autofocus: true, maxLines: 2, controller: controller, ), ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); // Just testing the test and making sure that the last character is outside // the bottom of the field. final int textLength = controller.text.length; final double lineHeight = findRenderEditable(tester).preferredLineHeight; final double firstCharY = textOffsetToPosition(tester, 0).dy; expect( textOffsetToPosition(tester, textLength).dy, moreOrLessEquals(firstCharY + lineHeight * 2, epsilon: 1), ); // Start long pressing on the first line. final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 19)); await tester.pump(const Duration(milliseconds: 500)); expect( controller.selection, const TextSelection.collapsed(offset: 19), ); await tester.pumpAndSettle(); // Move down to the second line. await gesture.moveBy(Offset(0.0, lineHeight)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 65), ); // Still hasn't scrolled. expect( textOffsetToPosition(tester, 65).dy, moreOrLessEquals(firstCharY + lineHeight, epsilon: 1), ); // Keep selecting down to the third and final line. await gesture.moveBy(Offset(0.0, lineHeight)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 110), ); // The last character is no longer three line heights down from the top of // the field, it's now only two line heights down, because it has scrolled // down by one line. expect( textOffsetToPosition(tester, 110).dy, moreOrLessEquals(firstCharY + lineHeight, epsilon: 1), ); // Likewise, the first character is now scrolled out of the top of the field // by one line. expect( textOffsetToPosition(tester, 0).dy, moreOrLessEquals(firstCharY - lineHeight, epsilon: 1), ); // End gesture and skip the magnifier hide animation, so it can release // resources. await gesture.up(); await tester.pumpAndSettle(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('keyboard selection change scrolls the field vertically', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( maxLines: 2, controller: controller, ), ), ), ), ); // Just testing the test and making sure that the last character is outside // the bottom of the field. final int textLength = controller.text.length; final double lineHeight = findRenderEditable(tester).preferredLineHeight; final double firstCharY = textOffsetToPosition(tester, 0).dy; expect( textOffsetToPosition(tester, textLength).dy, moreOrLessEquals(firstCharY + lineHeight * 2, epsilon: 1), ); await tester.tapAt(textOffsetToPosition(tester, 13)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 13), ); // Move down to the second line. await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 59), ); // Still hasn't scrolled. expect( textOffsetToPosition(tester, 66).dy, moreOrLessEquals(firstCharY + lineHeight, epsilon: 1), ); // Move down to the third and final line. await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 104), ); // The last character is no longer three line heights down from the top of // the field, it's now only two line heights down, because it has scrolled // down by one line. expect( textOffsetToPosition(tester, textLength).dy, moreOrLessEquals(firstCharY + lineHeight, epsilon: 1), ); // Likewise, the first character is now scrolled out of the top of the field // by one line. expect( textOffsetToPosition(tester, 0).dy, moreOrLessEquals(firstCharY - lineHeight, epsilon: 1), ); }, variant: TargetPlatformVariant.all(), skip: isBrowser, // [intended] Browser handles arrow keys differently. ); testWidgets('mouse click and drag can edge scroll vertically', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( maxLines: 2, controller: controller, ), ), ), ), ); // Just testing the test and making sure that the last character is outside // the bottom of the field. final int textLength = controller.text.length; final double lineHeight = findRenderEditable(tester).preferredLineHeight; final double firstCharY = textOffsetToPosition(tester, 0).dy; expect( textOffsetToPosition(tester, textLength).dy, moreOrLessEquals(firstCharY + lineHeight * 2, epsilon: 1), ); // Start selecting on the first line. final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 19), pointer: 7, kind: PointerDeviceKind.mouse, ); // Still hasn't scrolled. expect( textOffsetToPosition(tester, 60).dy, moreOrLessEquals(firstCharY + lineHeight, epsilon: 1), ); // Select down to the second line. await gesture.moveBy(Offset(0.0, lineHeight)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 19, extentOffset: 65), ); // Still hasn't scrolled. expect( textOffsetToPosition(tester, 60).dy, moreOrLessEquals(firstCharY + lineHeight, epsilon: 1), ); // Keep selecting down to the third and final line. await gesture.moveBy(Offset(0.0, lineHeight)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 19, extentOffset: 110), ); // The last character is no longer three line heights down from the top of // the field, it's now only two line heights down, because it has scrolled // down by one line. expect( textOffsetToPosition(tester, textLength).dy, moreOrLessEquals(firstCharY + lineHeight, epsilon: 1), ); // Likewise, the first character is now scrolled out of the top of the field // by one line. expect( textOffsetToPosition(tester, 0).dy, moreOrLessEquals(firstCharY - lineHeight, epsilon: 1), ); }, variant: TargetPlatformVariant.all()); testWidgets( 'long tap after a double tap select is not affected', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset pPos = textOffsetToPosition(tester, 9); // Index of 'P|eel' final Offset ePos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r' await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor to the beginning of the second word. expect( controller.selection, isTargetPlatformMobile ? const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream) : const TextSelection.collapsed(offset: 9), ); await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 500)); await tester.longPressAt(ePos); await tester.pumpAndSettle(); // Plain collapsed selection at the exact tap position. expect( controller.selection, const TextSelection.collapsed(offset: 6), ); // The toolbar shows up. expectCupertinoToolbarForCollapsedSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'double tap after a long tap is not affected', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( autofocus: true, controller: controller, ), ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); // The second tap is slightly higher to avoid tapping the context menu on // desktop. final Offset pPos = textOffsetToPosition(tester, 9) + const Offset(0.0, -20.0); // Index of 'P|eel' final Offset wPos = textOffsetToPosition(tester, 3); // Index of 'Atw|ater' await tester.longPressAt(wPos); await tester.pumpAndSettle(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection.collapsed(offset: 3), ); await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, isTargetPlatformMobile ? const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream) : const TextSelection.collapsed(offset: 9), ); await tester.tapAt(pPos); await tester.pumpAndSettle(); // Double tap selection. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'double click after a click on desktop platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(TextField)); final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(50.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection.collapsed(offset: 3), ); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // First click moved the cursor to the precise location, not the start of // the word. expect( controller.selection, const TextSelection.collapsed(offset: 9), ); // Double click selection. await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // The text selection toolbar isn't shown on Mac without a right click. expectNoCupertinoToolbar(); }, variant: TargetPlatformVariant.desktop(), ); testWidgets( 'double tap chains work', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); // Double tap selecting the same word somewhere else is fine. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap hides the toolbar and retains the selection. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectNoCupertinoToolbar(); // Second tap shows the toolbar and retains the selection. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); // Wait for the consecutive tap timer to timeout so the next // tap is not detected as a triple tap. await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor and hid the toolbar. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream) ); expectNoCupertinoToolbar(); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'double click chains work', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(TextField)); // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(50.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection.collapsed(offset: 3), ); // Second click selects. await gesture.down(textFieldStart + const Offset(50.0, 9.0)); await tester.pump(); await gesture.up(); // Wait for the consecutive tap timer to timeout so the next // tap is not detected as a triple tap. await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectNoCupertinoToolbar(); // Double tap selecting the same word somewhere else is fine. await gesture.down(textFieldStart + const Offset(100.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 6), ); await gesture.down(textFieldStart + const Offset(100.0, 9.0)); await tester.pump(); await gesture.up(); // Wait for the consecutive tap timer to timeout so the next // tap is not detected as a triple tap. await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectNoCupertinoToolbar(); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 9), ); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.windows, TargetPlatform.linux }), ); testWidgets('double tapping a space selects the previous word on iOS', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: ' blah blah \n blah', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( maxLines: null, controller: controller, ), ), ), ), ); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, -1); expect(controller.value.selection.extentOffset, -1); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 19)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 19); expect(controller.value.selection.extentOffset, 19); // Double tapping does the same thing. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.extentOffset, 5); expect(controller.value.selection.baseOffset, 1); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 19)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 19); expect(controller.value.selection.extentOffset, 19); // Double tapping does the same thing for the first space. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 0); expect(controller.value.selection.extentOffset, 1); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 19)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 19); expect(controller.value.selection.extentOffset, 19); // Double tapping the last space selects all previous contiguous spaces on // both lines and the previous word. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 14)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 14)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 6); expect(controller.value.selection.extentOffset, 14); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets('selecting a space selects the space on non-iOS platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: ' blah blah', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, -1); expect(controller.value.selection.extentOffset, -1); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 10)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 10); expect(controller.value.selection.extentOffset, 10); // Double tapping the second space selects it. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 5); expect(controller.value.selection.extentOffset, 6); // Tap at the end of the text to move the selection to the end. On some // platforms, the context menu "Cut" button blocks this tap, so move it out // of the way by an Offset. await tester.tapAt(textOffsetToPosition(tester, 10) + const Offset(200.0, 0.0)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 10); expect(controller.value.selection.extentOffset, 10); // Double tapping the second space selects it. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 0); expect(controller.value.selection.extentOffset, 1); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia, TargetPlatform.android })); testWidgets('selecting a space selects the space on Desktop platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: ' blah blah', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, -1); expect(controller.value.selection.extentOffset, -1); // Put the cursor at the end of the field. final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 10), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 10); expect(controller.value.selection.extentOffset, 10); // Double clicking the second space selects it. await tester.pump(const Duration(milliseconds: 500)); await gesture.down(textOffsetToPosition(tester, 5)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); await gesture.down(textOffsetToPosition(tester, 5)); await tester.pump(); await gesture.up(); // Wait for the consecutive tap timer to timeout so our next tap is not // detected as a triple tap. await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 5); expect(controller.value.selection.extentOffset, 6); // Put the cursor at the end of the field. await gesture.down(textOffsetToPosition(tester, 10)); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 10); expect(controller.value.selection.extentOffset, 10); // Double tapping the second space selects it. await tester.pump(const Duration(milliseconds: 500)); await gesture.down(textOffsetToPosition(tester, 0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); await gesture.down(textOffsetToPosition(tester, 0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 0); expect(controller.value.selection.extentOffset, 1); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.windows, TargetPlatform.linux })); testWidgets('Force press does not set selection on Android or Fuchsia touch devices', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final Offset offset = tester.getTopLeft(find.byType(TextField)) + const Offset(150.0, 9.0); final int pointerValue = tester.nextPointer; final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( offset, PointerDownEvent( pointer: pointerValue, position: offset, pressure: 0.0, pressureMax: 6.0, pressureMin: 0.0, ), ); await gesture.updateWithCustomEvent(PointerMoveEvent( pointer: pointerValue, position: offset + const Offset(150.0, 9.0), pressure: 0.5, pressureMin: 0, )); await gesture.up(); await tester.pump(); // We don't want this gesture to select any word on Android. expect(controller.selection, const TextSelection.collapsed(offset: -1)); expectNoMaterialToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia })); testWidgets('Force press sets selection on desktop platforms that do not support it', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final Offset offset = tester.getTopLeft(find.byType(TextField)) + const Offset(150.0, 9.0); final int pointerValue = tester.nextPointer; final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( offset, PointerDownEvent( pointer: pointerValue, position: offset, pressure: 0.0, pressureMax: 6.0, pressureMin: 0.0, ), ); await gesture.updateWithCustomEvent(PointerMoveEvent( pointer: pointerValue, position: offset + const Offset(150.0, 9.0), pressure: 0.5, pressureMin: 0, )); await gesture.up(); await tester.pump(); // We don't want this gesture to select any word on Android. expect(controller.selection, const TextSelection.collapsed(offset: 9)); expectNoMaterialToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux, TargetPlatform.windows })); testWidgets('force press selects word', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); final int pointerValue = tester.nextPointer; final Offset offset = textfieldStart + const Offset(150.0, 9.0); final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( offset, PointerDownEvent( pointer: pointerValue, position: offset, pressure: 0.0, pressureMax: 6.0, pressureMin: 0.0, ), ); await gesture.updateWithCustomEvent( PointerMoveEvent( pointer: pointerValue, position: textfieldStart + const Offset(150.0, 9.0), pressure: 0.5, pressureMin: 0, ), ); // We expect the force press to select a word at the given location. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); await gesture.up(); await tester.pumpAndSettle(); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets('tap on non-force-press-supported devices work', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget(Container(key: GlobalKey())); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); final int pointerValue = tester.nextPointer; final Offset offset = textfieldStart + const Offset(150.0, 9.0); final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( offset, PointerDownEvent( pointer: pointerValue, position: offset, // iPhone 6 and below report 0 across the board. pressure: 0, pressureMax: 0, pressureMin: 0, ), ); await gesture.updateWithCustomEvent( PointerMoveEvent( pointer: pointerValue, position: textfieldStart + const Offset(150.0, 9.0), pressure: 0.5, pressureMin: 0, ), ); await gesture.up(); // The event should fallback to a normal tap and move the cursor. // Single taps selects the edge of the word. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.pump(); // Single taps shouldn't trigger the toolbar. expectNoCupertinoToolbar(); // TODO(gspencergoog): Add in TargetPlatform.macOS in the line below when we figure out what global state is leaking. // https://github.com/flutter/flutter/issues/43445 }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets('default TextField debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const TextField().debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>[]); }); testWidgets('TextField implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); // Not checking controller, inputFormatters, focusNode const TextField( decoration: InputDecoration(labelText: 'foo'), keyboardType: TextInputType.text, textInputAction: TextInputAction.done, style: TextStyle(color: Color(0xff00ff00)), textAlign: TextAlign.end, textDirection: TextDirection.ltr, autofocus: true, autocorrect: false, maxLines: 10, maxLength: 100, maxLengthEnforcement: MaxLengthEnforcement.none, smartDashesType: SmartDashesType.disabled, smartQuotesType: SmartQuotesType.disabled, enabled: false, cursorWidth: 1.0, cursorHeight: 1.0, cursorRadius: Radius.zero, cursorColor: Color(0xff00ff00), keyboardAppearance: Brightness.dark, scrollPadding: EdgeInsets.zero, scrollPhysics: ClampingScrollPhysics(), enableInteractiveSelection: false, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>[ 'enabled: false', 'decoration: InputDecoration(labelText: "foo")', 'style: TextStyle(inherit: true, color: Color(0xff00ff00))', 'autofocus: true', 'autocorrect: false', 'smartDashesType: disabled', 'smartQuotesType: disabled', 'maxLines: 10', 'maxLength: 100', 'maxLengthEnforcement: none', 'textInputAction: done', 'textAlign: end', 'textDirection: ltr', 'cursorWidth: 1.0', 'cursorHeight: 1.0', 'cursorRadius: Radius.circular(0.0)', 'cursorColor: Color(0xff00ff00)', 'keyboardAppearance: Brightness.dark', 'scrollPadding: EdgeInsets.zero', 'selection disabled', 'scrollPhysics: ClampingScrollPhysics', ]); }); testWidgets( 'strut basic single line', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: const Material( child: Center( child: TextField(), ), ), ), ); expect( tester.getSize(find.byType(TextField)), // The TextField will be as tall as the decoration (24) plus the metrics // from the default TextStyle of the theme (16), or 40 altogether. // Because this is less than the kMinInteractiveDimension, it will be // increased to that value (48). const Size(800, kMinInteractiveDimension), ); }, ); testWidgets( 'strut TextStyle increases height', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: TextField( style: TextStyle(fontSize: 20), ), ), ), ), ); expect( tester.getSize(find.byType(TextField)), // Strut should inherit the TextStyle.fontSize by default and produce the // same height as if it were disabled. const Size(800, kMinInteractiveDimension), // Because 44 < 48. ); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: const Material( child: Center( child: TextField( style: TextStyle(fontSize: 20), strutStyle: StrutStyle.disabled, ), ), ), ), ); expect( tester.getSize(find.byType(TextField)), // The height here should match the previous version with strut enabled. const Size(800, kMinInteractiveDimension), // Because 44 < 48. ); }, ); testWidgets( 'strut basic multi line', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: TextField( maxLines: 6, ), ), ), ), ); expect( tester.getSize(find.byType(TextField)), // The height should be the input decoration (24) plus 6x the strut height (16). const Size(800, 120), ); }, ); testWidgets( 'strut no force small strut', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: TextField( maxLines: 6, strutStyle: StrutStyle( // The small strut is overtaken by the larger // TextStyle fontSize. fontSize: 5, ), ), ), ), ), ); expect( tester.getSize(find.byType(TextField)), // When the strut's height is smaller than TextStyle's and forceStrutHeight // is disabled, then the TextStyle takes precedence. Should be the same height // as 'strut basic multi line'. const Size(800, 120), ); }, ); testWidgets( 'strut no force large strut', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: TextField( maxLines: 6, strutStyle: StrutStyle( fontSize: 25, ), ), ), ), ), ); expect( tester.getSize(find.byType(TextField)), // When the strut's height is larger than TextStyle's and forceStrutHeight // is disabled, then the StrutStyle takes precedence. const Size(800, 174), ); }, skip: isBrowser, // TODO(mdebbar): https://github.com/flutter/flutter/issues/32243 ); testWidgets( 'strut height override', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: TextField( maxLines: 3, strutStyle: StrutStyle( fontSize: 8, forceStrutHeight: true, ), ), ), ), ), ); expect( tester.getSize(find.byType(TextField)), // The smaller font size of strut make the field shorter than normal. const Size(800, 48), ); }, skip: isBrowser, // TODO(mdebbar): https://github.com/flutter/flutter/issues/32243 ); testWidgets( 'strut forces field taller', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: TextField( maxLines: 3, style: TextStyle(fontSize: 10), strutStyle: StrutStyle( fontSize: 18, forceStrutHeight: true, ), ), ), ), ), ); expect( tester.getSize(find.byType(TextField)), // When the strut fontSize is larger than a provided TextStyle, the // strut's height takes precedence. const Size(800, 78), ); }, skip: isBrowser, // TODO(mdebbar): https://github.com/flutter/flutter/issues/32243 ); testWidgets('Caret center position', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: Theme( data: ThemeData(useMaterial3: false), child: const SizedBox( width: 300.0, child: TextField( textAlign: TextAlign.center, decoration: null, ), ), ), ), ); final RenderEditable editable = findRenderEditable(tester); await tester.enterText(find.byType(TextField), 'abcd'); await tester.pump(); Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 4)).topLeft, ); expect(topLeft.dx, equals(431)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 3)).topLeft, ); expect(topLeft.dx, equals(415)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 2)).topLeft, ); expect(topLeft.dx, equals(399)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 1)).topLeft, ); expect(topLeft.dx, equals(383)); }); testWidgets('Caret indexes into trailing whitespace center align', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: Theme( data: ThemeData(useMaterial3: false), child: const SizedBox( width: 300.0, child: TextField( textAlign: TextAlign.center, decoration: null, ), ), ), ), ); final RenderEditable editable = findRenderEditable(tester); await tester.enterText(find.byType(TextField), 'abcd '); await tester.pump(); Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 7)).topLeft, ); expect(topLeft.dx, equals(479)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 8)).topLeft, ); expect(topLeft.dx, equals(495)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 4)).topLeft, ); expect(topLeft.dx, equals(431)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 3)).topLeft, ); expect(topLeft.dx, equals(415)); // Should be same as equivalent in 'Caret center position' topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 2)).topLeft, ); expect(topLeft.dx, equals(399)); // Should be same as equivalent in 'Caret center position' topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 1)).topLeft, ); expect(topLeft.dx, equals(383)); // Should be same as equivalent in 'Caret center position' }); testWidgets('selection handles are rendered and not faded away', (WidgetTester tester) async { const String testText = 'lorem ipsum'; final TextEditingController controller = _textEditingController(text: testText); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pumpAndSettle(); final List<FadeTransition> transitions = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0]; final FadeTransition right = transitions[1]; expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); }); testWidgets('iOS selection handles are rendered and not faded away', (WidgetTester tester) async { const String testText = 'lorem ipsum'; final TextEditingController controller = _textEditingController(text: testText); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final RenderEditable renderEditable = tester.state<EditableTextState>(find.byType(EditableText)).renderEditable; await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pumpAndSettle(); final List<FadeTransition> transitions = find.byType(FadeTransition).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0]; final FadeTransition right = transitions[1]; expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('iPad Scribble selection change shows selection handles', (WidgetTester tester) async { const String testText = 'lorem ipsum'; final TextEditingController controller = _textEditingController(text: testText); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); await tester.showKeyboard(find.byType(EditableText)); await tester.testTextInput.startScribbleInteraction(); tester.testTextInput.updateEditingValue(const TextEditingValue( text: testText, selection: TextSelection(baseOffset: 2, extentOffset: 7), )); await tester.pumpAndSettle(); final List<FadeTransition> transitions = find.byType(FadeTransition).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0]; final FadeTransition right = transitions[1]; expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets('Tap shows handles but not toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abc def ghi', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Tap to trigger the text field. await tester.tap(find.byType(TextField)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); }); testWidgets( 'Tap in empty text field does not show handles nor toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Tap to trigger the text field. await tester.tap(find.byType(TextField)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); }, ); testWidgets('Long press shows handles and toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abc def ghi', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Long press to trigger the text field. await tester.longPress(find.byType(TextField)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); expect(editableText.selectionOverlay!.toolbarIsVisible, isContextMenuProvidedByPlatform ? isFalse : isTrue); }); testWidgets( 'Long press in empty text field shows handles and toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Tap to trigger the text field. await tester.longPress(find.byType(TextField)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); expect(editableText.selectionOverlay!.toolbarIsVisible, isContextMenuProvidedByPlatform ? isFalse : isTrue); }, ); testWidgets('Double tap shows handles and toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abc def ghi', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Double tap to trigger the text field. await tester.tap(find.byType(TextField)); await tester.pump(const Duration(milliseconds: 50)); await tester.tap(find.byType(TextField)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); expect(editableText.selectionOverlay!.toolbarIsVisible, isContextMenuProvidedByPlatform ? isFalse : isTrue); }); testWidgets( 'Double tap in empty text field shows toolbar but not handles', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Double tap to trigger the text field. await tester.tap(find.byType(TextField)); await tester.pump(const Duration(milliseconds: 50)); await tester.tap(find.byType(TextField)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); expect(editableText.selectionOverlay!.toolbarIsVisible, isContextMenuProvidedByPlatform ? isFalse : isTrue); }, ); testWidgets( 'Mouse tap does not show handles nor toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abc def ghi', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Long press to trigger the text field. final Offset textFieldPos = tester.getCenter(find.byType(TextField)); final TestGesture gesture = await tester.startGesture( textFieldPos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); }, ); testWidgets( 'Mouse long press does not show handles nor toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abc def ghi', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Long press to trigger the text field. final Offset textFieldPos = tester.getCenter(find.byType(TextField)); final TestGesture gesture = await tester.startGesture( textFieldPos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); }, ); testWidgets( 'Mouse double tap does not show handles nor toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abc def ghi', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Double tap to trigger the text field. final Offset textFieldPos = tester.getCenter(find.byType(TextField)); final TestGesture gesture = await tester.startGesture( textFieldPos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); await tester.pump(); await gesture.down(textFieldPos); await tester.pump(); await gesture.up(); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); }, ); testWidgets('Does not show handles when updated from the web engine', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abc def ghi', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Interact with the text field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); final TestGesture gesture = await tester.startGesture( topLeft + const Offset(0.0, 5.0), kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); await tester.pumpAndSettle(); final EditableTextState state = tester.state(find.byType(EditableText)); expect(state.selectionOverlay!.handlesAreVisible, isFalse); expect(controller.selection, const TextSelection.collapsed(offset: 0)); if (kIsWeb) { tester.testTextInput.updateEditingValue(const TextEditingValue( text: 'abc def ghi', selection: TextSelection(baseOffset: 2, extentOffset: 7), )); // Wait for all the `setState` calls to be flushed. await tester.pumpAndSettle(); expect( state.currentTextEditingValue.selection, const TextSelection(baseOffset: 2, extentOffset: 7), ); expect(state.selectionOverlay!.handlesAreVisible, isFalse); } }); testWidgets('Tapping selection handles toggles the toolbar', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abc def ghi', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField(controller: controller), ), ), ); // Tap to position the cursor and show the selection handles. final Offset ePos = textOffsetToPosition(tester, 5); // Index of 'e'. await tester.tapAt(ePos, pointer: 7); await tester.pumpAndSettle(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.length, 1); // Tap the handle to show the toolbar. final Offset handlePos = endpoints[0].point + const Offset(0.0, 1.0); await tester.tapAt(handlePos, pointer: 7); await tester.pump(); expect(editableText.selectionOverlay!.toolbarIsVisible, isContextMenuProvidedByPlatform ? isFalse : isTrue); // Tap the handle again to hide the toolbar. await tester.tapAt(handlePos, pointer: 7); await tester.pump(); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); }); testWidgets('when TextField would be blocked by keyboard, it is shown with enough space for the selection handle', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Center( child: ListView( controller: scrollController, children: <Widget>[ Container(height: 579), // Push field almost off screen. const TextField(), Container(height: 1000), ], ), ), ), )); // Tap the TextField to put the cursor into it and bring it into view. expect(scrollController.offset, 0.0); await tester.tapAt(tester.getTopLeft(find.byType(TextField))); await tester.pumpAndSettle(); // The ListView has scrolled to keep the TextField and cursor handle // visible. expect(scrollController.offset, 50.0); }); // Regression test for https://github.com/flutter/flutter/issues/74566 testWidgets('TextField and last input character are visible on the screen when the cursor is not shown', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); final ScrollController textFieldScrollController = ScrollController(); addTearDown(() { scrollController.dispose(); textFieldScrollController.dispose(); }); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Center( child: ListView( controller: scrollController, children: <Widget>[ Container(height: 579), // Push field almost off screen. TextField( scrollController: textFieldScrollController, showCursor: false, ), Container(height: 1000), ], ), ), ), )); // Tap the TextField to bring it into view. expect(scrollController.offset, 0.0); await tester.tapAt(tester.getTopLeft(find.byType(TextField))); await tester.pumpAndSettle(); // The ListView has scrolled to keep the TextField visible. expect(scrollController.offset, 50.0); expect(textFieldScrollController.offset, 0.0); // After entering some long text, the last input character remains on the screen. final String testValue = 'I love Flutter!' * 10; tester.testTextInput.updateEditingValue(TextEditingValue( text: testValue, selection: TextSelection.collapsed(offset: testValue.length), )); await tester.pump(); await tester.pumpAndSettle(); // Text scroll animation. expect(textFieldScrollController.offset, 1602.0); }); group('height', () { testWidgets('By default, TextField is at least kMinInteractiveDimension high', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( theme: ThemeData(), home: const Scaffold( body: Center( child: TextField(), ), ), )); final RenderBox renderBox = tester.renderObject(find.byType(TextField)); expect(renderBox.size.height, greaterThanOrEqualTo(kMinInteractiveDimension)); }); testWidgets("When text is very small, TextField still doesn't go below kMinInteractiveDimension height", (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( theme: ThemeData(), home: const Scaffold( body: Center( child: TextField( style: TextStyle(fontSize: 2.0), ), ), ), )); final RenderBox renderBox = tester.renderObject(find.byType(TextField)); expect(renderBox.size.height, kMinInteractiveDimension); }); testWidgets('When isDense, TextField can go below kMinInteractiveDimension height', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( theme: ThemeData(), home: const Scaffold( body: Center( child: TextField( decoration: InputDecoration( isDense: true, ), ), ), ), )); final RenderBox renderBox = tester.renderObject(find.byType(TextField)); expect(renderBox.size.height, lessThan(kMinInteractiveDimension)); }); group('intrinsics', () { Widget buildTest({ required bool isDense }) { return MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ SliverFillRemaining( hasScrollBody: false, child: Column( children: <Widget>[ TextField( decoration: InputDecoration( isDense: isDense, ), ), Container( height: 1000, ), ], ), ), ], ), ), ); } testWidgets('By default, intrinsic height is at least kMinInteractiveDimension high', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/54729 // If the intrinsic height does not match that of the height after // performLayout, this will fail. await tester.pumpWidget(buildTest(isDense: false)); }); testWidgets('When isDense, intrinsic height can go below kMinInteractiveDimension height', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/54729 // If the intrinsic height does not match that of the height after // performLayout, this will fail. await tester.pumpWidget(buildTest(isDense: true)); }); }); }); testWidgets("Arrow keys don't move input focus", (WidgetTester tester) async { final TextEditingController controller1 = _textEditingController(); final TextEditingController controller2 = _textEditingController(); final TextEditingController controller3 = _textEditingController(); final TextEditingController controller4 = _textEditingController(); final TextEditingController controller5 = _textEditingController(); final FocusNode focusNode1 = FocusNode(debugLabel: 'Field 1'); final FocusNode focusNode2 = FocusNode(debugLabel: 'Field 2'); final FocusNode focusNode3 = FocusNode(debugLabel: 'Field 3'); final FocusNode focusNode4 = FocusNode(debugLabel: 'Field 4'); final FocusNode focusNode5 = FocusNode(debugLabel: 'Field 5'); addTearDown(() { focusNode1.dispose(); focusNode2.dispose(); focusNode3.dispose(); focusNode4.dispose(); focusNode5.dispose(); }); // Lay out text fields in a "+" formation, and focus the center one. await tester.pumpWidget(MaterialApp( theme: ThemeData(), home: Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox( width: 100.0, child: TextField( controller: controller1, focusNode: focusNode1, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox( width: 100.0, child: TextField( controller: controller2, focusNode: focusNode2, ), ), SizedBox( width: 100.0, child: TextField( controller: controller3, focusNode: focusNode3, ), ), SizedBox( width: 100.0, child: TextField( controller: controller4, focusNode: focusNode4, ), ), ], ), SizedBox( width: 100.0, child: TextField( controller: controller5, focusNode: focusNode5, ), ), ], ), ), ), )); focusNode3.requestFocus(); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); }); testWidgets('Scrolling shortcuts are disabled in text fields', (WidgetTester tester) async { bool scrollInvoked = false; await tester.pumpWidget( MaterialApp( home: Actions( actions: <Type, Action<Intent>>{ ScrollIntent: CallbackAction<ScrollIntent>(onInvoke: (Intent intent) { scrollInvoked = true; return null; }), }, child: Material( child: ListView( children: const <Widget>[ Padding(padding: EdgeInsets.symmetric(vertical: 200)), TextField(), Padding(padding: EdgeInsets.symmetric(vertical: 800)), ], ), ), ), ), ); await tester.pump(); expect(scrollInvoked, isFalse); // Set focus on the text field. await tester.tapAt(tester.getTopLeft(find.byType(TextField))); await tester.sendKeyEvent(LogicalKeyboardKey.space); expect(scrollInvoked, isFalse); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); expect(scrollInvoked, isFalse); }); testWidgets("A buildCounter that returns null doesn't affect the size of the TextField", (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/44909 final GlobalKey textField1Key = GlobalKey(); final GlobalKey textField2Key = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( children: <Widget>[ TextField(key: textField1Key), TextField( key: textField2Key, maxLength: 1, buildCounter: (BuildContext context, {required int currentLength, required bool isFocused, int? maxLength}) => null, ), ], ), ), ), ); await tester.pumpAndSettle(); final Size textFieldSize1 = tester.getSize(find.byKey(textField1Key)); final Size textFieldSize2 = tester.getSize(find.byKey(textField2Key)); expect(textFieldSize1, equals(textFieldSize2)); }); testWidgets( 'The selection menu displays in an Overlay without error', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/43787 final TextEditingController controller = _textEditingController( text: 'This is a test that shows some odd behavior with Text Selection!', ); late final OverlayEntry overlayEntry; addTearDown(() => overlayEntry..remove()..dispose()); await tester.pumpWidget(MaterialApp( home: Scaffold( body: ColoredBox( color: Colors.grey, child: Center( child: Container( color: Colors.red, width: 300, height: 600, child: Overlay( initialEntries: <OverlayEntry>[ overlayEntry = OverlayEntry( builder: (BuildContext context) => Center( child: TextField( controller: controller, ), ), ), ], ), ), ), ), ), )); await showSelectionMenuAt(tester, controller, controller.text.indexOf('test')); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }, ); testWidgets('clipboard status is checked via hasStrings without getting the full clipboard contents', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, ), ), ), ), ); bool calledGetData = false; bool calledHasStrings = false; tester.binding.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { switch (methodCall.method) { case 'Clipboard.getData': calledGetData = true; case 'Clipboard.hasStrings': calledHasStrings = true; default: break; } return null; }); final Offset textfieldStart = tester.getTopLeft(find.byType(TextField)); // Double tap like when showing the text selection menu on Android/iOS. await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(); // getData is not called unless something is pasted. hasStrings is used to // check the status of the clipboard. expect(calledGetData, false); // hasStrings is checked in order to decide if the content can be pasted. expect(calledHasStrings, true); }, skip: kIsWeb, // [intended] web doesn't call hasStrings. ); testWidgets('TextField changes mouse cursor when hovered', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextField( mouseCursor: SystemMouseCursors.grab, decoration: InputDecoration( // Add an icon so that the left edge is not the text area icon: Icon(Icons.person), ), ), ), ), ), ); // Center, which is within the text area final Offset center = tester.getCenter(find.byType(TextField)); // Top left, which is not the text area final Offset edge = tester.getTopLeft(find.byType(TextField)) + const Offset(1, 1); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: center); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab); // Test default cursor await tester.pumpWidget( const MaterialApp( home: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextField( decoration: InputDecoration( icon: Icon(Icons.person), ), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); await gesture.moveTo(edge); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); await gesture.moveTo(center); // Test default cursor when disabled await tester.pumpWidget( const MaterialApp( home: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextField( enabled: false, decoration: InputDecoration( icon: Icon(Icons.person), ), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); await gesture.moveTo(edge); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); await gesture.moveTo(center); }); testWidgets('TextField icons change mouse cursor when hovered', (WidgetTester tester) async { // Test default cursor in icons area. await tester.pumpWidget( const MaterialApp( home: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextField( decoration: InputDecoration( icon: Icon(Icons.label), prefixIcon: Icon(Icons.cabin), suffixIcon: Icon(Icons.person), ), ), ), ), ), ); // Center, which is within the text area final Offset center = tester.getCenter(find.byType(TextField)); // The Icon area final Offset iconArea = tester.getCenter(find.byIcon(Icons.label)); // The prefix Icon area final Offset prefixIconArea = tester.getCenter(find.byIcon(Icons.cabin)); // The suffix Icon area final Offset suffixIconArea = tester.getCenter(find.byIcon(Icons.person)); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: center); await tester.pump(); await gesture.moveTo(center); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); await gesture.moveTo(iconArea); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); await gesture.moveTo(prefixIconArea); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); await gesture.moveTo(suffixIconArea); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); await gesture.moveTo(center); // Test click cursor in icons area for buttons. await tester.pumpWidget( MaterialApp( home: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextField( decoration: InputDecoration( icon: IconButton( icon: const Icon(Icons.label), onPressed: () {}, ), prefixIcon: IconButton( icon: const Icon(Icons.cabin), onPressed: () {}, ), suffixIcon: IconButton( icon: const Icon(Icons.person), onPressed: () {}, ), ), ), ), ), ), ); await tester.pump(); await gesture.moveTo(center); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); await gesture.moveTo(iconArea); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); await gesture.moveTo(prefixIconArea); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); await gesture.moveTo(suffixIconArea); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); }); testWidgets('Text selection menu does not change mouse cursor when hovered', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextField( controller: controller, ), ), ), ), ); expect(find.text('Copy'), findsNothing); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 3), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); expect(find.text('Paste'), findsOneWidget); await gesture.moveTo(tester.getCenter(find.text('Paste'))); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }, variant: TargetPlatformVariant.desktop(), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Caret rtl with changing width', (WidgetTester tester) async { late StateSetter setState; bool isWide = false; const double wideWidth = 300.0; const double narrowWidth = 200.0; const TextStyle style = TextStyle(fontSize: 10, height: 1.0, letterSpacing: 0.0, wordSpacing: 0.0); const double caretWidth = 2.0; final TextEditingController controller = _textEditingController(); await tester.pumpWidget( boilerplate( child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return SizedBox( width: isWide ? wideWidth : narrowWidth, child: TextField( key: textFieldKey, controller: controller, textDirection: TextDirection.rtl, style: style, ), ); }, ), ), ); // The cursor is on the right of the input because it's RTL. RenderEditable editable = findRenderEditable(tester); double cursorRight = editable.getLocalRectForCaret( TextPosition(offset: controller.value.text.length), ).topRight.dx; double inputWidth = editable.size.width; expect(inputWidth, narrowWidth); expect(cursorRight, inputWidth - kCaretGap); const String text = '12345'; // After entering some text, the cursor is placed to the left of the text // because the paragraph's writing direction is RTL. await tester.enterText(find.byType(TextField), text); await tester.pump(); editable = findRenderEditable(tester); cursorRight = editable.getLocalRectForCaret( TextPosition(offset: controller.value.text.length), ).topRight.dx; inputWidth = editable.size.width; expect(cursorRight, inputWidth - kCaretGap - text.length * 10 - caretWidth); // Since increasing the width of the input moves its right edge further to // the right, the cursor has followed this change and still appears on the // right of the input. setState(() { isWide = true; }); await tester.pump(); editable = findRenderEditable(tester); cursorRight = editable.getLocalRectForCaret( TextPosition(offset: controller.value.text.length), ).topRight.dx; inputWidth = editable.size.width; expect(inputWidth, wideWidth); expect(cursorRight, inputWidth - kCaretGap - text.length * 10 - caretWidth); }); testWidgets('Text selection menu hides after select all on desktop', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); final String selectAll = defaultTargetPlatform == TargetPlatform.macOS ? 'Select All' : 'Select all'; expect(find.text(selectAll), findsNothing); expect(find.text('Copy'), findsNothing); final TestGesture gesture = await tester.startGesture( const Offset(10.0, 0.0) + textOffsetToPosition(tester, controller.text.length), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.value.selection, TextSelection.collapsed( offset: controller.text.length, affinity: TextAffinity.upstream, ), ); expect(find.text(selectAll), findsOneWidget); await tester.tapAt(tester.getCenter(find.text(selectAll))); await tester.pump(); expect(find.text(selectAll), findsNothing); expect(find.text('Copy'), findsNothing); }, // All desktop platforms except MacOS, which has no select all button. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux, TargetPlatform.windows }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); // Regressing test for https://github.com/flutter/flutter/issues/70625 testWidgets('TextFields can inherit [FloatingLabelBehaviour] from InputDecorationTheme.', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); Widget textFieldBuilder({ FloatingLabelBehavior behavior = FloatingLabelBehavior.auto }) { return MaterialApp( theme: ThemeData( useMaterial3: false, inputDecorationTheme: InputDecorationTheme( floatingLabelBehavior: behavior, ), ), home: Scaffold( body: TextField( focusNode: focusNode, decoration: const InputDecoration( labelText: 'Label', ), ), ), ); } await tester.pumpWidget(textFieldBuilder()); // The label will be positioned within the content when unfocused. expect(tester.getTopLeft(find.text('Label')).dy, 20.0); focusNode.requestFocus(); await tester.pumpAndSettle(); // label animation. // The label will float above the content when focused. expect(tester.getTopLeft(find.text('Label')).dy, 12.0); focusNode.unfocus(); await tester.pumpAndSettle(); // label animation. await tester.pumpWidget(textFieldBuilder(behavior: FloatingLabelBehavior.never)); await tester.pumpAndSettle(); // theme animation. // The label will be positioned within the content. expect(tester.getTopLeft(find.text('Label')).dy, 20.0); focusNode.requestFocus(); await tester.pumpAndSettle(); // label animation. // The label will always be positioned within the content. expect(tester.getTopLeft(find.text('Label')).dy, 20.0); await tester.pumpWidget(textFieldBuilder(behavior: FloatingLabelBehavior.always)); await tester.pumpAndSettle(); // theme animation. // The label will always float above the content. expect(tester.getTopLeft(find.text('Label')).dy, 12.0); focusNode.unfocus(); await tester.pumpAndSettle(); // label animation. // The label will always float above the content. expect(tester.getTopLeft(find.text('Label')).dy, 12.0); }); // Regression test for https://github.com/flutter/flutter/issues/140607. testWidgets('TextFields can inherit errorStyle color from InputDecorationTheme.', (WidgetTester tester) async { Widget textFieldBuilder() { return MaterialApp( theme: ThemeData( inputDecorationTheme: const InputDecorationTheme( errorStyle: TextStyle(color: Colors.green), ), ), home: const Scaffold( body: TextField( decoration: InputDecoration( errorText: 'error', ), ), ), ); } await tester.pumpWidget(textFieldBuilder()); await tester.pumpAndSettle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.widget.cursorColor, Colors.green); }); group('MaxLengthEnforcement', () { const int maxLength = 5; Future<void> setupWidget( WidgetTester tester, MaxLengthEnforcement? enforcement, ) async { final Widget widget = MaterialApp( home: Material( child: TextField( maxLength: maxLength, maxLengthEnforcement: enforcement, ), ), ); await tester.pumpWidget(widget); await tester.pumpAndSettle(); } testWidgets('using none enforcement.', (WidgetTester tester) async { const MaxLengthEnforcement enforcement = MaxLengthEnforcement.none; await setupWidget(tester, enforcement); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.text, 'abc'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.text, 'abcdef'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 6)); state.updateEditingValue(const TextEditingValue(text: 'abcdef')); expect(state.currentTextEditingValue.text, 'abcdef'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); testWidgets('using enforced.', (WidgetTester tester) async { const MaxLengthEnforcement enforcement = MaxLengthEnforcement.enforced; await setupWidget(tester, enforcement); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.text, 'abc'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: 'abcdef')); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); }); testWidgets('using truncateAfterCompositionEnds.', (WidgetTester tester) async { const MaxLengthEnforcement enforcement = MaxLengthEnforcement.truncateAfterCompositionEnds; await setupWidget(tester, enforcement); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.text, 'abc'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.text, 'abcdef'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 6)); state.updateEditingValue(const TextEditingValue(text: 'abcdef')); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); testWidgets('using default behavior for different platforms.', (WidgetTester tester) async { await setupWidget(tester, null); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: '侬好啊')); expect(state.currentTextEditingValue.text, '侬好啊'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: '侬好啊旁友', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.text, '侬好啊旁友'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: '侬好啊旁友们', composing: TextRange(start: 3, end: 6))); if (kIsWeb || defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.linux || defaultTargetPlatform == TargetPlatform.fuchsia ) { expect(state.currentTextEditingValue.text, '侬好啊旁友们'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 6)); } else { expect(state.currentTextEditingValue.text, '侬好啊旁友'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); } state.updateEditingValue(const TextEditingValue(text: '侬好啊旁友')); expect(state.currentTextEditingValue.text, '侬好啊旁友'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); }); testWidgets('TextField does not leak touch events when deadline has exceeded', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/118340. int textFieldTapCount = 0; int prefixTapCount = 0; int suffixTapCount = 0; final FocusNode focusNode = _focusNode(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: TextField( focusNode: focusNode, onTap: () { textFieldTapCount += 1; }, decoration: InputDecoration( labelText: 'Label', prefix: ElevatedButton( onPressed: () { prefixTapCount += 1; }, child: const Text('prefix'), ), suffix: ElevatedButton( onPressed: () { suffixTapCount += 1; }, child: const Text('suffix'), ), ), ), ), ), ); // Focus to show the prefix and suffix buttons. focusNode.requestFocus(); await tester.pump(); TestGesture gesture = await tester.startGesture( tester.getRect(find.text('prefix')).center, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); await gesture.up(); expect(textFieldTapCount, 0); expect(prefixTapCount, 1); expect(suffixTapCount, 0); gesture = await tester.startGesture( tester.getRect(find.text('suffix')).center, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); await gesture.up(); expect(textFieldTapCount, 0); expect(prefixTapCount, 1); expect(suffixTapCount, 1); }); testWidgets('prefix/suffix buttons do not leak touch events', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/39376. int textFieldTapCount = 0; int prefixTapCount = 0; int suffixTapCount = 0; final FocusNode focusNode = _focusNode(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: TextField( focusNode: focusNode, onTap: () { textFieldTapCount += 1; }, decoration: InputDecoration( labelText: 'Label', prefix: ElevatedButton( onPressed: () { prefixTapCount += 1; }, child: const Text('prefix'), ), suffix: ElevatedButton( onPressed: () { suffixTapCount += 1; }, child: const Text('suffix'), ), ), ), ), ), ); // Focus to show the prefix and suffix buttons. focusNode.requestFocus(); await tester.pump(); await tester.tap(find.text('prefix')); expect(textFieldTapCount, 0); expect(prefixTapCount, 1); expect(suffixTapCount, 0); await tester.tap(find.text('suffix')); expect(textFieldTapCount, 0); expect(prefixTapCount, 1); expect(suffixTapCount, 1); }); testWidgets('autofill info has hint text', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: TextField( decoration: InputDecoration( hintText: 'placeholder text' ), ), ), ), ), ); await tester.tap(find.byType(TextField)); expect( tester.testTextInput.setClientArgs?['autofill'], containsPair('hintText', 'placeholder text'), ); }); testWidgets('TextField at rest does not push any layers with alwaysNeedsAddToScene', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: TextField(), ), ), ), ); expect(tester.layers.any((Layer layer) => layer.debugSubtreeNeedsAddToScene!), isFalse); }); testWidgets('Focused TextField does not push any layers with alwaysNeedsAddToScene', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField(focusNode: focusNode), ), ), ), ); await tester.showKeyboard(find.byType(TextField)); expect(focusNode.hasFocus, isTrue); expect(tester.layers.any((Layer layer) => layer.debugSubtreeNeedsAddToScene!), isFalse); }); testWidgets('TextField does not push any layers with alwaysNeedsAddToScene after toolbar is dismissed', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField(focusNode: focusNode), ), ), ), ); await tester.showKeyboard(find.byType(TextField)); // Bring up the toolbar. const String testValue = 'A B C'; tester.testTextInput.updateEditingValue( const TextEditingValue( text: testValue, ), ); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); expect(state.showToolbar(), true); await tester.pumpAndSettle(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Copy'), findsOneWidget); // Toolbar is visible // Hide the toolbar focusNode.unfocus(); await tester.pumpAndSettle(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Copy'), findsNothing); // Toolbar is not visible expect(tester.layers.any((Layer layer) => layer.debugSubtreeNeedsAddToScene!), isFalse); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('cursor blinking respects TickerMode', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); Widget builder({required bool tickerMode}) { return MaterialApp( home: Material( child: Center( child: TickerMode(enabled: tickerMode, child: TextField(focusNode: focusNode)), ), ), ); } // TickerMode is on, cursor is blinking. await tester.pumpWidget(builder(tickerMode: true)); await tester.showKeyboard(find.byType(TextField)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable editable = state.renderEditable; expect(editable.showCursor.value, isTrue); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isTrue); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); // TickerMode is off, cursor does not blink. await tester.pumpWidget(builder(tickerMode: false)); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); // TickerMode is on, cursor blinks again. await tester.pumpWidget(builder(tickerMode: true)); expect(editable.showCursor.value, isTrue); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isTrue); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); // Dismissing focus while tickerMode is off does not start cursor blinking // when tickerMode is turned on again. await tester.pumpWidget(builder(tickerMode: false)); focusNode.unfocus(); await tester.pump(); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pumpWidget(builder(tickerMode: true)); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); // Focusing while tickerMode is off does not start cursor blinking... await tester.pumpWidget(builder(tickerMode: false)); await tester.showKeyboard(find.byType(TextField)); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); // ... but it does start when tickerMode is switched on again. await tester.pumpWidget(builder(tickerMode: true)); expect(editable.showCursor.value, isTrue); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isFalse); await tester.pump(state.cursorBlinkInterval); expect(editable.showCursor.value, isTrue); }); testWidgets('can shift + tap to select with a keyboard (Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField(controller: controller), ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 13)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 13); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.tapAt(textOffsetToPosition(tester, 20)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 20); await tester.pump(kDoubleTapTimeout); await tester.tapAt(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 23); await tester.pump(kDoubleTapTimeout); await tester.tapAt(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 4); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 4); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('can shift + tap to select with a keyboard (non-Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField(controller: controller), ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 13)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 13); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.tapAt(textOffsetToPosition(tester, 20)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 20); await tester.pump(kDoubleTapTimeout); await tester.tapAt(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 23); await tester.pump(kDoubleTapTimeout); await tester.tapAt(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 4); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 4); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows })); testWidgets('shift tapping an unfocused field', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); final FocusNode focusNode = _focusNode(); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( controller: controller, focusNode: focusNode, ), ), ), ), ); expect(focusNode.hasFocus, isFalse); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, controller.text.length)); await tester.pump(kDoubleTapTimeout); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); expect(controller.selection.baseOffset, 35); expect(controller.selection.extentOffset, 35); // Unfocus the field, but the selection remains. focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isFalse); expect(controller.selection.baseOffset, 35); expect(controller.selection.extentOffset, 35); // Shift tap in the middle of the field. await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.tapAt(textOffsetToPosition(tester, 20)); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); switch (defaultTargetPlatform) { // Apple platforms start the selection from 0. case TargetPlatform.iOS: case TargetPlatform.macOS: expect(controller.selection.baseOffset, 0); // Other platforms start from the previous selection. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, 35); } expect(controller.selection.extentOffset, 20); }, variant: TargetPlatformVariant.all()); testWidgets('can shift + tap + drag to select with a keyboard (Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField(controller: controller), ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 23), pointer: 7, kind: PointerDeviceKind.mouse, ); if (isTargetPlatformMobile) { await gesture.up(); } await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Expand the selection a bit. if (isTargetPlatformMobile) { await gesture.down(textOffsetToPosition(tester, 24)); } await tester.pumpAndSettle(); await gesture.moveTo(textOffsetToPosition(tester, 28)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 28); // Move back to the original selection. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Collapse the selection. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); // Invert the selection. The base jumps to the original extent. await gesture.moveTo(textOffsetToPosition(tester, 7)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 7); // Continuing to move in the inverted direction expands the selection. await gesture.moveTo(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 4); // Move back to the original base. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Continue to move past the original base, which will cause the selection // to invert back to the original orientation. await gesture.moveTo(textOffsetToPosition(tester, 9)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 9); // Continuing to select in this direction selects just like it did // originally. await gesture.moveTo(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); // Releasing the shift key has no effect; the selection continues as the // mouse continues to move. await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); await gesture.moveTo(textOffsetToPosition(tester, 26)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 26); await gesture.up(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 26); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('can shift + tap + drag to select with a keyboard (non-Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.fuchsia; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField(controller: controller), ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 23), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); if (isTargetPlatformMobile) { await gesture.up(); // Not a double tap + drag. await tester.pumpAndSettle(kDoubleTapTimeout); } expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Expand the selection a bit. if (isTargetPlatformMobile) { await gesture.down(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); } await gesture.moveTo(textOffsetToPosition(tester, 28)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 28); // Move back to the original selection. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Collapse the selection. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); // Invert the selection. The original selection is not restored like on iOS // and Mac. await gesture.moveTo(textOffsetToPosition(tester, 7)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 7); // Continuing to move in the inverted direction expands the selection. await gesture.moveTo(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 4); // Move back to the original base. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); // Continue to move past the original base. await gesture.moveTo(textOffsetToPosition(tester, 9)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 9); // Continuing to select in this direction selects just like it did // originally. await gesture.moveTo(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); // Releasing the shift key has no effect; the selection continues as the // mouse continues to move. await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); await gesture.moveTo(textOffsetToPosition(tester, 26)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 26); await gesture.up(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 26); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux, TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.windows })); testWidgets('can shift + tap + drag to select with a keyboard, reversed (Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField(controller: controller), ), ), ), ); // Make a selection from right to left. await tester.tapAt(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 8), pointer: 7, kind: PointerDeviceKind.mouse, ); if (isTargetPlatformMobile) { await gesture.up(); } await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Expand the selection a bit. if (isTargetPlatformMobile) { await gesture.down(textOffsetToPosition(tester, 7)); } await gesture.moveTo(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 5); // Move back to the original selection. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Collapse the selection. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); // Invert the selection. The base jumps to the original extent. await gesture.moveTo(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); // Continuing to move in the inverted direction expands the selection. await gesture.moveTo(textOffsetToPosition(tester, 27)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 27); // Move back to the original base. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Continue to move past the original base, which will cause the selection // to invert back to the original orientation. await gesture.moveTo(textOffsetToPosition(tester, 22)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 22); // Continuing to select in this direction selects just like it did // originally. await gesture.moveTo(textOffsetToPosition(tester, 16)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 16); // Releasing the shift key has no effect; the selection continues as the // mouse continues to move. await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 16); await gesture.moveTo(textOffsetToPosition(tester, 14)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 14); await gesture.up(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 14); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('can shift + tap + drag to select with a keyboard, reversed (non-Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.fuchsia; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: TextField(controller: controller), ), ), ), ); // Make a selection from right to left. await tester.tapAt(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 8), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); if (isTargetPlatformMobile) { await gesture.up(); // Not a double tap + drag. await tester.pumpAndSettle(kDoubleTapTimeout); } expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Expand the selection a bit. if (isTargetPlatformMobile) { await gesture.down(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); } await gesture.moveTo(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 5); // Move back to the original selection. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Collapse the selection. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); // Invert the selection. The selection is not restored like it would be on // iOS and Mac. await gesture.moveTo(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 24); // Continuing to move in the inverted direction expands the selection. await gesture.moveTo(textOffsetToPosition(tester, 27)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 27); // Move back to the original base. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); // Continue to move past the original base. await gesture.moveTo(textOffsetToPosition(tester, 22)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 22); // Continuing to select in this direction selects just like it did // originally. await gesture.moveTo(textOffsetToPosition(tester, 16)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 16); // Releasing the shift key has no effect; the selection continues as the // mouse continues to move. await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 16); await gesture.moveTo(textOffsetToPosition(tester, 14)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 14); await gesture.up(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 14); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux, TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.windows })); // Regression test for https://github.com/flutter/flutter/issues/101587. testWidgets('Right clicking menu behavior', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'blah1 blah2', ); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Initially, the menu is not shown and there is no selection. expectNoCupertinoToolbar(); expect(controller.selection, const TextSelection(baseOffset: -1, extentOffset: -1)); final Offset midBlah1 = textOffsetToPosition(tester, 2); final Offset midBlah2 = textOffsetToPosition(tester, 8); // Right click the second word. final TestGesture gesture = await tester.startGesture( midBlah2, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: expect(controller.selection, const TextSelection(baseOffset: 6, extentOffset: 11)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection, const TextSelection.collapsed(offset: 8)); expect(find.text('Cut'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsOneWidget); expect(find.text('Select all'), findsOneWidget); } // Right click the first word. await gesture.down(midBlah1); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection, const TextSelection.collapsed(offset: 8)); expect(find.text('Cut'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsNothing); expect(find.text('Select all'), findsNothing); } }, variant: TargetPlatformVariant.all(), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Cannot request focus when canRequestFocus is false', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); // Default test. The canRequestFocus is true by default and the text field can be focused await tester.pumpWidget( boilerplate( child: TextField( focusNode: focusNode, ), ), ); expect(focusNode.hasFocus, isFalse); focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasFocus, isTrue); // Set canRequestFocus to false: the text field cannot be focused when it is tapped/long pressed. await tester.pumpWidget( boilerplate( child: TextField( focusNode: focusNode, canRequestFocus: false, ), ), ); expect(focusNode.hasFocus, isFalse); focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasFocus, isFalse); // The text field cannot be focused if it is tapped. await tester.tap(find.byType(TextField)); await tester.pump(); expect(focusNode.hasFocus, isFalse); // The text field cannot be focused if it is long pressed. await tester.longPress(find.byType(TextField)); await tester.pump(); expect(focusNode.hasFocus, isFalse); }); group('Right click focus', () { testWidgets('Can right click to focus multiple times', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/103228 final FocusNode focusNode1 = _focusNode(); final FocusNode focusNode2 = _focusNode(); final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: Column( children: <Widget>[ TextField( key: key1, focusNode: focusNode1, ), const SizedBox(height: 100.0), TextField( key: key2, focusNode: focusNode2, ), ], ), ), ), ); // Interact with the field to establish the input connection. await tester.tapAt( tester.getCenter(find.byKey(key1)), buttons: kSecondaryButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); await tester.tapAt( tester.getCenter(find.byKey(key2)), buttons: kSecondaryButton, ); await tester.pump(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); await tester.tapAt( tester.getCenter(find.byKey(key1)), buttons: kSecondaryButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); }); testWidgets('Can right click to focus on previously selected word on Apple platforms', (WidgetTester tester) async { final FocusNode focusNode1 = _focusNode(); final FocusNode focusNode2 = _focusNode(); final TextEditingController controller = _textEditingController( text: 'first second', ); final UniqueKey key1 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: Column( children: <Widget>[ TextField( key: key1, controller: controller, focusNode: focusNode1, ), Focus( focusNode: focusNode2, child: const Text('focusable'), ), ], ), ), ), ); // Interact with the field to establish the input connection. await tester.tapAt( tester.getCenter(find.byKey(key1)), buttons: kSecondaryButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); // Select the second word. controller.selection = const TextSelection( baseOffset: 6, extentOffset: 12, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect(controller.selection.isCollapsed, isFalse); expect(controller.selection.baseOffset, 6); expect(controller.selection.extentOffset, 12); // Unfocus the first field. focusNode2.requestFocus(); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); // Right click the second word in the first field, which is still selected // even though the selection is not visible. await tester.tapAt( textOffsetToPosition(tester, 8), buttons: kSecondaryButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect(controller.selection.baseOffset, 6); expect(controller.selection.extentOffset, 12); // Select everything. controller.selection = const TextSelection( baseOffset: 0, extentOffset: 12, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 12); // Unfocus the first field. focusNode2.requestFocus(); await tester.pumpAndSettle(); // Right click the first word in the first field. await tester.tapAt( textOffsetToPosition(tester, 2), buttons: kSecondaryButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 5); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Right clicking cannot request focus if canRequestFocus is false', (WidgetTester tester) async { final FocusNode focusNode = _focusNode(); final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: Column( children: <Widget>[ TextField( key: key, focusNode: focusNode, canRequestFocus: false, ), ], ), ), ), ); await tester.tapAt( tester.getCenter(find.byKey(key)), buttons: kSecondaryButton, ); await tester.pump(); expect(focusNode.hasFocus, isFalse); }); }); group('context menu', () { testWidgets('builds AdaptiveTextSelectionToolbar by default', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: Column( children: <Widget>[ TextField( controller: controller, ), ], ), ), ), ); await tester.pump(); // Wait for autofocus to take effect. expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); testWidgets('contextMenuBuilder is used in place of the default text selection toolbar', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: Column( children: <Widget>[ TextField( controller: controller, contextMenuBuilder: ( BuildContext context, EditableTextState editableTextState, ) { return Placeholder(key: key); }, ), ], ), ), ), ); await tester.pump(); // Wait for autofocus to take effect. expect(find.byKey(key), findsNothing); // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(find.byKey(key), findsOneWidget); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); testWidgets('contextMenuBuilder changes from default to null', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final TextEditingController controller = _textEditingController(); await tester.pumpWidget(MaterialApp(home: Material(child: TextField(key: key, controller: controller)))); await tester.pump(); // Wait for autofocus to take effect. // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pump(); expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); // Set contextMenuBuilder to null. await tester.pumpWidget( MaterialApp( home: Material( child: TextField( key: key, controller: controller, contextMenuBuilder: null, ), ), ), ); // Trigger build one more time... await tester.pumpWidget( MaterialApp( home: Material( child: Padding( padding: EdgeInsets.zero, child: TextField(key: key, controller: controller, contextMenuBuilder: null), ), ), ), ); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); }); group('magnifier builder', () { testWidgets('should build custom magnifier if given', (WidgetTester tester) async { final Widget customMagnifier = Container( key: UniqueKey(), ); final TextField textField = TextField( magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: (BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo>? info) => customMagnifier, ), ); await tester.pumpWidget(const MaterialApp( home: Placeholder(), )); final BuildContext context = tester.firstElement(find.byType(Placeholder)); final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); addTearDown(magnifierInfo.dispose); expect( textField.magnifierConfiguration!.magnifierBuilder( context, MagnifierController(), magnifierInfo, ), isA<Widget>().having( (Widget widget) => widget.key, 'built magnifier key equal to passed in magnifier key', equals(customMagnifier.key))); }); group('defaults', () { testWidgets('should build Magnifier on Android', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Scaffold(body: TextField())) ); final BuildContext context = tester.firstElement(find.byType(TextField)); final EditableText editableText = tester.widget(find.byType(EditableText)); final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); addTearDown(magnifierInfo.dispose); expect( editableText.magnifierConfiguration.magnifierBuilder( context, MagnifierController(), magnifierInfo, ), isA<TextMagnifier>()); }, variant: TargetPlatformVariant.only(TargetPlatform.android)); testWidgets('should build CupertinoMagnifier on iOS', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Scaffold(body: TextField())) ); final BuildContext context = tester.firstElement(find.byType(TextField)); final EditableText editableText = tester.widget(find.byType(EditableText)); final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); addTearDown(magnifierInfo.dispose); expect( editableText.magnifierConfiguration.magnifierBuilder( context, MagnifierController(), magnifierInfo, ), isA<CupertinoTextMagnifier>()); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets('should build nothing on Android and iOS', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Scaffold(body: TextField())) ); final BuildContext context = tester.firstElement(find.byType(TextField)); final EditableText editableText = tester.widget(find.byType(EditableText)); final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); addTearDown(magnifierInfo.dispose); expect( editableText.magnifierConfiguration.magnifierBuilder( context, MagnifierController(), magnifierInfo, ), isNull); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android })); }); }); group('magnifier', () { late ValueNotifier<MagnifierInfo> magnifierInfo; final Widget fakeMagnifier = Container(key: UniqueKey()); testWidgets( 'Can drag handles to show, unshow, and update magnifier', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( overlay( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: ( BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Double tap the 'e' to select 'def'. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(const Duration(milliseconds: 30)); await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(const Duration(milliseconds: 30)); final TextSelection selection = controller.selection; final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); // Drag the right handle 2 letters to the right. final Offset handlePos = endpoints.last.point + const Offset(1.0, 1.0); final TestGesture gesture = await tester.startGesture(handlePos); await gesture.moveTo(textOffsetToPosition(tester, testValue.length - 2)); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); final Offset firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, testValue.length)); await tester.pump(); // Expect the position the magnifier gets to have moved. expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); await gesture.up(); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsNothing); }); testWidgets('Can drag to show, unshow, and update magnifier', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: ( BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Tap at '|a' to move the selection to position 0. await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); expect(find.byKey(fakeMagnifier.key!), findsNothing); // Start a drag gesture to move the selection to the dragged position, showing // the magnifier. final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 0)); await tester.pump(); await gesture.moveTo(textOffsetToPosition(tester, 5)); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); Offset firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, 10)); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 10); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); // Expect the position the magnifier gets to have moved. expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); // The magnifier should hide when the drag ends. await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 10); expect(find.byKey(fakeMagnifier.key!), findsNothing); // Start a double-tap select the word at the tapped position. await gesture.down(textOffsetToPosition(tester, 1)); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(tester, 1)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 3); // Start a drag gesture to extend the selection word-by-word, showing the // magnifier. await gesture.moveTo(textOffsetToPosition(tester, 5)); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 7); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, 10)); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 11); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); // Expect the position the magnifier gets to have moved. expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); // The magnifier should hide when the drag ends. await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 11); expect(find.byKey(fakeMagnifier.key!), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); testWidgets('Can long press to show, unshow, and update magnifier', (WidgetTester tester) async { final TextEditingController controller = _textEditingController(); final bool isTargetPlatformAndroid = defaultTargetPlatform == TargetPlatform.android; await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( dragStartBehavior: DragStartBehavior.down, controller: controller, magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: ( BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(TextField), testValue); await skipPastScrollingAnimation(tester); // Tap at 'e' to set the selection to position 5 on Android. // Tap at 'e' to set the selection to the closest word edge, which is position 4 on iOS. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pumpAndSettle(const Duration(milliseconds: 300)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, isTargetPlatformAndroid ? 5 : 7); expect(find.byKey(fakeMagnifier.key!), findsNothing); // Long press the 'e' to select 'def' on Android and show magnifier. // Long press the 'e' to move the cursor in front of the 'e' on iOS and show the magnifier. final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); expect(controller.selection.baseOffset, isTargetPlatformAndroid ? 4 : 5); expect(controller.selection.extentOffset, isTargetPlatformAndroid ? 7 : 5); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); final Offset firstLongPressGesturePosition = magnifierInfo.value.globalGesturePosition; // Move the gesture to 'h' on Android to update the magnifier and select 'ghi'. // Move the gesture to 'h' on iOS to update the magnifier and move the cursor to 'h'. await gesture.moveTo(textOffsetToPosition(tester, testValue.indexOf('h'))); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, isTargetPlatformAndroid ? 4 : 9); expect(controller.selection.extentOffset, isTargetPlatformAndroid ? 11 : 9); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); // Expect the position the magnifier gets to have moved. expect(firstLongPressGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); // End the long press to hide the magnifier. await gesture.up(); await tester.pumpAndSettle(); expect(find.byKey(fakeMagnifier.key!), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); testWidgets('magnifier does not show when tapping outside field', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/128321 await tester.pumpWidget( MaterialApp( home: Scaffold( body: Padding( padding: const EdgeInsets.all(20), child: TextField( magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: ( BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), onTapOutside: (PointerDownEvent event) { FocusManager.instance.primaryFocus?.unfocus(); } ), ), ), ), ); await tester.tapAt( tester.getCenter(find.byType(TextField)), ); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsNothing); final TestGesture gesture = await tester.startGesture( tester.getBottomLeft(find.byType(TextField)) - const Offset(10.0, 20.0), ); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsNothing); await gesture.up(); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsNothing); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), ); }); group('TapRegion integration', () { testWidgets('Tapping outside loses focus on desktop', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: SizedBox( width: 100, height: 100, child: Opacity( opacity: 0.5, child: TextField( autofocus: true, focusNode: focusNode, decoration: const InputDecoration( hintText: 'Placeholder', border: OutlineInputBorder(), ), ), ), ), ), ), ), ); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); await tester.tapAt(const Offset(10, 10)); await tester.pump(); expect(focusNode.hasPrimaryFocus, isFalse); }, variant: TargetPlatformVariant.desktop()); testWidgets("Tapping outside doesn't lose focus on mobile", (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: SizedBox( width: 100, height: 100, child: Opacity( opacity: 0.5, child: TextField( autofocus: true, focusNode: focusNode, decoration: const InputDecoration( hintText: 'Placeholder', border: OutlineInputBorder(), ), ), ), ), ), ), ), ); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); await tester.tapAt(const Offset(10, 10)); await tester.pump(); // Focus is lost on mobile browsers, but not mobile apps. expect(focusNode.hasPrimaryFocus, kIsWeb ? isFalse : isTrue); }, variant: TargetPlatformVariant.mobile()); testWidgets("Tapping on toolbar doesn't lose focus", (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); final TextEditingController controller = _textEditingController(text: 'A B C'); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: SizedBox( width: 100, height: 100, child: Opacity( opacity: 0.5, child: TextField( controller: controller, focusNode: focusNode, decoration: const InputDecoration(hintText: 'Placeholder'), ), ), ), ), ), ), ); // The selectWordsInRange with SelectionChangedCause.tap seems to be needed to show the toolbar. final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); final Offset aPosition = textOffsetToPosition(tester, 1); // Right clicking shows the menu. final TestGesture gesture = await tester.startGesture( aPosition, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Sanity check that the toolbar widget exists. expect(find.text('Copy'), findsOneWidget); expect(focusNode.hasPrimaryFocus, isTrue); // Now tap on it to see if we lose focus. await tester.tap(find.text('Copy')); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); }, variant: TargetPlatformVariant.all(), skip: isBrowser, // [intended] On the web, the toolbar isn't rendered by Flutter. ); testWidgets("Tapping on input decorator doesn't lose focus", (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: SizedBox( width: 100, height: 100, child: Opacity( opacity: 0.5, child: TextField( autofocus: true, focusNode: focusNode, decoration: const InputDecoration( hintText: 'Placeholder', border: OutlineInputBorder(), ), ), ), ), ), ), ), ); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); final Rect decorationBox = tester.getRect(find.byType(TextField)); // Tap just inside the decoration, but not inside the EditableText. await tester.tapAt(decorationBox.topLeft + const Offset(1, 1)); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); }, variant: TargetPlatformVariant.all()); // PointerDownEvents can't be trackpad events, apparently, so we skip that one. for (final PointerDeviceKind pointerDeviceKind in PointerDeviceKind.values.toSet()..remove(PointerDeviceKind.trackpad)) { testWidgets('Default TextField handling of onTapOutside follows platform conventions for ${pointerDeviceKind.name}', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test'); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( children: <Widget>[ const Text('Outside'), TextField( autofocus: true, focusNode: focusNode, ), ], ), ), ), ); await tester.pump(); Future<void> click(Finder finder) async { final TestGesture gesture = await tester.startGesture( tester.getCenter(finder), kind: pointerDeviceKind, ); await gesture.up(); await gesture.removePointer(); } expect(focusNode.hasPrimaryFocus, isTrue); await click(find.text('Outside')); switch (pointerDeviceKind) { case PointerDeviceKind.touch: switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.android: case TargetPlatform.fuchsia: expect(focusNode.hasPrimaryFocus, equals(!kIsWeb)); case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(focusNode.hasPrimaryFocus, isFalse); } case PointerDeviceKind.mouse: case PointerDeviceKind.stylus: case PointerDeviceKind.invertedStylus: case PointerDeviceKind.trackpad: case PointerDeviceKind.unknown: expect(focusNode.hasPrimaryFocus, isFalse); } }, variant: TargetPlatformVariant.all()); } }); testWidgets('Builds the corresponding default spell check toolbar by platform', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; late final BuildContext builderContext; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: Builder( builder: (BuildContext context) { builderContext = context; return const TextField( autofocus: true, spellCheckConfiguration: SpellCheckConfiguration(), ); }, ), ), ), ), ); // Allow the autofocus to take effect. await tester.pump(); final EditableTextState editableTextState = tester.state<EditableTextState>(find.byType(EditableText)); editableTextState.spellCheckResults = const SpellCheckResults( '', <SuggestionSpan>[ SuggestionSpan(TextRange(start: 0, end: 0), <String>['something']), ], ); final Widget spellCheckToolbar = TextField.defaultSpellCheckSuggestionsToolbarBuilder( builderContext, editableTextState, ); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: expect(spellCheckToolbar, isA<CupertinoSpellCheckSuggestionsToolbar>()); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(spellCheckToolbar, isA<SpellCheckSuggestionsToolbar>()); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); testWidgets('Builds the corresponding default spell check configuration by platform', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; final SpellCheckConfiguration expectedConfiguration; switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: expectedConfiguration = SpellCheckConfiguration( misspelledTextStyle: CupertinoTextField.cupertinoMisspelledTextStyle, misspelledSelectionColor: CupertinoTextField.kMisspelledSelectionColor, spellCheckService: DefaultSpellCheckService(), spellCheckSuggestionsToolbarBuilder: CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expectedConfiguration = SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, spellCheckService: DefaultSpellCheckService(), spellCheckSuggestionsToolbarBuilder: TextField.defaultSpellCheckSuggestionsToolbarBuilder, ); } await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Center( child: TextField( autofocus: true, spellCheckConfiguration: SpellCheckConfiguration(), ), ), ), ), ); final EditableTextState editableTextState = tester.state<EditableTextState>(find.byType(EditableText)); expect( editableTextState.spellCheckConfiguration.misspelledTextStyle, expectedConfiguration.misspelledTextStyle, ); expect( editableTextState.spellCheckConfiguration.misspelledSelectionColor, expectedConfiguration.misspelledSelectionColor, ); expect( editableTextState.spellCheckConfiguration.spellCheckService.runtimeType, expectedConfiguration.spellCheckService.runtimeType, ); expect( editableTextState.spellCheckConfiguration.spellCheckSuggestionsToolbarBuilder, expectedConfiguration.spellCheckSuggestionsToolbarBuilder, ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); testWidgets('text selection toolbar is hidden on tap down on desktop platforms', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'blah1 blah2', ); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: TextField( controller: controller, ), ), ), ), ); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 8), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); gesture = await tester.startGesture( textOffsetToPosition(tester, 2), kind: PointerDeviceKind.mouse, ); await tester.pump(); // After the gesture is down but not up, the toolbar is already gone. expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); await gesture.up(); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. variant: TargetPlatformVariant.all(excluding: TargetPlatformVariant.mobile().values), ); testWidgets('Text processing actions are added to the toolbar', (WidgetTester tester) async { const String initialText = 'I love Flutter'; final TextEditingController controller = _textEditingController(text: initialText); final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Long press to put the cursor after the "F". final int index = initialText.indexOf('F'); await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pump(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 7, extentOffset: 14)); // The toolbar is visible and the text processing actions are visible on Android. final bool areTextActionsSupported = defaultTargetPlatform == TargetPlatform.android; expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); expect(find.text(fakeAction1Label), areTextActionsSupported ? findsOneWidget : findsNothing); expect(find.text(fakeAction2Label), areTextActionsSupported ? findsOneWidget : findsNothing); }, variant: TargetPlatformVariant.all(), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets( 'Text processing actions are not added to the toolbar for obscured text', (WidgetTester tester) async { const String initialText = 'I love Flutter'; final TextEditingController controller = _textEditingController(text: initialText); final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( obscureText: true, controller: controller, ), ), ), ); // Long press to put the cursor after the "F". final int index = initialText.indexOf('F'); await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pump(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 14)); // The toolbar is visible but does not contain the text processing actions. expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); expect(find.text(fakeAction1Label), findsNothing); expect(find.text(fakeAction2Label), findsNothing); }, variant: TargetPlatformVariant.all(), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets( 'Text processing actions are not added to the toolbar if selection is collapsed (Android only)', (WidgetTester tester) async { const String initialText = 'I love Flutter'; final TextEditingController controller = _textEditingController(text: initialText); final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Open the text selection toolbar. await showSelectionMenuAt(tester, controller, initialText.indexOf('F')); await skipPastScrollingAnimation(tester); // The toolbar is visible but does not contain the text processing actions. expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); expect(controller.selection.isCollapsed, true); expect(find.text(fakeAction1Label), findsNothing); expect(find.text(fakeAction2Label), findsNothing); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets( 'Invoke a text processing action that does not return a value (Android only)', (WidgetTester tester) async { const String initialText = 'I love Flutter'; final TextEditingController controller = _textEditingController(text: initialText); final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Long press to put the cursor after the "F". final int index = initialText.indexOf('F'); await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pump(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 7, extentOffset: 14)); // Run an action that does not return a processed text. await tester.tap(find.text(fakeAction2Label)); await tester.pump(const Duration(milliseconds: 200)); // The action was correctly called. expect(mockProcessTextHandler.lastCalledActionId, fakeAction2Id); expect(mockProcessTextHandler.lastTextToProcess, 'Flutter'); // The text field was not updated. expect(controller.text, initialText); // The toolbar is no longer visible. expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets( 'Invoking a text processing action that returns a value replaces the selection (Android only)', (WidgetTester tester) async { const String initialText = 'I love Flutter'; final TextEditingController controller = _textEditingController(text: initialText); final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( controller: controller, ), ), ), ); // Long press to put the cursor after the "F". final int index = initialText.indexOf('F'); await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pump(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 7, extentOffset: 14)); // Run an action that returns a processed text. await tester.tap(find.text(fakeAction1Label)); await tester.pump(const Duration(milliseconds: 200)); // The action was correctly called. expect(mockProcessTextHandler.lastCalledActionId, fakeAction1Id); expect(mockProcessTextHandler.lastTextToProcess, 'Flutter'); // The text field was updated. expect(controller.text, 'I love Flutter!!!'); // The toolbar is no longer visible. expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets( 'Invoking a text processing action that returns a value does not replace the selection of a readOnly text field (Android only)', (WidgetTester tester) async { const String initialText = 'I love Flutter'; final TextEditingController controller = _textEditingController(text: initialText); final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); await tester.pumpWidget( MaterialApp( home: Material( child: TextField( readOnly: true, controller: controller, ), ), ), ); // Long press to put the cursor after the "F". final int index = initialText.indexOf('F'); await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pump(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 7, extentOffset: 14)); // Run an action that returns a processed text. await tester.tap(find.text(fakeAction1Label)); await tester.pump(const Duration(milliseconds: 200)); // The Action was correctly called. expect(mockProcessTextHandler.lastCalledActionId, fakeAction1Id); expect(mockProcessTextHandler.lastTextToProcess, 'Flutter'); // The text field was not updated. expect(controller.text, initialText); // The toolbar is no longer visible. expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Start the floating cursor on long tap', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; final TextEditingController controller = _textEditingController( text: 'abcd', ); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: RepaintBoundary( key: const ValueKey<int>(1), child: TextField( autofocus: true, controller: controller, ), ) ), ), ), ); // Wait for autofocus. await tester.pumpAndSettle(); final Offset textFieldCenter = tester.getCenter(find.byType(TextField)); final TestGesture gesture = await tester.startGesture(textFieldCenter); await tester.pump(kLongPressTimeout); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('text_field_floating_cursor.regular_and_floating_both.material.0.png'), ); await gesture.moveTo(Offset(10, textFieldCenter.dy)); await tester.pump(); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('text_field_floating_cursor.only_floating_cursor.material.0.png'), ); await gesture.up(); EditableText.debugDeterministicCursor = false; }, variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); testWidgets('Cursor should not blink when long-pressing to show floating cursor.', (WidgetTester tester) async { final TextEditingController controller = _textEditingController( text: 'abcdefghijklmnopqr', ); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextField( autofocus: true, controller: controller, cursorOpacityAnimates: false ) ), ), ), ); final EditableTextState state = tester.state(find.byType(EditableText)); Future<void> checkCursorBlinking({ bool isBlinking = true }) async { bool initialShowCursor = true; if (isBlinking) { initialShowCursor = state.renderEditable.showCursor.value; } await tester.pump(state.cursorBlinkInterval); expect(state.cursorCurrentlyVisible, equals(isBlinking ? !initialShowCursor : initialShowCursor)); await tester.pump(state.cursorBlinkInterval); expect(state.cursorCurrentlyVisible, equals(initialShowCursor)); await tester.pump(state.cursorBlinkInterval); expect(state.cursorCurrentlyVisible, equals(isBlinking ? !initialShowCursor : initialShowCursor)); await tester.pump(state.cursorBlinkInterval); expect(state.cursorCurrentlyVisible, equals(initialShowCursor)); } // Wait for autofocus. await tester.pumpAndSettle(); // Before long-pressing, the cursor should blink. await checkCursorBlinking(); final TestGesture gesture = await tester.startGesture(tester.getTopLeft(find.byType(TextField))); await tester.pump(kLongPressTimeout); // When long-pressing, the cursor shouldn't blink. await checkCursorBlinking(isBlinking: false); await gesture.moveBy(const Offset(20, 0)); await tester.pump(); // When long-pressing and dragging to move the cursor, the cursor shouldn't blink. await checkCursorBlinking(isBlinking: false); await gesture.up(); // After finishing the long-press, the cursor should blink. await checkCursorBlinking(); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); } /// A Simple widget for testing the obscure text. class _ObscureTextTestWidget extends StatefulWidget { const _ObscureTextTestWidget({ required this.controller }); final TextEditingController controller; @override _ObscureTextTestWidgetState createState() => _ObscureTextTestWidgetState(); } class _ObscureTextTestWidgetState extends State<_ObscureTextTestWidget> { bool _obscureText = false; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { return Column( children: <Widget>[ TextField( obscureText: _obscureText, controller: widget.controller, ), ElevatedButton( onPressed: () => setState(() {_obscureText = !_obscureText;}), child: const SizedBox.shrink(), ), ], ); }, ), ), ); } } typedef FormatEditUpdateCallback = void Function(TextEditingValue oldValue, TextEditingValue newValue); // On web, key events in text fields are handled by the browser. const bool areKeyEventsHandledByPlatform = isBrowser; class CupertinoLocalizationsDelegate extends LocalizationsDelegate<CupertinoLocalizations> { @override bool isSupported(Locale locale) => true; @override Future<CupertinoLocalizations> load(Locale locale) => DefaultCupertinoLocalizations.load(locale); @override bool shouldReload(CupertinoLocalizationsDelegate old) => false; } class MaterialLocalizationsDelegate extends LocalizationsDelegate<MaterialLocalizations> { @override bool isSupported(Locale locale) => true; @override Future<MaterialLocalizations> load(Locale locale) => DefaultMaterialLocalizations.load(locale); @override bool shouldReload(MaterialLocalizationsDelegate old) => false; } class WidgetsLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocalizations> { @override bool isSupported(Locale locale) => true; @override Future<WidgetsLocalizations> load(Locale locale) => DefaultWidgetsLocalizations.load(locale); @override bool shouldReload(WidgetsLocalizationsDelegate old) => false; } Widget overlay({ required Widget child }) { final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) { return Center( child: Material( child: child, ), ); }, ); addTearDown(() => entry..remove()..dispose()); return overlayWithEntry(entry); } Widget overlayWithEntry(OverlayEntry entry) { return Localizations( locale: const Locale('en', 'US'), delegates: <LocalizationsDelegate<dynamic>>[ WidgetsLocalizationsDelegate(), MaterialLocalizationsDelegate(), CupertinoLocalizationsDelegate(), ], child: DefaultTextEditingShortcuts( child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), child: Overlay( initialEntries: <OverlayEntry>[ entry, ], ), ), ), ), ); } Widget boilerplate({ required Widget child, ThemeData? theme }) { return MaterialApp( theme: theme, home: Localizations( locale: const Locale('en', 'US'), delegates: <LocalizationsDelegate<dynamic>>[ WidgetsLocalizationsDelegate(), MaterialLocalizationsDelegate(), ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), child: Center( child: Material( child: child, ), ), ), ), ), ); } Future<void> skipPastScrollingAnimation(WidgetTester tester) async { await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); } double getOpacity(WidgetTester tester, Finder finder) { return tester.widget<FadeTransition>( find.ancestor( of: finder, matching: find.byType(FadeTransition), ), ).opacity.value; } class TestFormatter extends TextInputFormatter { TestFormatter(this.onFormatEditUpdate); FormatEditUpdateCallback onFormatEditUpdate; @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { onFormatEditUpdate(oldValue, newValue); return newValue; } } FocusNode _focusNode() { final FocusNode result = FocusNode(); addTearDown(result.dispose); return result; } TextEditingController _textEditingController({String text = ''}) { final TextEditingController result = TextEditingController(text: text); addTearDown(result.dispose); return result; }
flutter/packages/flutter/test/material/text_field_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/text_field_test.dart", "repo_id": "flutter", "token_count": 252657 }
667
// 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 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; import 'feedback_tester.dart'; const String tooltipText = 'TIP'; Finder _findTooltipContainer(String tooltipText) { return find.ancestor( of: find.text(tooltipText), matching: find.byType(Container), ); } void main() { testWidgets('Does tooltip end up in the right place - center', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 300.0, top: 0.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 20.0, padding: const EdgeInsets.all(5.0), verticalOffset: 20.0, preferBelow: false, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen * o * y=0 * | * }- 20.0 vertical offset, of which 10.0 is in the screen edge margin * +----+ * \- (5.0 padding in height) * | | * |- 20 height * +----+ * /- (5.0 padding in height) * * *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); final Offset tipInGlobal = tip.localToGlobal(tip.size.topCenter(Offset.zero)); // The exact position of the left side depends on the font the test framework // happens to pick, so we don't test that. expect(tipInGlobal.dx, 300.0); expect(tipInGlobal.dy, 20.0); }); testWidgets('Does tooltip end up in the right place - center with padding outside overlay', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Padding( padding: const EdgeInsets.all(20), child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 300.0, top: 0.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 20.0, padding: const EdgeInsets.all(5.0), verticalOffset: 20.0, preferBelow: false, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /************************ 800x600 screen * ________________ * }- 20.0 padding outside overlay * | o | * y=0 * | | | * }- 20.0 vertical offset, of which 10.0 is in the screen edge margin * | +----+ | * \- (5.0 padding in height) * | | | | * |- 20 height * | +----+ | * /- (5.0 padding in height) * |________________| * * * } - 20.0 padding outside overlay ************************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); final Offset tipInGlobal = tip.localToGlobal(tip.size.topCenter(Offset.zero)); // The exact position of the left side depends on the font the test framework // happens to pick, so we don't test that. expect(tipInGlobal.dx, 320.0); expect(tipInGlobal.dy, 40.0); }); testWidgets('Material2 - Does tooltip end up in the right place - top left', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 0.0, top: 0.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 20.0, padding: const EdgeInsets.all(5.0), verticalOffset: 20.0, preferBelow: false, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen *o * y=0 *| * }- 20.0 vertical offset, of which 10.0 is in the screen edge margin *+----+ * \- (5.0 padding in height) *| | * |- 20 height *+----+ * /- (5.0 padding in height) * * *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(24.0)); // 14.0 height + 5.0 padding * 2 (top, bottom) expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)), equals(const Offset(10.0, 20.0))); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Material3 - Does tooltip end up in the right place - top left', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 0.0, top: 0.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 20.0, padding: const EdgeInsets.all(5.0), verticalOffset: 20.0, preferBelow: false, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen *o * y=0 *| * }- 20.0 vertical offset, of which 10.0 is in the screen edge margin *+----+ * \- (5.0 padding in height) *| | * |- 20 height *+----+ * /- (5.0 padding in height) * * *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(30.0)); // 20.0 height + 5.0 padding * 2 (top, bottom) expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)), equals(const Offset(10.0, 20.0))); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Does tooltip end up in the right place - center prefer above fits', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 400.0, top: 300.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 100.0, padding: EdgeInsets.zero, verticalOffset: 100.0, preferBelow: false, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen * ___ * }- 10.0 margin * |___| * }-100.0 height * | * }-100.0 vertical offset * o * y=300.0 * * * * * * *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(100.0)); expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)).dy, equals(100.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dy, equals(200.0)); }); testWidgets('Does tooltip end up in the right place - center prefer above does not fit', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 400.0, top: 299.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 190.0, padding: EdgeInsets.zero, verticalOffset: 100.0, preferBelow: false, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) // we try to put it here but it doesn't fit: /********************* 800x600 screen * ___ * }- 10.0 margin * |___| * }-190.0 height (starts at y=9.0) * | * }-100.0 vertical offset * o * y=299.0 * * * * * * *********************/ // so we put it here: /********************* 800x600 screen * * * * * o * y=299.0 * _|_ * }-100.0 vertical offset * |___| * }-190.0 height * * }- 10.0 margin *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(190.0)); expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)).dy, equals(399.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dy, equals(589.0)); }); testWidgets('Does tooltip end up in the right place - center prefer below fits', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 400.0, top: 300.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 190.0, padding: EdgeInsets.zero, verticalOffset: 100.0, preferBelow: true, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen * * * * * o * y=300.0 * _|_ * }-100.0 vertical offset * |___| * }-190.0 height * * }- 10.0 margin *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(190.0)); expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)).dy, equals(400.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dy, equals(590.0)); }); testWidgets('Material2 - Does tooltip end up in the right place - way off to the right', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 1600.0, top: 300.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 10.0, padding: EdgeInsets.zero, verticalOffset: 10.0, preferBelow: true, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen * * * * * * y=300.0; target --> o * ___| * }-10.0 vertical offset * |___| * }-10.0 height * * * * }-10.0 margin *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(14.0)); expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)).dy, equals(310.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dx, equals(790.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dy, equals(324.0)); }); testWidgets('Material3 - Does tooltip end up in the right place - way off to the right', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 1600.0, top: 300.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 10.0, padding: EdgeInsets.zero, verticalOffset: 10.0, preferBelow: true, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen * * * * * * y=300.0; target --> o * ___| * }-10.0 vertical offset * |___| * }-10.0 height * * * * }-10.0 margin *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(20.0)); expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)).dy, equals(310.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dx, equals(790.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dy, equals(330.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Material2 - Does tooltip end up in the right place - near the edge', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 780.0, top: 300.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 10.0, padding: EdgeInsets.zero, verticalOffset: 10.0, preferBelow: true, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen * * * * * o * y=300.0 * __| * }-10.0 vertical offset * |___| * }-10.0 height * * * * }-10.0 margin *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(14.0)); expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)).dy, equals(310.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dx, equals(790.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dy, equals(324.0)); }); testWidgets('Material3 - Does tooltip end up in the right place - near the edge', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 780.0, top: 300.0, child: Tooltip( key: tooltipKey, message: tooltipText, height: 10.0, padding: EdgeInsets.zero, verticalOffset: 10.0, preferBelow: true, child: const SizedBox.shrink(), ), ), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) /********************* 800x600 screen * * * * * o * y=300.0 * __| * }-10.0 vertical offset * |___| * }-10.0 height * * * * }-10.0 margin *********************/ final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(20.0)); expect(tip.localToGlobal(tip.size.topLeft(Offset.zero)).dy, equals(310.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dx, equals(790.0)); expect(tip.localToGlobal(tip.size.bottomRight(Offset.zero)).dy, equals(330.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Tooltip should be fully visible when MediaQuery.viewInsets > 0', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/23666 Widget materialAppWithViewInsets(double viewInsetsHeight) { final Widget scaffold = Scaffold( body: const TextField(), floatingActionButton: FloatingActionButton( tooltip: tooltipText, onPressed: () { /* do nothing */ }, child: const Icon(Icons.add), ), ); return MediaQuery( data: MediaQueryData( viewInsets: EdgeInsets.only(bottom: viewInsetsHeight), ), child: MaterialApp( useInheritedMediaQuery: true, home: scaffold, ), ); } // Start with MediaQuery.viewInsets.bottom = 0 await tester.pumpWidget(materialAppWithViewInsets(0)); // Show FAB tooltip final Finder fabFinder = find.byType(FloatingActionButton); await tester.longPress(fabFinder); await tester.pump(const Duration(milliseconds: 500)); expect(find.byType(Tooltip), findsOneWidget); // FAB tooltip should be above FAB RenderBox tip = tester.renderObject(_findTooltipContainer(tooltipText)); Offset fabTopRight = tester.getTopRight(fabFinder); Offset tooltipTopRight = tip.localToGlobal(tip.size.topRight(Offset.zero)); expect(tooltipTopRight.dy, lessThan(fabTopRight.dy)); // Simulate Keyboard opening (MediaQuery.viewInsets.bottom = 300)) await tester.pumpWidget(materialAppWithViewInsets(300)); // Wait for the tooltip to dismiss. await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); // Show FAB tooltip await tester.longPress(fabFinder); await tester.pump(const Duration(milliseconds: 500)); expect(find.byType(Tooltip), findsOneWidget); // FAB tooltip should still be above FAB tip = tester.renderObject(_findTooltipContainer(tooltipText)); fabTopRight = tester.getTopRight(fabFinder); tooltipTopRight = tip.localToGlobal(tip.size.topRight(Offset.zero)); expect(tooltipTopRight.dy, lessThan(fabTopRight.dy)); }); testWidgets('Custom tooltip margin', (WidgetTester tester) async { const double customMarginValue = 10.0; final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Tooltip( key: tooltipKey, message: tooltipText, padding: EdgeInsets.zero, margin: const EdgeInsets.all(customMarginValue), child: const SizedBox.shrink(), ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final Offset topLeftTipInGlobal = tester.getTopLeft( _findTooltipContainer(tooltipText), ); final Offset topLeftTooltipContentInGlobal = tester.getTopLeft(find.text(tooltipText)); expect(topLeftTooltipContentInGlobal.dx, topLeftTipInGlobal.dx + customMarginValue); expect(topLeftTooltipContentInGlobal.dy, topLeftTipInGlobal.dy + customMarginValue); final Offset topRightTipInGlobal = tester.getTopRight( _findTooltipContainer(tooltipText), ); final Offset topRightTooltipContentInGlobal = tester.getTopRight(find.text(tooltipText)); expect(topRightTooltipContentInGlobal.dx, topRightTipInGlobal.dx - customMarginValue); expect(topRightTooltipContentInGlobal.dy, topRightTipInGlobal.dy + customMarginValue); final Offset bottomLeftTipInGlobal = tester.getBottomLeft( _findTooltipContainer(tooltipText), ); final Offset bottomLeftTooltipContentInGlobal = tester.getBottomLeft(find.text(tooltipText)); expect(bottomLeftTooltipContentInGlobal.dx, bottomLeftTipInGlobal.dx + customMarginValue); expect(bottomLeftTooltipContentInGlobal.dy, bottomLeftTipInGlobal.dy - customMarginValue); final Offset bottomRightTipInGlobal = tester.getBottomRight( _findTooltipContainer(tooltipText), ); final Offset bottomRightTooltipContentInGlobal = tester.getBottomRight(find.text(tooltipText)); expect(bottomRightTooltipContentInGlobal.dx, bottomRightTipInGlobal.dx - customMarginValue); expect(bottomRightTooltipContentInGlobal.dy, bottomRightTipInGlobal.dy - customMarginValue); }); testWidgets('Material2 - Default tooltip message textStyle - light', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: Tooltip( key: tooltipKey, message: tooltipText, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), )); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final TextStyle textStyle = tester.widget<Text>(find.text(tooltipText)).style!; expect(textStyle.color, Colors.white); expect(textStyle.fontFamily, 'Roboto'); expect(textStyle.decoration, TextDecoration.none); expect(textStyle.debugLabel, '((englishLike bodyMedium 2014).merge(blackMountainView bodyMedium)).copyWith'); }); testWidgets('Material3 - Default tooltip message textStyle - light', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget(MaterialApp( home: Tooltip( key: tooltipKey, message: tooltipText, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), )); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final TextStyle textStyle = tester.widget<Text>(find.text(tooltipText)).style!; expect(textStyle.color, Colors.white); expect(textStyle.fontFamily, 'Roboto'); expect(textStyle.decoration, TextDecoration.none); expect( textStyle.debugLabel, '((englishLike bodyMedium 2021).merge((blackMountainView bodyMedium).apply)).copyWith', ); }); testWidgets('Material2 - Default tooltip message textStyle - dark', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget(MaterialApp( theme: ThemeData( useMaterial3: false, brightness: Brightness.dark, ), home: Tooltip( key: tooltipKey, message: tooltipText, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), )); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final TextStyle textStyle = tester.widget<Text>(find.text(tooltipText)).style!; expect(textStyle.color, Colors.black); expect(textStyle.fontFamily, 'Roboto'); expect(textStyle.decoration, TextDecoration.none); expect(textStyle.debugLabel, '((englishLike bodyMedium 2014).merge(whiteMountainView bodyMedium)).copyWith'); }); testWidgets('Material3 - Default tooltip message textStyle - dark', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget(MaterialApp( theme: ThemeData(brightness: Brightness.dark), home: Tooltip( key: tooltipKey, message: tooltipText, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), )); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final TextStyle textStyle = tester.widget<Text>(find.text(tooltipText)).style!; expect(textStyle.color, Colors.black); expect(textStyle.fontFamily, 'Roboto'); expect(textStyle.decoration, TextDecoration.none); expect(textStyle.debugLabel, '((englishLike bodyMedium 2021).merge((whiteMountainView bodyMedium).apply)).copyWith'); }); testWidgets('Custom tooltip message textStyle', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget(MaterialApp( home: Tooltip( key: tooltipKey, textStyle: const TextStyle( color: Colors.orange, decoration: TextDecoration.underline, ), message: tooltipText, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), )); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final TextStyle textStyle = tester.widget<Text>(find.text(tooltipText)).style!; expect(textStyle.color, Colors.orange); expect(textStyle.fontFamily, null); expect(textStyle.decoration, TextDecoration.underline); }); testWidgets('Custom tooltip message textAlign', (WidgetTester tester) async { Future<void> pumpTooltipWithTextAlign({TextAlign? textAlign}) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget( MaterialApp( home: Tooltip( key: tooltipKey, textAlign: textAlign, message: tooltipText, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) } // Default value should be TextAlign.start await pumpTooltipWithTextAlign(); TextAlign textAlign = tester.widget<Text>(find.text(tooltipText)).textAlign!; expect(textAlign, TextAlign.start); await pumpTooltipWithTextAlign(textAlign: TextAlign.center); textAlign = tester.widget<Text>(find.text(tooltipText)).textAlign!; expect(textAlign, TextAlign.center); await pumpTooltipWithTextAlign(textAlign: TextAlign.end); textAlign = tester.widget<Text>(find.text(tooltipText)).textAlign!; expect(textAlign, TextAlign.end); }); testWidgets('Tooltip overlay respects ambient Directionality', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/40702. Widget buildApp(String text, TextDirection textDirection) { return MaterialApp( home: Directionality( textDirection: textDirection, child: Center( child: Tooltip( message: text, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ), ), ); } await tester.pumpWidget(buildApp(tooltipText, TextDirection.rtl)); await tester.longPress(find.byType(Tooltip)); expect(find.text(tooltipText), findsOneWidget); RenderParagraph tooltipRenderParagraph = tester.renderObject<RenderParagraph>(find.text(tooltipText)); expect(tooltipRenderParagraph.textDirection, TextDirection.rtl); await tester.pump(const Duration(seconds: 10)); await tester.pumpAndSettle(); await tester.pump(); await tester.pumpWidget(buildApp(tooltipText, TextDirection.ltr)); await tester.longPress(find.byType(Tooltip)); expect(find.text(tooltipText), findsOneWidget); tooltipRenderParagraph = tester.renderObject<RenderParagraph>(find.text(tooltipText)); expect(tooltipRenderParagraph.textDirection, TextDirection.ltr); }); testWidgets('Tooltip overlay wrapped with a non-fallback DefaultTextStyle widget', (WidgetTester tester) async { // A Material widget is needed as an ancestor of the Text widget. // It is invalid to have text in a Material application that // does not have a Material ancestor. final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget(MaterialApp( home: Tooltip( key: tooltipKey, message: tooltipText, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), )); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final TextStyle textStyle = tester.widget<DefaultTextStyle>( find.ancestor( of: find.text(tooltipText), matching: find.byType(DefaultTextStyle), ).first, ).style; // The default fallback text style results in a text with a // double underline of Color(0xffffff00). expect(textStyle.decoration, isNot(TextDecoration.underline)); expect(textStyle.decorationColor, isNot(const Color(0xffffff00))); expect(textStyle.decorationStyle, isNot(TextDecorationStyle.double)); }); testWidgets('Material2 - Does tooltip end up with the right default size, shape, and color', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Tooltip( key: tooltipKey, message: tooltipText, child: const SizedBox.shrink(), ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final RenderBox tip = tester.renderObject(_findTooltipContainer(tooltipText)); expect(tip.size.height, equals(32.0)); expect(tip.size.width, equals(74.0)); expect(tip, paints..rrect( rrect: RRect.fromRectAndRadius(tip.paintBounds, const Radius.circular(4.0)), color: const Color(0xe6616161), )); final Container tooltipContainer = tester.firstWidget<Container>(_findTooltipContainer(tooltipText)); expect(tooltipContainer.padding, const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0)); }); testWidgets('Material3 - Does tooltip end up with the right default size, shape, and color', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Tooltip( key: tooltipKey, message: tooltipText, child: const SizedBox.shrink(), ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final RenderBox tip = tester.renderObject(_findTooltipContainer(tooltipText)); expect(tip.size.height, equals(32.0)); expect(tip.size.width, equals(74.75)); expect(tip, paints..rrect( rrect: RRect.fromRectAndRadius(tip.paintBounds, const Radius.circular(4.0)), color: const Color(0xe6616161), )); final Container tooltipContainer = tester.firstWidget<Container>(_findTooltipContainer(tooltipText)); expect(tooltipContainer.padding, const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0)); }); testWidgets('Material2 - Tooltip default size, shape, and color test for Desktop', (WidgetTester tester) async { // Regressing test for https://github.com/flutter/flutter/issues/68601 final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Tooltip( key: tooltipKey, message: tooltipText, child: const SizedBox.shrink(), ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final RenderParagraph tooltipRenderParagraph = tester.renderObject<RenderParagraph>(find.text(tooltipText)); expect(tooltipRenderParagraph.textSize.height, equals(12.0)); final RenderBox tooltipRenderBox = tester.renderObject(_findTooltipContainer(tooltipText)); expect(tooltipRenderBox.size.height, equals(24.0)); expect(tooltipRenderBox, paints..rrect( rrect: RRect.fromRectAndRadius(tooltipRenderBox.paintBounds, const Radius.circular(4.0)), color: const Color(0xe6616161), )); final Container tooltipContainer = tester.firstWidget<Container>(_findTooltipContainer(tooltipText)); expect(tooltipContainer.padding, const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS, TargetPlatform.linux, TargetPlatform.windows})); testWidgets('Material3 - Tooltip default size, shape, and color test for Desktop', (WidgetTester tester) async { // Regressing test for https://github.com/flutter/flutter/issues/68601 final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget( MaterialApp( home: Tooltip( key: tooltipKey, message: tooltipText, child: const SizedBox.shrink(), ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final RenderParagraph tooltipRenderParagraph = tester.renderObject<RenderParagraph>(find.text(tooltipText)); expect(tooltipRenderParagraph.textSize.height, equals(17.0)); final RenderBox tooltipRenderBox = tester.renderObject(_findTooltipContainer(tooltipText)); expect(tooltipRenderBox.size.height, equals(25.0)); expect(tooltipRenderBox, paints..rrect( rrect: RRect.fromRectAndRadius(tooltipRenderBox.paintBounds, const Radius.circular(4.0)), color: const Color(0xe6616161), )); final Container tooltipContainer = tester.firstWidget<Container>(_findTooltipContainer(tooltipText)); expect(tooltipContainer.padding, const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS, TargetPlatform.linux, TargetPlatform.windows}), skip: kIsWeb && !isCanvasKit, // https://github.com/flutter/flutter/issues/99933 ); testWidgets('Material2 - Can tooltip decoration be customized', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); const Decoration customDecoration = ShapeDecoration( shape: StadiumBorder(), color: Color(0x80800000), ); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Tooltip( key: tooltipKey, decoration: customDecoration, message: tooltipText, child: const SizedBox.shrink(), ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(32.0)); expect(tip.size.width, equals(74.0)); expect(tip, paints..rrect(color: const Color(0x80800000))); }); testWidgets('Material3 - Can tooltip decoration be customized', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); const Decoration customDecoration = ShapeDecoration( shape: StadiumBorder(), color: Color(0x80800000), ); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( MaterialApp( home: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Tooltip( key: tooltipKey, decoration: customDecoration, message: tooltipText, child: const SizedBox.shrink(), ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(32.0)); expect(tip.size.width, equals(74.75)); expect(tip, paints..rrect(color: const Color(0x80800000))); }); testWidgets('Tooltip stays after long press', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Center( child: Tooltip( triggerMode: TooltipTriggerMode.longPress, message: tooltipText, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ), ), ); final Finder tooltip = find.byType(Tooltip); TestGesture gesture = await tester.startGesture(tester.getCenter(tooltip)); // long press reveals tooltip await tester.pump(kLongPressTimeout); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tooltipText), findsOneWidget); await gesture.up(); // tap (down, up) gesture hides tooltip, since its not // a long press await tester.tap(tooltip); await tester.pump(); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); // long press once more gesture = await tester.startGesture(tester.getCenter(tooltip)); await tester.pump(); await tester.pump(const Duration(milliseconds: 300)); expect(find.text(tooltipText), findsNothing); await tester.pump(kLongPressTimeout); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tooltipText), findsOneWidget); // keep holding the long press, should still show tooltip await tester.pump(kLongPressTimeout); expect(find.text(tooltipText), findsOneWidget); await gesture.up(); }); testWidgets('Tooltip dismiss countdown begins on long press release', (WidgetTester tester) async { // Specs: https://github.com/flutter/flutter/issues/4182 const Duration showDuration = Duration(seconds: 1); const Duration eternity = Duration(days: 9999); await setWidgetForTooltipMode(tester, TooltipTriggerMode.longPress, showDuration: showDuration); final Finder tooltip = find.byType(Tooltip); final TestGesture gesture = await tester.startGesture(tester.getCenter(tooltip)); await tester.pump(kLongPressTimeout); expect(find.text(tooltipText), findsOneWidget); // Keep holding to prevent the tooltip from dismissing. await tester.pump(eternity); expect(find.text(tooltipText), findsOneWidget); await tester.pump(); expect(find.text(tooltipText), findsOneWidget); await gesture.up(); await tester.pump(); expect(find.text(tooltipText), findsOneWidget); await tester.pump(showDuration); await tester.pump(const Duration(milliseconds: 500)); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip is dismissed after a long press and showDuration expired', (WidgetTester tester) async { const Duration showDuration = Duration(seconds: 3); await setWidgetForTooltipMode(tester, TooltipTriggerMode.longPress, showDuration: showDuration); final Finder tooltip = find.byType(Tooltip); final TestGesture gesture = await tester.startGesture(tester.getCenter(tooltip)); // Long press reveals tooltip await tester.pump(kLongPressTimeout); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tooltipText), findsOneWidget); await gesture.up(); // Tooltip is dismissed after showDuration expired await tester.pump(showDuration); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip is dismissed after a tap and showDuration expired', (WidgetTester tester) async { const Duration showDuration = Duration(seconds: 3); await setWidgetForTooltipMode(tester, TooltipTriggerMode.tap, showDuration: showDuration); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); await _testGestureTap(tester, tooltip); expect(find.text(tooltipText), findsOneWidget); // Tooltip is dismissed after showDuration expired await tester.pump(showDuration); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip is dismissed after tap to dismiss immediately', (WidgetTester tester) async { await setWidgetForTooltipMode(tester, TooltipTriggerMode.tap); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); // Tap to trigger the tooltip. await _testGestureTap(tester, tooltip); expect(find.text(tooltipText), findsOneWidget); // Tap to dismiss the tooltip. Tooltip is dismissed immediately. await _testGestureTap(tester, find.text(tooltipText)); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip is not dismissed after tap if enableTapToDismiss is false', (WidgetTester tester) async { await setWidgetForTooltipMode(tester, TooltipTriggerMode.tap, enableTapToDismiss: false); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); // Tap to trigger the tooltip. await _testGestureTap(tester, tooltip); expect(find.text(tooltipText), findsOneWidget); // Tap the tooltip. Tooltip is not dismissed . await _testGestureTap(tester, find.text(tooltipText)); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tooltipText), findsOneWidget); }); testWidgets('Tooltip is dismissed after a tap and showDuration expired when competing with a GestureDetector', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/98854 const Duration showDuration = Duration(seconds: 3); await tester.pumpWidget( MaterialApp( home: GestureDetector( onVerticalDragStart: (_) { /* Do nothing */ }, child: const Tooltip( message: tooltipText, triggerMode: TooltipTriggerMode.tap, showDuration: showDuration, child: SizedBox(width: 100.0, height: 100.0), ), ), ), ); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); await tester.tap(tooltip); // Wait for GestureArena disambiguation, delay is kPressTimeout to disambiguate // between onTap and onVerticalDragStart await tester.pump(kPressTimeout); expect(find.text(tooltipText), findsOneWidget); // Tooltip is dismissed after showDuration expired await tester.pump(showDuration); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tooltipText), findsNothing); }); testWidgets('Dispatch the mouse events before tip overlay detached', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/96890 const Duration waitDuration = Duration.zero; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { return gesture.removePointer(); }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); // Trigger the tip overlay. final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); // Remove the `Tooltip` widget. await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.shrink(), ), ), ); // The tooltip should be removed, including the overlay child. expect(find.text(tooltipText), findsNothing); expect(find.byTooltip(tooltipText), findsNothing); }); testWidgets('Calling ensureTooltipVisible on an unmounted TooltipState returns false', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/95851 await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); final TooltipState tooltipState = tester.state(find.byType(Tooltip)); expect(tooltipState.ensureTooltipVisible(), true); // Remove the tooltip. await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.shrink(), ), ), ); expect(tooltipState.ensureTooltipVisible(), false); }); testWidgets('Tooltip shows/hides when hovered', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { return gesture.removePointer(); }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(Offset.zero); await tester.pump(); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(find.text(tooltipText), findsOneWidget); // Wait a looong time to make sure that it doesn't go away if the mouse is // still over the widget. await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsOneWidget); await gesture.moveTo(Offset.zero); await tester.pump(); // Wait for it to disappear. await tester.pumpAndSettle(); await gesture.removePointer(); expect(find.text(tooltipText), findsNothing); }); // Regression test for https://github.com/flutter/flutter/issues/141644. // This allows the user to quickly explore the UI via tooltips. testWidgets('Tooltip shows without delay when the mouse moves from another tooltip', (WidgetTester tester) async { const Duration waitDuration = Durations.extralong1; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { return gesture.removePointer(); }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Column( children: <Widget>[ Tooltip( message: 'first tooltip', waitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), Tooltip( message: 'last tooltip', waitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), ], ), ), ); await gesture.moveTo(Offset.zero); await tester.pump(); await gesture.moveTo(tester.getCenter(find.byType(Tooltip).first)); await tester.pump(); // Wait for the first tooltip to appear. await tester.pump(waitDuration); expect(find.text('first tooltip'), findsOneWidget); expect(find.text('last tooltip'), findsNothing); // Move to the second tooltip and expect it to show up immediately. await gesture.moveTo(tester.getCenter(find.byType(Tooltip).last)); await tester.pump(); expect(find.text('first tooltip'), findsNothing); expect(find.text('last tooltip'), findsOneWidget); }); // Regression test for https://github.com/flutter/flutter/issues/142045. testWidgets('Tooltip shows/hides when the mouse hovers, and then exits and re-enters in quick succession', (WidgetTester tester) async { const Duration waitDuration = Durations.extralong1; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { return gesture.removePointer(); }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, exitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); Future<void> mouseEnterAndWaitUntilVisible() async { await gesture.moveTo(tester.getCenter(find.byType(Tooltip))); await tester.pump(); await tester.pump(waitDuration); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsOne); } Future<void> mouseExit() async { await gesture.moveTo(Offset.zero); await tester.pump(); } Future<void> performSequence(Iterable<Future<void> Function()> actions) async { for (final Future<void> Function() action in actions) { await action(); } } await performSequence(<Future<void> Function()>[mouseEnterAndWaitUntilVisible]); expect(find.text(tooltipText), findsOne); // Wait for reset. await mouseExit(); await tester.pump(const Duration(hours: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); await performSequence(<Future<void> Function()>[ mouseEnterAndWaitUntilVisible, mouseExit, mouseEnterAndWaitUntilVisible, ]); expect(find.text(tooltipText), findsOne); // Wait for reset. await mouseExit(); await tester.pump(const Duration(hours: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); await performSequence(<Future<void> Function()>[ mouseEnterAndWaitUntilVisible, mouseExit, mouseEnterAndWaitUntilVisible, mouseExit, mouseEnterAndWaitUntilVisible, ]); expect(find.text(tooltipText), findsOne); // Wait for reset. await mouseExit(); await tester.pump(const Duration(hours: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip text is also hoverable', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { return gesture.removePointer(); }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, child: Text('I am tool tip'), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(Offset.zero); await tester.pump(); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(find.text(tooltipText), findsOneWidget); // Wait a looong time to make sure that it doesn't go away if the mouse is // still over the widget. await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsOneWidget); // Hover to the tool tip text and verify the tooltip doesn't go away. await gesture.moveTo(tester.getTopLeft(find.text(tooltipText))); await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsOneWidget); await gesture.moveTo(Offset.zero); await tester.pump(); // Wait for it to disappear. await tester.pumpAndSettle(); await gesture.removePointer(); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip should not show more than one tooltip when hovered', (WidgetTester tester) async { const Duration waitDuration = Duration(milliseconds: 500); final UniqueKey innerKey = UniqueKey(); final UniqueKey outerKey = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Center( child: Tooltip( message: 'Outer', child: Container( key: outerKey, width: 100, height: 100, alignment: Alignment.centerRight, child: Tooltip( message: 'Inner', child: SizedBox( key: innerKey, width: 25, height: 100, ), ), ), ), ), ), ); TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { gesture?.removePointer(); }); // Both the inner and outer containers have tooltips associated with them, but only // the currently hovered one should appear, even though the pointer is inside both. final Finder outer = find.byKey(outerKey); final Finder inner = find.byKey(innerKey); await gesture.moveTo(Offset.zero); await tester.pump(); await gesture.moveTo(tester.getCenter(outer)); await tester.pump(); await gesture.moveTo(tester.getCenter(inner)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(find.text('Outer'), findsNothing); expect(find.text('Inner'), findsOneWidget); await gesture.moveTo(tester.getCenter(outer)); await tester.pump(); // Wait for it to switch. await tester.pumpAndSettle(); expect(find.text('Outer'), findsOneWidget); expect(find.text('Inner'), findsNothing); await gesture.moveTo(Offset.zero); // Wait for all tooltips to disappear. await tester.pumpAndSettle(); await gesture.removePointer(); gesture = null; expect(find.text('Outer'), findsNothing); expect(find.text('Inner'), findsNothing); }); testWidgets('Tooltip can be dismissed by escape key', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { if (gesture != null) { return gesture.removePointer(); } }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, child: Text('I am tool tip'), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(Offset.zero); await tester.pump(); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(find.text(tooltipText), findsOneWidget); // Try to dismiss the tooltip with the shortcut key await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); await gesture.removePointer(); gesture = null; }); testWidgets('Multiple Tooltips are dismissed by escape key', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; await tester.pumpWidget( const MaterialApp( home: Center( child: Column( children: <Widget>[ Tooltip( message: 'message1', waitDuration: waitDuration, showDuration: Duration(days: 1), child: Text('tooltip1'), ), Spacer(flex: 2), Tooltip( message: 'message2', waitDuration: waitDuration, showDuration: Duration(days: 1), child: Text('tooltip2'), ), ], ), ), ), ); tester.state<TooltipState>(find.byTooltip('message1')).ensureTooltipVisible(); tester.state<TooltipState>(find.byTooltip('message2')).ensureTooltipVisible(); await tester.pump(); await tester.pump(waitDuration); // Make sure both messages are on the screen. expect(find.text('message1'), findsOneWidget); expect(find.text('message2'), findsOneWidget); // Try to dismiss the tooltip with the shortcut key await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(find.text('message1'), findsNothing); expect(find.text('message2'), findsNothing); }); testWidgets('Tooltip does not attempt to show after unmount', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/54096. const Duration waitDuration = Duration(seconds: 1); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { return gesture.removePointer(); }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(Offset.zero); await tester.pump(); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Pump another random widget to unmount the Tooltip widget. await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox(), ), ), ); // If the issue regresses, an exception will be thrown while we are waiting. await tester.pump(waitDuration); }); testWidgets('Does tooltip contribute semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return Stack( children: <Widget>[ Positioned( left: 780.0, top: 300.0, child: Tooltip( key: tooltipKey, message: tooltipText, child: const SizedBox(width: 10.0, height: 10.0), ), ), ], ); }, ), ], ), ), ); final TestSemantics expected = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, tooltip: 'TIP', textDirection: TextDirection.ltr, ), ], ); expect(semantics, hasSemantics(expected, ignoreTransform: true, ignoreRect: true)); // This triggers a rebuild of the semantics because the tree changes. tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) expect(semantics, hasSemantics(expected, ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('Tooltip semantics does not merge into child', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) { return ListView( children: <Widget>[ const Text('before'), Tooltip( key: tooltipKey, showDuration: const Duration(seconds: 50), message: 'B', child: const Text('child'), ), const Text('after'), ], ); }, ), ], ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); // Starts the animation. await tester.pump(); // Make sure the fade in animation has started and the tooltip isn't transparent. await tester.pump(const Duration(seconds: 2)); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], children: <TestSemantics>[ TestSemantics(label: 'before'), TestSemantics(label: 'child', tooltip: 'B', children: <TestSemantics>[TestSemantics(label: 'B')]), TestSemantics(label: 'after'), ], ), ], ), ], ), ignoreId: true, ignoreRect: true, ignoreTransform: true, )); semantics.dispose(); }); testWidgets('Material2 - Tooltip text scales with textScaler', (WidgetTester tester) async { Widget buildApp(String text, { required TextScaler textScaler }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: MediaQuery( data: MediaQueryData(textScaler: textScaler), child: Directionality( textDirection: TextDirection.ltr, child: Navigator( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( builder: (BuildContext context) { return Center( child: Tooltip( message: text, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ); }, ); }, ), ), ), ); } await tester.pumpWidget(buildApp(tooltipText, textScaler: TextScaler.noScaling)); await tester.longPress(find.byType(Tooltip)); expect(find.text(tooltipText), findsOneWidget); expect(tester.getSize(find.text(tooltipText)), equals(const Size(42.0, 14.0))); RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(32.0)); await tester.pumpWidget(buildApp(tooltipText, textScaler: const TextScaler.linear(4.0))); await tester.longPress(find.byType(Tooltip)); expect(find.text(tooltipText), findsOneWidget); expect(tester.getSize(find.text(tooltipText)), equals(const Size(168.0, 56.0))); tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(64.0)); }); testWidgets('Material3 - Tooltip text scales with textScaleFactor', (WidgetTester tester) async { Widget buildApp(String text, { required TextScaler textScaler }) { return MaterialApp( home: MediaQuery( data: MediaQueryData(textScaler: textScaler), child: Navigator( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( builder: (BuildContext context) { return Center( child: Tooltip( message: text, child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ); }, ); }, ), ), ); } await tester.pumpWidget(buildApp(tooltipText, textScaler: TextScaler.noScaling)); await tester.longPress(find.byType(Tooltip)); expect(find.text(tooltipText), findsOneWidget); expect(tester.getSize(find.text(tooltipText)).width, equals(42.75)); expect(tester.getSize(find.text(tooltipText)).height, equals(20.0)); RenderBox tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(32.0)); await tester.pumpWidget(buildApp(tooltipText, textScaler: const TextScaler.linear(4.0))); await tester.longPress(find.byType(Tooltip)); expect(find.text(tooltipText), findsOneWidget); expect(tester.getSize(find.text(tooltipText)).width, equals(168.75)); expect(tester.getSize(find.text(tooltipText)).height, equals(80.0)); tip = tester.renderObject( _findTooltipContainer(tooltipText), ); expect(tip.size.height, equals(88.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933 testWidgets('Tooltip text displays with richMessage', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); const String textSpan1Text = 'I am a rich tooltip message. '; const String textSpan2Text = 'I am another span of a rich tooltip message'; await tester.pumpWidget( MaterialApp( home: Tooltip( key: tooltipKey, richMessage: const TextSpan( text: textSpan1Text, children: <InlineSpan>[ TextSpan( text: textSpan2Text, ), ], ), child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) final RichText richText = tester.widget<RichText>(find.byType(RichText)); expect(richText.text.toPlainText(), equals('$textSpan1Text$textSpan2Text')); }); testWidgets('Tooltip throws assertion error when both message and richMessage are specified', (WidgetTester tester) async { expect( () { MaterialApp( home: Tooltip( message: 'I am a tooltip message.', richMessage: const TextSpan( text: 'I am a rich tooltip.', children: <InlineSpan>[ TextSpan( text: 'I am another span of a rich tooltip.', ), ], ), child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ); }, throwsA(const TypeMatcher<AssertionError>()), ); }); testWidgets('Haptic feedback', (WidgetTester tester) async { final FeedbackTester feedback = FeedbackTester(); await tester.pumpWidget( MaterialApp( home: Center( child: Tooltip( message: 'Foo', child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ), ), ); await tester.longPress(find.byType(Tooltip)); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(feedback.hapticCount, 1); feedback.dispose(); }); testWidgets('Semantics included', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: 'Foo', child: Text('Bar'), ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( tooltip: 'Foo', label: 'Bar', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreId: true, ignoreTransform: true)); semantics.dispose(); }); testWidgets('Semantics excluded', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: 'Foo', excludeFromSemantics: true, child: Text('Bar'), ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'Bar', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreId: true, ignoreTransform: true)); semantics.dispose(); }); testWidgets('has semantic events', (WidgetTester tester) async { final List<dynamic> semanticEvents = <dynamic>[]; tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, (dynamic message) async { semanticEvents.add(message); }); final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MaterialApp( home: Center( child: Tooltip( message: 'Foo', child: Container( width: 100.0, height: 100.0, color: Colors.green[500], ), ), ), ), ); await tester.longPress(find.byType(Tooltip)); final RenderObject object = tester.firstRenderObject(find.byType(Tooltip)); expect(semanticEvents, unorderedEquals(<dynamic>[ <String, dynamic>{ 'type': 'longPress', 'nodeId': _findDebugSemantics(object).id, 'data': <String, dynamic>{}, }, <String, dynamic>{ 'type': 'tooltip', 'data': <String, dynamic>{ 'message': 'Foo', }, }, ])); semantics.dispose(); tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null); }); testWidgets('default Tooltip debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const Tooltip(message: 'message').debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>[ '"message"', ]); }); testWidgets('default Tooltip debugFillProperties with richMessage', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const Tooltip( richMessage: TextSpan( text: 'This is a ', children: <InlineSpan>[ TextSpan( text: 'richMessage', ), ], ), ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>[ '"This is a richMessage"', ]); }); testWidgets('Tooltip implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); // Not checking controller, inputFormatters, focusNode const Tooltip( key: ValueKey<String>('foo'), message: 'message', decoration: BoxDecoration(), waitDuration: Duration(seconds: 1), showDuration: Duration(seconds: 2), padding: EdgeInsets.zero, margin: EdgeInsets.all(5.0), height: 100.0, excludeFromSemantics: true, preferBelow: false, verticalOffset: 50.0, triggerMode: TooltipTriggerMode.manual, enableFeedback: true, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>[ '"message"', 'height: 100.0', 'padding: EdgeInsets.zero', 'margin: EdgeInsets.all(5.0)', 'vertical offset: 50.0', 'position: above', 'semantics: excluded', 'wait duration: 0:00:01.000000', 'show duration: 0:00:02.000000', 'triggerMode: TooltipTriggerMode.manual', 'enableFeedback: true', ]); }); testWidgets('Tooltip triggers on tap when trigger mode is tap', (WidgetTester tester) async { await setWidgetForTooltipMode(tester, TooltipTriggerMode.tap); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); await _testGestureTap(tester, tooltip); expect(find.text(tooltipText), findsOneWidget); }); testWidgets('Tooltip triggers on long press when mode is long press', (WidgetTester tester) async { await setWidgetForTooltipMode(tester, TooltipTriggerMode.longPress); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); await _testGestureTap(tester, tooltip); expect(find.text(tooltipText), findsNothing); await _testGestureLongPress(tester, tooltip); expect(find.text(tooltipText), findsOneWidget); }); testWidgets('Tooltip does not trigger on tap when trigger mode is longPress', (WidgetTester tester) async { await setWidgetForTooltipMode(tester, TooltipTriggerMode.longPress); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); await _testGestureTap(tester, tooltip); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip does not trigger when trigger mode is manual', (WidgetTester tester) async { await setWidgetForTooltipMode(tester, TooltipTriggerMode.manual); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); await _testGestureTap(tester, tooltip); expect(find.text(tooltipText), findsNothing); await _testGestureLongPress(tester, tooltip); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip onTriggered is called when Tooltip triggers', (WidgetTester tester) async { bool onTriggeredCalled = false; void onTriggered() => onTriggeredCalled = true; await setWidgetForTooltipMode(tester, TooltipTriggerMode.longPress, onTriggered: onTriggered); Finder tooltip = find.byType(Tooltip); await _testGestureLongPress(tester, tooltip); expect(onTriggeredCalled, true); onTriggeredCalled = false; await setWidgetForTooltipMode(tester, TooltipTriggerMode.tap, onTriggered: onTriggered); tooltip = find.byType(Tooltip); await _testGestureTap(tester, tooltip); expect(onTriggeredCalled, true); }); testWidgets('Tooltip onTriggered is not called when Tooltip is hovered', (WidgetTester tester) async { bool onTriggeredCalled = false; void onTriggered() => onTriggeredCalled = true; const Duration waitDuration = Duration.zero; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, onTriggered: onTriggered, child: const SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(onTriggeredCalled, false); }); testWidgets('dismissAllToolTips dismisses hovered tooltips', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(find.text(tooltipText), findsOneWidget); await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsOneWidget); expect(Tooltip.dismissAllToolTips(), isTrue); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); }); testWidgets('Hovered tooltips do not dismiss after showDuration', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, triggerMode: TooltipTriggerMode.longPress, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(find.text(tooltipText), findsOneWidget); await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsOneWidget); await tester.longPressAt(tester.getCenter(tooltip)); await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); // Still visible. expect(find.text(tooltipText), findsOneWidget); // Still visible. await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); // The tooltip is no longer hovered and becomes invisible. await gesture.moveTo(Offset.zero); await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); }); testWidgets('Hovered tooltips with showDuration set do dismiss when hovering elsewhere', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; const Duration showDuration = Duration(seconds: 1); await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: waitDuration, showDuration: showDuration, triggerMode: TooltipTriggerMode.longPress, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await gesture.moveTo(tester.getCenter(find.byTooltip(tooltipText))); await tester.pump(const Duration(seconds: 1)); expect(find.text(tooltipText), findsOneWidget, reason: 'Tooltip should be visible when hovered.'); await gesture.moveTo(Offset.zero); // Set a duration equal to the default exit await tester.pump(const Duration(milliseconds: 100)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing, reason: 'Tooltip should not wait for showDuration before it hides itself.'); }); testWidgets('Hovered tooltips hide after stopping the hover', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.square( dimension: 10.0, child: Tooltip( message: tooltipText, triggerMode: TooltipTriggerMode.longPress, child: SizedBox.expand(), ), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await gesture.moveTo(tester.getCenter(find.byTooltip(tooltipText))); await tester.pump(const Duration(seconds: 1)); expect(find.text(tooltipText), findsOneWidget, reason: 'Tooltip should be visible when hovered.'); await gesture.moveTo(Offset.zero); await tester.pump(const Duration(milliseconds: 100)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing, reason: 'Tooltip should be hidden when no longer hovered.'); }); testWidgets('Hovered tooltips hide after stopping the hover and exitDuration expires', (WidgetTester tester) async { const Duration exitDuration = Duration(seconds: 1); await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.square( dimension: 10.0, child: Tooltip( message: tooltipText, exitDuration: exitDuration, triggerMode: TooltipTriggerMode.longPress, child: SizedBox.expand(), ), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await gesture.moveTo(tester.getCenter(find.byTooltip(tooltipText))); await tester.pump(const Duration(seconds: 1)); expect(find.text(tooltipText), findsOneWidget, reason: 'Tooltip should be visible when hovered.'); await gesture.moveTo(Offset.zero); await tester.pump(const Duration(milliseconds: 100)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsOneWidget, reason: 'Tooltip should wait until exitDuration expires before being hidden'); await tester.pump(const Duration(seconds: 1)); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing, reason: 'Tooltip should be hidden when no longer hovered.'); }); testWidgets('Tooltip should not be shown with empty message (with child)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Tooltip( message: tooltipText, child: Text(tooltipText), ), ), ); expect(find.text(tooltipText), findsOneWidget); }); testWidgets('Tooltip should not be shown with empty message (without child)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Tooltip( message: tooltipText, ), ), ); expect(find.text(tooltipText), findsNothing); if (tooltipText.isEmpty) { expect(find.byType(SizedBox), findsOneWidget); } }); testWidgets('Tooltip trigger mode ignores mouse events', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Tooltip( message: tooltipText, triggerMode: TooltipTriggerMode.longPress, child: SizedBox.expand(), ), ), ); final TestGesture mouseGesture = await tester.startGesture(tester.getCenter(find.byTooltip(tooltipText)), kind: PointerDeviceKind.mouse); await tester.pump(kLongPressTimeout + kPressTimeout); await mouseGesture.up(); await tester.pump(); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); final TestGesture touchGesture = await tester.startGesture(tester.getCenter(find.byTooltip(tooltipText))); await tester.pump(kLongPressTimeout + kPressTimeout); await touchGesture.up(); await tester.pump(); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsOneWidget); }); testWidgets('Tooltip does not block other mouse regions', (WidgetTester tester) async { bool entered = false; await tester.pumpWidget( MaterialApp( home: MouseRegion( onEnter: (PointerEnterEvent event) { entered = true; }, child: const Tooltip( message: tooltipText, child: SizedBox.expand(), ), ), ), ); expect(entered, isFalse); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(Tooltip))); await gesture.removePointer(); expect(entered, isTrue); }); testWidgets('Does not rebuild on mouse connect/disconnect', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/117627 int buildCount = 0; await tester.pumpWidget( MaterialApp( home: Tooltip( message: tooltipText, child: Builder(builder: (BuildContext context) { buildCount += 1; return const SizedBox.expand(); }), ), ), ); expect(buildCount, 1); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await tester.pump(); await gesture.removePointer(); await tester.pump(); expect(buildCount, 1); }); testWidgets('Tooltip should not ignore users tap on richMessage', (WidgetTester tester) async { bool isTapped = false; final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); await tester.pumpWidget( MaterialApp( home: Tooltip( richMessage: TextSpan( text: tooltipText, recognizer: recognizer..onTap = () { isTapped = true; } ), showDuration: const Duration(seconds: 5), triggerMode: TooltipTriggerMode.tap, child: const Icon(Icons.refresh) ), ), ); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); await _testGestureTap(tester, tooltip); final Finder textSpan = find.text(tooltipText); expect(textSpan, findsOneWidget); await _testGestureTap(tester, textSpan); expect(isTapped, isTrue); }); testWidgets('Hold mouse button down and hover over the Tooltip widget', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.square( dimension: 10.0, child: Tooltip( message: tooltipText, waitDuration: Duration(seconds: 1), triggerMode: TooltipTriggerMode.longPress, child: SizedBox.expand(), ), ), ), ), ); final TestGesture mouseGesture = await tester.startGesture(Offset.zero, kind: PointerDeviceKind.mouse); addTearDown(mouseGesture.removePointer); await mouseGesture.moveTo(tester.getCenter(find.byTooltip(tooltipText))); await tester.pump(const Duration(seconds: 1)); expect( find.text(tooltipText), findsOneWidget, reason: 'Tooltip should be visible when hovered.'); await mouseGesture.up(); await tester.pump(const Duration(days: 10)); await tester.pumpAndSettle(); expect( find.text(tooltipText), findsOneWidget, reason: 'Tooltip should be visible even when there is a PointerUp when hovered.', ); await mouseGesture.moveTo(Offset.zero); await tester.pump(const Duration(seconds: 1)); await tester.pumpAndSettle(); expect( find.text(tooltipText), findsNothing, reason: 'Tooltip should be dismissed with no hovering mouse cursor.' , ); }); testWidgets('Hovered text should dismiss when clicked outside', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.square( dimension: 10.0, child: Tooltip( message: tooltipText, waitDuration: Duration(seconds: 1), triggerMode: TooltipTriggerMode.longPress, child: SizedBox.expand(), ), ), ), ), ); // Avoid using startGesture here to avoid the PointDown event from also being // interpreted as a PointHover event by the Tooltip. final TestGesture mouseGesture1 = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(mouseGesture1.removePointer); await mouseGesture1.moveTo(tester.getCenter(find.byTooltip(tooltipText))); await tester.pump(const Duration(seconds: 1)); expect(find.text(tooltipText), findsOneWidget, reason: 'Tooltip should be visible when hovered.'); // Tapping on the Tooltip widget should dismiss the tooltip, since the // trigger mode is longPress. await tester.tap(find.byTooltip(tooltipText)); await tester.pump(); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing); await mouseGesture1.removePointer(); final TestGesture mouseGesture2 = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(mouseGesture2.removePointer); await mouseGesture2.moveTo(tester.getCenter(find.byTooltip(tooltipText))); await tester.pump(const Duration(seconds: 1)); expect(find.text(tooltipText), findsOneWidget, reason: 'Tooltip should be visible when hovered.'); await tester.tapAt(Offset.zero); await tester.pump(); await tester.pumpAndSettle(); expect(find.text(tooltipText), findsNothing, reason: 'Tapping outside of the Tooltip widget should dismiss the tooltip.'); }); testWidgets('Mouse tap and hover over the Tooltip widget', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/127575 . await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.square( dimension: 10.0, child: Tooltip( message: tooltipText, waitDuration: Duration(seconds: 1), triggerMode: TooltipTriggerMode.longPress, child: SizedBox.expand(), ), ), ), ), ); // The PointDown event is also interpreted as a PointHover event by the // Tooltip. This should be pretty rare but since it's more of a tap event // than a hover event, the tooltip shouldn't show unless the triggerMode // is set to tap. final TestGesture mouseGesture1 = await tester.startGesture( tester.getCenter(find.byTooltip(tooltipText)), kind: PointerDeviceKind.mouse, ); addTearDown(mouseGesture1.removePointer); await tester.pump(const Duration(seconds: 1)); expect( find.text(tooltipText), findsNothing, reason: 'Tooltip should NOT be visible when hovered and tapped, when trigger mode is not tap', ); await mouseGesture1.up(); await mouseGesture1.removePointer(); await tester.pump(const Duration(days: 10)); await tester.pumpAndSettle(); await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.square( dimension: 10.0, child: Tooltip( message: tooltipText, waitDuration: Duration(seconds: 1), triggerMode: TooltipTriggerMode.tap, child: SizedBox.expand(), ), ), ), ), ); final TestGesture mouseGesture2 = await tester.startGesture( tester.getCenter(find.byTooltip(tooltipText)), kind: PointerDeviceKind.mouse, ); addTearDown(mouseGesture2.removePointer); // The tap should be ignored, since Tooltip does not track "trigger gestures" // for mouse devices. await tester.pump(const Duration(milliseconds: 100)); await mouseGesture2.up(); await tester.pump(const Duration(seconds: 1)); expect( find.text(tooltipText), findsNothing, reason: 'Tooltip should NOT be visible when hovered and tapped, when trigger mode is tap', ); }); testWidgets('Tooltip does not rebuild for fade in / fade out animation', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Center( child: SizedBox.square( dimension: 10.0, child: Tooltip( message: tooltipText, waitDuration: Duration(seconds: 1), triggerMode: TooltipTriggerMode.longPress, child: SizedBox.expand(), ), ), ), ), ); final TooltipState tooltipState = tester.state(find.byType(Tooltip)); final Element element = tooltipState.context as Element; // The Tooltip widget itself is almost stateless thus doesn't need // rebuilding. expect(element.dirty, isFalse); expect(tooltipState.ensureTooltipVisible(), isTrue); expect(element.dirty, isFalse); await tester.pump(const Duration(seconds: 1)); expect(element.dirty, isFalse); expect(Tooltip.dismissAllToolTips(), isTrue); expect(element.dirty, isFalse); await tester.pump(const Duration(seconds: 1)); expect(element.dirty, isFalse); }); testWidgets('Tooltip does not initialize animation controller in dispose process', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Center( child: Tooltip( message: tooltipText, waitDuration: Duration(seconds: 1), triggerMode: TooltipTriggerMode.longPress, child: SizedBox.square(dimension: 50), ), ), ), ); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Tooltip))); await tester.pumpWidget(const SizedBox()); expect(tester.takeException(), isNull); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); testWidgets('Tooltip does not crash when showing the tooltip but the OverlayPortal is unmounted, during dispose', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: SelectionArea( child: Center( child: Tooltip( message: tooltipText, waitDuration: Duration(seconds: 1), triggerMode: TooltipTriggerMode.longPress, child: SizedBox.square(dimension: 50), ), ), ), ), ); final TooltipState tooltipState = tester.state(find.byType(Tooltip)); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Tooltip))); tooltipState.ensureTooltipVisible(); await tester.pumpWidget(const SizedBox()); expect(tester.takeException(), isNull); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); testWidgets('Tooltip is not selectable', (WidgetTester tester) async { const String tooltipText = 'AAAAAAAAAAAAAAAAAAAAAAA'; String? selectedText; await tester.pumpWidget( MaterialApp( home: SelectionArea( onSelectionChanged: (SelectedContent? content) { selectedText = content?.plainText; }, child: const Center( child: Column( children: <Widget>[ Text('Select Me'), Tooltip( message: tooltipText, waitDuration: Duration(seconds: 1), triggerMode: TooltipTriggerMode.longPress, child: SizedBox.square(dimension: 50), ), ], ), ), ), ), ); final TooltipState tooltipState = tester.state(find.byType(Tooltip)); final Rect textRect = tester.getRect(find.text('Select Me')); final TestGesture gesture = await tester.startGesture(Alignment.centerLeft.alongSize(textRect.size) + textRect.topLeft); // Drag from centerLeft to centerRight to select the text. await tester.pump(const Duration(seconds: 1)); await gesture.moveTo(Alignment.centerRight.alongSize(textRect.size) + textRect.topLeft); await tester.pump(); tooltipState.ensureTooltipVisible(); await tester.pump(); // Make sure the tooltip becomes visible. expect(find.text(tooltipText), findsOneWidget); assert(selectedText != null); final Rect tooltipTextRect = tester.getRect(find.text(tooltipText)); // Now drag from centerLeft to centerRight to select the tooltip text. await gesture.moveTo(Alignment.centerLeft.alongSize(tooltipTextRect.size) + tooltipTextRect.topLeft); await tester.pump(); await gesture.moveTo(Alignment.centerRight.alongSize(tooltipTextRect.size) + tooltipTextRect.topLeft); await tester.pump(); expect(selectedText, isNot(contains('A'))); }); } Future<void> setWidgetForTooltipMode( WidgetTester tester, TooltipTriggerMode triggerMode, { Duration? showDuration, bool? enableTapToDismiss, TooltipTriggeredCallback? onTriggered, }) async { await tester.pumpWidget( MaterialApp( home: Tooltip( message: tooltipText, triggerMode: triggerMode, onTriggered: onTriggered, showDuration: showDuration, enableTapToDismiss: enableTapToDismiss ?? true, child: const SizedBox(width: 100.0, height: 100.0), ), ), ); } Future<void> _testGestureLongPress(WidgetTester tester, Finder tooltip) async { final TestGesture gestureLongPress = await tester.startGesture(tester.getCenter(tooltip)); await tester.pump(); await tester.pump(kLongPressTimeout); await gestureLongPress.up(); await tester.pump(); } Future<void> _testGestureTap(WidgetTester tester, Finder tooltip) async { await tester.tap(tooltip); await tester.pump(const Duration(milliseconds: 10)); } SemanticsNode _findDebugSemantics(RenderObject object) { return object.debugSemantics ?? _findDebugSemantics(object.parent!); }
flutter/packages/flutter/test/material/tooltip_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/tooltip_test.dart", "repo_id": "flutter", "token_count": 48062 }
668
// 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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestCanvas implements Canvas { final List<Invocation> invocations = <Invocation>[]; @override void noSuchMethod(Invocation invocation) { invocations.add(invocation); } } void main() { test('Border.fromBorderSide constructor', () { const BorderSide side = BorderSide(); const Border border = Border.fromBorderSide(side); expect(border.left, same(side)); expect(border.top, same(side)); expect(border.right, same(side)); expect(border.bottom, same(side)); }); test('Border.symmetric constructor', () { const BorderSide side1 = BorderSide(color: Color(0xFFFFFFFF)); const BorderSide side2 = BorderSide(); const Border border = Border.symmetric(vertical: side1, horizontal: side2); expect(border.left, same(side1)); expect(border.top, same(side2)); expect(border.right, same(side1)); expect(border.bottom, same(side2)); }); test('Border.merge', () { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); expect( Border.merge( const Border(top: yellow2), const Border(right: magenta3), ), const Border(top: yellow2, right: magenta3), ); expect( Border.merge( const Border(bottom: magenta3), const Border(bottom: magenta3), ), const Border(bottom: magenta6), ); expect( Border.merge( const Border(left: magenta3, right: yellowNone0), const Border(right: yellow2), ), const Border(left: magenta3, right: yellow2), ); expect( Border.merge(const Border(), const Border()), const Border(), ); expect( () => Border.merge( const Border(left: magenta3), const Border(left: yellow2), ), throwsAssertionError, ); }); test('Border.add', () { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); expect( const Border(top: yellow2) + const Border(right: magenta3), const Border(top: yellow2, right: magenta3), ); expect( const Border(bottom: magenta3) + const Border(bottom: magenta3), const Border(bottom: magenta6), ); expect( const Border(left: magenta3, right: yellowNone0) + const Border(right: yellow2), const Border(left: magenta3, right: yellow2), ); expect( const Border() + const Border(), const Border(), ); expect( const Border(left: magenta3) + const Border(left: yellow2), isNot(isA<Border>()), // see shape_border_test.dart for better tests of this case ); const Border b3 = Border(top: magenta3); const Border b6 = Border(top: magenta6); expect(b3 + b3, b6); const Border b0 = Border(top: yellowNone0); const Border bZ = Border(); expect(b0 + b0, bZ); expect(bZ + bZ, bZ); expect(b0 + bZ, bZ); expect(bZ + b0, bZ); }); test('Border.scale', () { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); const Border b3 = Border(left: magenta3); const Border b6 = Border(left: magenta6); expect(b3.scale(2.0), b6); const Border bY0 = Border(top: yellowNone0); expect(bY0.scale(3.0), bY0); const Border bY2 = Border(top: yellow2); expect(bY2.scale(0.0), bY0); }); test('Border.dimensions', () { expect( const Border( left: BorderSide(width: 2.0), top: BorderSide(width: 3.0), bottom: BorderSide(width: 5.0), right: BorderSide(width: 7.0), ).dimensions, const EdgeInsets.fromLTRB(2.0, 3.0, 7.0, 5.0), ); }); test('Border.isUniform', () { expect( const Border( left: BorderSide(width: 3.0), top: BorderSide(width: 3.0), right: BorderSide(width: 3.0), bottom: BorderSide(width: 3.1), ).isUniform, false, ); expect( const Border( left: BorderSide(width: 3.0), top: BorderSide(width: 3.0), right: BorderSide(width: 3.0), bottom: BorderSide(width: 3.0), ).isUniform, true, ); expect( const Border( left: BorderSide(color: Color(0xFFFFFFFE)), top: BorderSide(color: Color(0xFFFFFFFF)), right: BorderSide(color: Color(0xFFFFFFFF)), bottom: BorderSide(color: Color(0xFFFFFFFF)), ).isUniform, false, ); expect( const Border( left: BorderSide(color: Color(0xFFFFFFFF)), top: BorderSide(color: Color(0xFFFFFFFF)), right: BorderSide(color: Color(0xFFFFFFFF)), bottom: BorderSide(color: Color(0xFFFFFFFF)), ).isUniform, true, ); expect( const Border( left: BorderSide(style: BorderStyle.none), top: BorderSide(style: BorderStyle.none), right: BorderSide(style: BorderStyle.none), bottom: BorderSide(width: 0.0), ).isUniform, false, ); expect( const Border( left: BorderSide(style: BorderStyle.none), top: BorderSide(style: BorderStyle.none), right: BorderSide(style: BorderStyle.none), bottom: BorderSide(width: 0.0), ).isUniform, false, ); expect( const Border( left: BorderSide(style: BorderStyle.none), top: BorderSide(style: BorderStyle.none), right: BorderSide(style: BorderStyle.none), ).isUniform, false, ); expect( const Border( left: BorderSide(), top: BorderSide(strokeAlign: BorderSide.strokeAlignCenter), right: BorderSide(strokeAlign: BorderSide.strokeAlignOutside), ).isUniform, false, ); expect( const Border().isUniform, true, ); expect( const Border().isUniform, true, ); }); test('Border.lerp', () { const Border visualWithTop10 = Border(top: BorderSide(width: 10.0)); const Border atMinus100 = Border(left: BorderSide(width: 0.0), right: BorderSide(width: 300.0)); const Border at0 = Border(left: BorderSide(width: 100.0), right: BorderSide(width: 200.0)); const Border at25 = Border(left: BorderSide(width: 125.0), right: BorderSide(width: 175.0)); const Border at75 = Border(left: BorderSide(width: 175.0), right: BorderSide(width: 125.0)); const Border at100 = Border(left: BorderSide(width: 200.0), right: BorderSide(width: 100.0)); const Border at200 = Border(left: BorderSide(width: 300.0), right: BorderSide(width: 0.0)); expect(Border.lerp(null, null, -1.0), null); expect(Border.lerp(visualWithTop10, null, -1.0), const Border(top: BorderSide(width: 20.0))); expect(Border.lerp(null, visualWithTop10, -1.0), const Border()); expect(Border.lerp(at0, at100, -1.0), atMinus100); expect(Border.lerp(null, null, 0.0), null); expect(Border.lerp(visualWithTop10, null, 0.0), const Border(top: BorderSide(width: 10.0))); expect(Border.lerp(null, visualWithTop10, 0.0), const Border()); expect(Border.lerp(at0, at100, 0.0), at0); expect(Border.lerp(null, null, 0.25), null); expect(Border.lerp(visualWithTop10, null, 0.25), const Border(top: BorderSide(width: 7.5))); expect(Border.lerp(null, visualWithTop10, 0.25), const Border(top: BorderSide(width: 2.5))); expect(Border.lerp(at0, at100, 0.25), at25); expect(Border.lerp(null, null, 0.75), null); expect(Border.lerp(visualWithTop10, null, 0.75), const Border(top: BorderSide(width: 2.5))); expect(Border.lerp(null, visualWithTop10, 0.75), const Border(top: BorderSide(width: 7.5))); expect(Border.lerp(at0, at100, 0.75), at75); expect(Border.lerp(null, null, 1.0), null); expect(Border.lerp(visualWithTop10, null, 1.0), const Border()); expect(Border.lerp(null, visualWithTop10, 1.0), const Border(top: BorderSide(width: 10.0))); expect(Border.lerp(at0, at100, 1.0), at100); expect(Border.lerp(null, null, 2.0), null); expect(Border.lerp(visualWithTop10, null, 2.0), const Border()); expect(Border.lerp(null, visualWithTop10, 2.0), const Border(top: BorderSide(width: 20.0))); expect(Border.lerp(at0, at100, 2.0), at200); }); test('Border - throws correct exception with strokeAlign', () { late FlutterError error; try { final TestCanvas canvas = TestCanvas(); // Border.all supports all StrokeAlign values. // Border() supports [BorderSide.strokeAlignInside] only. const Border( left: BorderSide(strokeAlign: BorderSide.strokeAlignCenter, color: Color(0xff000001)), right: BorderSide(strokeAlign: BorderSide.strokeAlignOutside, color: Color(0xff000002)), ).paint(canvas, const Rect.fromLTWH(10.0, 20.0, 30.0, 40.0)); } on FlutterError catch (e) { error = e; } expect(error, isNotNull); expect(error.diagnostics.length, 1); expect( error.diagnostics[0].toStringDeep(), 'A Border can only draw strokeAlign different than\nBorderSide.strokeAlignInside on borders with uniform colors.\n', ); }); test('Border.dimension', () { final Border insideBorder = Border.all(width: 10); expect(insideBorder.dimensions, const EdgeInsets.all(10)); final Border centerBorder = Border.all(width: 10, strokeAlign: BorderSide.strokeAlignCenter); expect(centerBorder.dimensions, const EdgeInsets.all(5)); final Border outsideBorder = Border.all(width: 10, strokeAlign: BorderSide.strokeAlignOutside); expect(outsideBorder.dimensions, EdgeInsets.zero); const BorderSide insideSide = BorderSide(width: 10); const BorderDirectional insideBorderDirectional = BorderDirectional(top: insideSide, bottom: insideSide, start: insideSide, end: insideSide); expect(insideBorderDirectional.dimensions, const EdgeInsetsDirectional.all(10)); const BorderSide centerSide = BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter); const BorderDirectional centerBorderDirectional = BorderDirectional(top: centerSide, bottom: centerSide, start: centerSide, end: centerSide); expect(centerBorderDirectional.dimensions, const EdgeInsetsDirectional.all(5)); const BorderSide outsideSide = BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside); const BorderDirectional outsideBorderDirectional = BorderDirectional(top: outsideSide, bottom: outsideSide, start: outsideSide, end: outsideSide); expect(outsideBorderDirectional.dimensions, EdgeInsetsDirectional.zero); const Border nonUniformBorder = Border( left: BorderSide(width: 5), top: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), right: BorderSide(width: 15, strokeAlign: BorderSide.strokeAlignOutside), bottom: BorderSide(width: 20), ); expect(nonUniformBorder.dimensions, const EdgeInsets.fromLTRB(5, 5, 0, 20)); const BorderDirectional nonUniformBorderDirectional = BorderDirectional( start: BorderSide(width: 5), top: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), end: BorderSide(width: 15, strokeAlign: BorderSide.strokeAlignOutside), bottom: BorderSide(width: 20), ); expect(nonUniformBorderDirectional.dimensions, const EdgeInsetsDirectional.fromSTEB(5, 5, 0, 20)); }); testWidgets('Non-Uniform Border variations', (WidgetTester tester) async { Widget buildWidget({ required BoxBorder border, BorderRadius? borderRadius, BoxShape boxShape = BoxShape.rectangle}) { return Directionality( textDirection: TextDirection.ltr, child: DecoratedBox( decoration: BoxDecoration( shape: boxShape, border: border, borderRadius: borderRadius, ), ), ); } // This is used to test every allowed non-uniform border combination. const Border allowedBorderVariations = Border( left: BorderSide(width: 5), top: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), right: BorderSide(width: 15, strokeAlign: BorderSide.strokeAlignOutside), bottom: BorderSide(width: 20), ); // This falls into non-uniform border because of strokeAlign. await tester.pumpWidget(buildWidget(border: allowedBorderVariations)); expect(tester.takeException(), isAssertionError, reason: 'Border with non-uniform strokeAlign should fail.'); await tester.pumpWidget(buildWidget( border: allowedBorderVariations, borderRadius: BorderRadius.circular(25), )); expect(tester.takeException(), isNull); await tester.pumpWidget(buildWidget(border: allowedBorderVariations, boxShape: BoxShape.circle)); expect(tester.takeException(), isNull); await tester.pumpWidget( buildWidget( border: const Border( left: BorderSide(width: 5, style: BorderStyle.none), top: BorderSide(width: 10), right: BorderSide(width: 15), bottom: BorderSide(width: 20), ), borderRadius: BorderRadius.circular(25), ), ); expect(tester.takeException(), isNull, reason: 'Border with non-uniform styles should work with borderRadius.'); await tester.pumpWidget( buildWidget( border: const Border( left: BorderSide(width: 5, color: Color(0xff123456)), top: BorderSide(width: 10), right: BorderSide(width: 15), bottom: BorderSide(width: 20), ), borderRadius: BorderRadius.circular(20), ), ); expect(tester.takeException(), isAssertionError, reason: 'Border with non-uniform colors should fail with borderRadius.'); await tester.pumpWidget( buildWidget( border: const Border(bottom: BorderSide(width: 0)), borderRadius: BorderRadius.zero, ), ); expect(tester.takeException(), isNull, reason: 'Border with a side.width == 0 should work without borderRadius (hairline border).'); await tester.pumpWidget( buildWidget( border: const Border(bottom: BorderSide(width: 0)), borderRadius: BorderRadius.circular(40), ), ); expect(tester.takeException(), isAssertionError, reason: 'Border with width == 0 and borderRadius should fail (hairline border).'); // Tests for BorderDirectional. const BorderDirectional allowedBorderDirectionalVariations = BorderDirectional( start: BorderSide(width: 5), top: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), end: BorderSide(width: 15, strokeAlign: BorderSide.strokeAlignOutside), bottom: BorderSide(width: 20), ); await tester.pumpWidget(buildWidget(border: allowedBorderDirectionalVariations)); expect(tester.takeException(), isAssertionError); await tester.pumpWidget(buildWidget( border: allowedBorderDirectionalVariations, borderRadius: BorderRadius.circular(25), )); expect(tester.takeException(), isNull, reason:'BorderDirectional should not fail with uniform styles and colors.'); await tester.pumpWidget(buildWidget(border: allowedBorderDirectionalVariations, boxShape: BoxShape.circle)); expect(tester.takeException(), isNull); }); test('Compound borders with differing preferPaintInteriors', () { expect(ShapeWithInterior().preferPaintInterior, isTrue); expect(ShapeWithoutInterior().preferPaintInterior, isFalse); expect((ShapeWithInterior() + ShapeWithInterior()).preferPaintInterior, isTrue); expect((ShapeWithInterior() + ShapeWithoutInterior()).preferPaintInterior, isFalse); expect((ShapeWithoutInterior() + ShapeWithInterior()).preferPaintInterior, isFalse); expect((ShapeWithoutInterior() + ShapeWithoutInterior()).preferPaintInterior, isFalse); }); } class ShapeWithInterior extends ShapeBorder { @override bool get preferPaintInterior => true; @override ShapeBorder scale(double t) { return this; } @override EdgeInsetsGeometry get dimensions => EdgeInsets.zero; @override Path getInnerPath(Rect rect, { TextDirection? textDirection }) { return Path(); } @override Path getOuterPath(Rect rect, { TextDirection? textDirection }) { return Path(); } @override void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { } @override void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { } } class ShapeWithoutInterior extends ShapeBorder { @override bool get preferPaintInterior => false; @override ShapeBorder scale(double t) { return this; } @override EdgeInsetsGeometry get dimensions => EdgeInsets.zero; @override Path getInnerPath(Rect rect, { TextDirection? textDirection }) { return Path(); } @override Path getOuterPath(Rect rect, { TextDirection? textDirection }) { return Path(); } @override void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { } @override void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { } }
flutter/packages/flutter/test/painting/border_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/border_test.dart", "repo_id": "flutter", "token_count": 6844 }
669
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'dart:math' as math; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('LinearGradient scale test', () { const LinearGradient testGradient = LinearGradient( begin: Alignment.bottomRight, end: Alignment(0.7, 1.0), colors: <Color>[ Color(0x00FFFFFF), Color(0x11777777), Color(0x44444444), ], ); final LinearGradient? actual = LinearGradient.lerp(null, testGradient, 0.25); expect(actual, const LinearGradient( begin: Alignment.bottomRight, end: Alignment(0.7, 1.0), colors: <Color>[ Color(0x00FFFFFF), Color(0x04777777), Color(0x11444444), ], )); }); test('LinearGradient lerp test', () { const LinearGradient testGradient1 = LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomLeft, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); const LinearGradient testGradient2 = LinearGradient( begin: Alignment.topRight, end: Alignment.topLeft, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], ); final LinearGradient? actual = LinearGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const LinearGradient( begin: Alignment.topCenter, end: Alignment.centerLeft, colors: <Color>[ Color(0x3B3B3B3B), Color(0x77777777), ], stops: <double>[0, 1], )); }); test('LinearGradient.lerp identical a,b', () { expect(LinearGradient.lerp(null, null, 0), null); const LinearGradient gradient = LinearGradient( colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); expect(identical(LinearGradient.lerp(gradient, gradient, 0.5), gradient), true); }); test('LinearGradient lerp test with stops', () { const LinearGradient testGradient1 = LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomLeft, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], stops: <double>[ 0.0, 0.5, ], ); const LinearGradient testGradient2 = LinearGradient( begin: Alignment.topRight, end: Alignment.topLeft, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], stops: <double>[ 0.5, 1.0, ], ); final LinearGradient? actual = LinearGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const LinearGradient( begin: Alignment.topCenter, end: Alignment.centerLeft, colors: <Color>[ Color(0x3B3B3B3B), Color(0x55555555), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 1.0, ], )); }); test('LinearGradient lerp test with unequal number of colors', () { const LinearGradient testGradient1 = LinearGradient( colors: <Color>[ Color(0x22222222), Color(0x66666666), ], ); const LinearGradient testGradient2 = LinearGradient( colors: <Color>[ Color(0x44444444), Color(0x66666666), Color(0x88888888), ], ); final LinearGradient? actual = LinearGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const LinearGradient( colors: <Color>[ Color(0x33333333), Color(0x55555555), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 1.0, ], )); }); test('LinearGradient lerp test with stops and unequal number of colors', () { const LinearGradient testGradient1 = LinearGradient( colors: <Color>[ Color(0x33333333), Color(0x66666666), ], stops: <double>[ 0.0, 0.5, ], ); const LinearGradient testGradient2 = LinearGradient( colors: <Color>[ Color(0x44444444), Color(0x48484848), Color(0x88888888), ], stops: <double>[ 0.5, 0.7, 1.0, ], ); final LinearGradient? actual = LinearGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const LinearGradient( colors: <Color>[ Color(0x3B3B3B3B), Color(0x55555555), Color(0x57575757), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 0.7, 1.0, ], )); }); test('LinearGradient toString', () { expect( const LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomLeft, transform: GradientRotation(1.6), colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ).toString(), equals( 'LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomLeft, colors: [Color(0x33333333), Color(0x66666666)], tileMode: TileMode.clamp, transform: GradientRotation(radians: 1.6))', ), ); }); test('LinearGradient with different transforms', () { const LinearGradient testGradient1 = LinearGradient( transform: GradientRotation(math.pi/4), colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); const LinearGradient testGradient1Copy = LinearGradient( transform: GradientRotation(math.pi/4), colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); const LinearGradient testGradient2 = LinearGradient( transform: GradientRotation(math.pi/2), colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); expect( testGradient1, equals(testGradient1Copy), ); expect( testGradient1, isNot(equals(testGradient2)), ); }); test('LinearGradient with AlignmentDirectional', () { expect( () { return const LinearGradient( begin: AlignmentDirectional.topStart, colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); }, throwsAssertionError, ); expect( () { return const LinearGradient( begin: AlignmentDirectional.topStart, colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.rtl); }, returnsNormally, ); expect( () { return const LinearGradient( begin: AlignmentDirectional.topStart, colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.ltr); }, returnsNormally, ); expect( () { return const LinearGradient( begin: Alignment.topLeft, colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); }, returnsNormally, ); }); test('RadialGradient with AlignmentDirectional', () { expect( () { return const RadialGradient( center: AlignmentDirectional.topStart, colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); }, throwsAssertionError, ); expect( () { return const RadialGradient( center: AlignmentDirectional.topStart, colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.rtl); }, returnsNormally, ); expect( () { return const RadialGradient( center: AlignmentDirectional.topStart, colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.ltr); }, returnsNormally, ); expect( () { return const RadialGradient( center: Alignment.topLeft, colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); }, returnsNormally, ); }); test('RadialGradient lerp test', () { const RadialGradient testGradient1 = RadialGradient( center: Alignment.topLeft, radius: 20.0, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); const RadialGradient testGradient2 = RadialGradient( center: Alignment.topRight, radius: 10.0, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const RadialGradient( center: Alignment.topCenter, radius: 15.0, colors: <Color>[ Color(0x3B3B3B3B), Color(0x77777777), ], stops: <double>[ 0.0, 1.0, ], )); }); test('RadialGradient.lerp identical a,b', () { expect(RadialGradient.lerp(null, null, 0), null); const RadialGradient gradient = RadialGradient( colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); expect(identical(RadialGradient.lerp(gradient, gradient, 0.5), gradient), true); }); test('RadialGradient lerp test with stops', () { const RadialGradient testGradient1 = RadialGradient( center: Alignment.topLeft, radius: 20.0, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], stops: <double>[ 0.0, 0.5, ], ); const RadialGradient testGradient2 = RadialGradient( center: Alignment.topRight, radius: 10.0, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], stops: <double>[ 0.5, 1.0, ], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const RadialGradient( center: Alignment.topCenter, radius: 15.0, colors: <Color>[ Color(0x3B3B3B3B), Color(0x55555555), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 1.0, ], )); expect(actual!.focal, isNull); }); test('RadialGradient lerp test with unequal number of colors', () { const RadialGradient testGradient1 = RadialGradient( colors: <Color>[ Color(0x22222222), Color(0x66666666), ], ); const RadialGradient testGradient2 = RadialGradient( colors: <Color>[ Color(0x44444444), Color(0x66666666), Color(0x88888888), ], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const RadialGradient( colors: <Color>[ Color(0x33333333), Color(0x55555555), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 1.0, ], )); }); test('RadialGradient lerp test with stops and unequal number of colors', () { const RadialGradient testGradient1 = RadialGradient( colors: <Color>[ Color(0x33333333), Color(0x66666666), ], stops: <double>[ 0.0, 0.5, ], ); const RadialGradient testGradient2 = RadialGradient( colors: <Color>[ Color(0x44444444), Color(0x48484848), Color(0x88888888), ], stops: <double>[ 0.5, 0.7, 1.0, ], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const RadialGradient( colors: <Color>[ Color(0x3B3B3B3B), Color(0x55555555), Color(0x57575757), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 0.7, 1.0, ], )); }); test('RadialGradient lerp test with focal', () { const RadialGradient testGradient1 = RadialGradient( center: Alignment.topLeft, focal: Alignment.centerLeft, radius: 20.0, focalRadius: 10.0, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); const RadialGradient testGradient2 = RadialGradient( center: Alignment.topRight, focal: Alignment.centerRight, radius: 10.0, focalRadius: 5.0, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], ); const RadialGradient testGradient3 = RadialGradient( center: Alignment.topRight, radius: 10.0, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const RadialGradient( center: Alignment.topCenter, focal: Alignment.center, radius: 15.0, focalRadius: 7.5, colors: <Color>[ Color(0x3B3B3B3B), Color(0x77777777), ], stops: <double>[ 0.0, 1.0, ], )); final RadialGradient? actual2 = RadialGradient.lerp(testGradient1, testGradient3, 0.5); expect(actual2, const RadialGradient( center: Alignment.topCenter, focal: Alignment(-0.5, 0.0), radius: 15.0, focalRadius: 5.0, colors: <Color>[ Color(0x3B3B3B3B), Color(0x77777777), ], stops: <double>[ 0.0, 1.0, ], )); }); test('SweepGradient lerp test', () { const SweepGradient testGradient1 = SweepGradient( center: Alignment.topLeft, endAngle: math.pi / 2, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); const SweepGradient testGradient2 = SweepGradient( center: Alignment.topRight, startAngle: math.pi / 2, endAngle: math.pi, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], ); final SweepGradient? actual = SweepGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const SweepGradient( center: Alignment.topCenter, startAngle: math.pi / 4, endAngle: math.pi * 3/4, colors: <Color>[ Color(0x3B3B3B3B), Color(0x77777777), ], stops: <double>[ 0.0, 1.0, ], )); }); test('SweepGradient.lerp identical a,b', () { expect(SweepGradient.lerp(null, null, 0), null); const SweepGradient gradient = SweepGradient( colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); expect(identical(SweepGradient.lerp(gradient, gradient, 0.5), gradient), true); }); test('SweepGradient lerp test with stops', () { const SweepGradient testGradient1 = SweepGradient( center: Alignment.topLeft, endAngle: math.pi / 2, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], stops: <double>[ 0.0, 0.5, ], ); const SweepGradient testGradient2 = SweepGradient( center: Alignment.topRight, startAngle: math.pi / 2, endAngle: math.pi, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], stops: <double>[ 0.5, 1.0, ], ); final SweepGradient? actual = SweepGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const SweepGradient( center: Alignment.topCenter, startAngle: math.pi / 4, endAngle: math.pi * 3/4, colors: <Color>[ Color(0x3B3B3B3B), Color(0x55555555), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 1.0, ], )); }); test('SweepGradient lerp test with unequal number of colors', () { const SweepGradient testGradient1 = SweepGradient( colors: <Color>[ Color(0x22222222), Color(0x66666666), ], ); const SweepGradient testGradient2 = SweepGradient( colors: <Color>[ Color(0x44444444), Color(0x66666666), Color(0x88888888), ], ); final SweepGradient? actual = SweepGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const SweepGradient( colors: <Color>[ Color(0x33333333), Color(0x55555555), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 1.0, ], )); }); test('SweepGradient lerp test with stops and unequal number of colors', () { const SweepGradient testGradient1 = SweepGradient( colors: <Color>[ Color(0x33333333), Color(0x66666666), ], stops: <double>[ 0.0, 0.5, ], ); const SweepGradient testGradient2 = SweepGradient( colors: <Color>[ Color(0x44444444), Color(0x48484848), Color(0x88888888), ], stops: <double>[ 0.5, 0.7, 1.0, ], ); final SweepGradient? actual = SweepGradient.lerp(testGradient1, testGradient2, 0.5); expect(actual, const SweepGradient( colors: <Color>[ Color(0x3B3B3B3B), Color(0x55555555), Color(0x57575757), Color(0x77777777), ], stops: <double>[ 0.0, 0.5, 0.7, 1.0, ], )); }); test('SweepGradient scale test)', () { const SweepGradient testGradient = SweepGradient( center: Alignment.topLeft, endAngle: math.pi / 2, colors: <Color>[ Color(0xff333333), Color(0xff666666), ], ); final SweepGradient actual = testGradient.scale(0.5); expect(actual, const SweepGradient( center: Alignment.topLeft, endAngle: math.pi / 2, colors: <Color>[ Color(0x80333333), Color(0x80666666), ], )); }); test('Gradient lerp test (with RadialGradient)', () { const RadialGradient testGradient1 = RadialGradient( center: Alignment.topLeft, radius: 20.0, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], stops: <double>[ 0.0, 1.0, ], ); const RadialGradient testGradient2 = RadialGradient( center: Alignment.topCenter, radius: 15.0, colors: <Color>[ Color(0x3B3B3B3B), Color(0x77777777), ], stops: <double>[ 0.0, 1.0, ], ); const RadialGradient testGradient3 = RadialGradient( center: Alignment.topRight, radius: 10.0, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], stops: <double>[ 0.0, 1.0, ], ); expect(Gradient.lerp(testGradient1, testGradient3, 0.0), testGradient1); expect(Gradient.lerp(testGradient1, testGradient3, 0.5), testGradient2); expect(Gradient.lerp(testGradient1, testGradient3, 1.0), testGradient3); expect(Gradient.lerp(testGradient3, testGradient1, 0.0), testGradient3); expect(Gradient.lerp(testGradient3, testGradient1, 0.5), testGradient2); expect(Gradient.lerp(testGradient3, testGradient1, 1.0), testGradient1); }); test('Gradient lerp test (LinearGradient to RadialGradient)', () { const LinearGradient testGradient1 = LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: <Color>[ Color(0x33333333), Color(0x66666666), ], ); const RadialGradient testGradient2 = RadialGradient( radius: 20.0, colors: <Color>[ Color(0x44444444), Color(0x88888888), ], ); expect(Gradient.lerp(testGradient1, testGradient2, 0.0), testGradient1); expect(Gradient.lerp(testGradient1, testGradient2, 1.0), testGradient2); expect(Gradient.lerp(testGradient1, testGradient2, 0.5), testGradient2.scale(0.0)); }); test('Gradients can handle missing stops and report mismatched stops', () { const LinearGradient test1a = LinearGradient( colors: <Color>[ Color(0x11111111), Color(0x22222222), Color(0x33333333), ], ); const RadialGradient test1b = RadialGradient( colors: <Color>[ Color(0x11111111), Color(0x22222222), Color(0x33333333), ], ); const LinearGradient test2a = LinearGradient( colors: <Color>[ Color(0x11111111), Color(0x22222222), Color(0x33333333), ], stops: <double>[0.0, 1.0], ); const RadialGradient test2b = RadialGradient( colors: <Color>[ Color(0x11111111), Color(0x22222222), Color(0x33333333), ], stops: <double>[0.0, 1.0], ); const Rect rect = Rect.fromLTWH(1.0, 2.0, 3.0, 4.0); expect(test1a.createShader(rect), isNotNull); expect(test1b.createShader(rect), isNotNull); expect(() { test2a.createShader(rect); }, throwsArgumentError); expect(() { test2b.createShader(rect); }, throwsArgumentError); }); group('Transforms', () { const List<Color> colors = <Color>[Color(0xFFFFFFFF), Color(0xFF000088)]; const Rect rect = Rect.fromLTWH(0.0, 0.0, 300.0, 400.0); const List<Gradient> gradients45 = <Gradient>[ LinearGradient(colors: colors, transform: GradientRotation(math.pi/4)), // A radial gradient won't be interesting to rotate unless the center is changed. RadialGradient(colors: colors, center: Alignment.topCenter, transform: GradientRotation(math.pi/4)), SweepGradient(colors: colors, transform: GradientRotation(math.pi/4)), ]; const List<Gradient> gradients90 = <Gradient>[ LinearGradient(colors: colors, transform: GradientRotation(math.pi/2)), // A radial gradient won't be interesting to rotate unless the center is changed. RadialGradient(colors: colors, center: Alignment.topCenter, transform: GradientRotation(math.pi/2)), SweepGradient(colors: colors, transform: GradientRotation(math.pi/2)), ]; const Map<Type, String> gradientSnakeCase = <Type, String> { LinearGradient: 'linear_gradient', RadialGradient: 'radial_gradient', SweepGradient: 'sweep_gradient', }; Future<void> runTest(WidgetTester tester, Gradient gradient, double degrees) async { final String goldenName = '${gradientSnakeCase[gradient.runtimeType]}_$degrees.png'; final Shader shader = gradient.createShader( rect, ); final Key painterKey = UniqueKey(); await tester.pumpWidget(Center( child: SizedBox.fromSize( size: rect.size, child: RepaintBoundary( key: painterKey, child: CustomPaint( painter: GradientPainter(shader, rect), ), ), ), )); await expectLater( find.byKey(painterKey), matchesGoldenFile(goldenName), ); } group('Gradients - 45 degrees', () { for (final Gradient gradient in gradients45) { testWidgets('$gradient', (WidgetTester tester) async { await runTest(tester, gradient, 45); }); } }); group('Gradients - 90 degrees', () { for (final Gradient gradient in gradients90) { testWidgets('$gradient', (WidgetTester tester) async { await runTest(tester, gradient, 90); }); } }); }); } class GradientPainter extends CustomPainter { const GradientPainter(this.shader, this.rect); final Shader shader; final Rect rect; @override void paint(Canvas canvas, Size size) { canvas.drawRect(rect, Paint()..shader = shader); } @override bool shouldRepaint(CustomPainter oldDelegate) => true; }
flutter/packages/flutter/test/painting/gradient_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/gradient_test.dart", "repo_id": "flutter", "token_count": 11465 }
670
// 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 'dart:async'; import 'dart:ui' as ui show Image; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; class TestImageInfo extends ImageInfo { TestImageInfo(this.value, { required super.image, super.scale, super.debugLabel, }); final int value; @override String toString() => '${objectRuntimeType(this, 'TestImageInfo')}($value)'; @override TestImageInfo clone() { return TestImageInfo(value, image: image.clone(), scale: scale, debugLabel: debugLabel); } @override int get hashCode => Object.hash(value, image, scale, debugLabel); @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is TestImageInfo && other.value == value && other.image.isCloneOf(image) && other.scale == scale && other.debugLabel == debugLabel; } } class TestImageProvider extends ImageProvider<int> { const TestImageProvider(this.key, this.imageValue, { required this.image }); final int key; final int imageValue; final ui.Image image; @override Future<int> obtainKey(ImageConfiguration configuration) { return Future<int>.value(key); } @override ImageStreamCompleter loadImage(int key, ImageDecoderCallback decode) { return OneFrameImageStreamCompleter( SynchronousFuture<ImageInfo>(TestImageInfo(imageValue, image: image.clone())), ); } @override String toString() => '${objectRuntimeType(this, 'TestImageProvider')}($key, $imageValue)'; } class FailingTestImageProvider extends TestImageProvider { const FailingTestImageProvider(super.key, super.imageValue, { required super.image }); @override ImageStreamCompleter loadImage(int key, ImageDecoderCallback decode) { return OneFrameImageStreamCompleter(Future<ImageInfo>.sync(() => Future<ImageInfo>.error('loading failed!'))); } } Future<ImageInfo> extractOneFrame(ImageStream stream) { final Completer<ImageInfo> completer = Completer<ImageInfo>(); late ImageStreamListener listener; listener = ImageStreamListener((ImageInfo image, bool synchronousCall) { completer.complete(image); stream.removeListener(listener); }); stream.addListener(listener); return completer.future; } class ErrorImageProvider extends ImageProvider<ErrorImageProvider> { @override ImageStreamCompleter loadImage(ErrorImageProvider key, ImageDecoderCallback decode) { throw Error(); } @override ImageStreamCompleter loadBuffer(ErrorImageProvider key, DecoderBufferCallback decode) { throw Error(); } @override Future<ErrorImageProvider> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<ErrorImageProvider>(this); } } class ObtainKeyErrorImageProvider extends ImageProvider<ObtainKeyErrorImageProvider> { @override ImageStreamCompleter loadImage(ObtainKeyErrorImageProvider key, ImageDecoderCallback decode) { throw Error(); } @override ImageStreamCompleter loadBuffer(ObtainKeyErrorImageProvider key, DecoderBufferCallback decode) { throw UnimplementedError(); } @override Future<ObtainKeyErrorImageProvider> obtainKey(ImageConfiguration configuration) { throw Error(); } } class LoadErrorImageProvider extends ImageProvider<LoadErrorImageProvider> { @override ImageStreamCompleter loadImage(LoadErrorImageProvider key, ImageDecoderCallback decode) { throw Error(); } @override ImageStreamCompleter loadBuffer(LoadErrorImageProvider key, DecoderBufferCallback decode) { throw UnimplementedError(); } @override Future<LoadErrorImageProvider> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<LoadErrorImageProvider>(this); } } class LoadErrorCompleterImageProvider extends ImageProvider<LoadErrorCompleterImageProvider> { @override ImageStreamCompleter loadImage(LoadErrorCompleterImageProvider key, ImageDecoderCallback decode) { final Completer<ImageInfo> completer = Completer<ImageInfo>.sync(); completer.completeError(Error()); return OneFrameImageStreamCompleter(completer.future); } @override Future<LoadErrorCompleterImageProvider> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<LoadErrorCompleterImageProvider>(this); } } class TestImageStreamCompleter extends ImageStreamCompleter { void testSetImage(ui.Image image) { setImage(ImageInfo(image: image)); } }
flutter/packages/flutter/test/painting/mocks_for_image_cache.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/mocks_for_image_cache.dart", "repo_id": "flutter", "token_count": 1403 }
671
// 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/painting.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('Linear TextScaler', () { test('equality', () { const TextScaler a = TextScaler.linear(3.0); final TextScaler b = TextScaler.noScaling.clamp(minScaleFactor: 3.0); // Creates a non-const TextScaler instance. final TextScaler c = TextScaler.linear(3.0); // ignore: prefer_const_constructors final TextScaler d = TextScaler.noScaling .clamp(minScaleFactor: 1, maxScaleFactor: 5) .clamp(minScaleFactor: 3, maxScaleFactor: 6); final List<TextScaler> list = <TextScaler>[a, b, c, d]; for (final TextScaler lhs in list) { expect(list, everyElement(lhs)); } }); test('clamping', () { expect(TextScaler.noScaling.clamp(minScaleFactor: 3.0), const TextScaler.linear(3.0)); expect(const TextScaler.linear(5.0).clamp(maxScaleFactor: 3.0), const TextScaler.linear(3.0)); expect(const TextScaler.linear(5.0).clamp(maxScaleFactor: 3.0), const TextScaler.linear(3.0)); expect(const TextScaler.linear(5.0).clamp(minScaleFactor: 3.0, maxScaleFactor: 3.0), const TextScaler.linear(3.0)); // Asserts when min > max. expect( () => TextScaler.noScaling.clamp(minScaleFactor: 5.0, maxScaleFactor: 4.0), throwsA(isA<AssertionError>().having((AssertionError error) => error.toString(), 'message', contains('maxScaleFactor >= minScaleFactor'))), ); }); }); }
flutter/packages/flutter/test/painting/text_scaler_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/text_scaler_test.dart", "repo_id": "flutter", "token_count": 653 }
672
// 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/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); test('handleMetricsChanged does not scheduleForcedFrame unless there a registered renderView with a child', () async { expect(SchedulerBinding.instance.hasScheduledFrame, false); RendererBinding.instance.handleMetricsChanged(); expect(SchedulerBinding.instance.hasScheduledFrame, false); RendererBinding.instance.addRenderView(RendererBinding.instance.renderView); RendererBinding.instance.handleMetricsChanged(); expect(SchedulerBinding.instance.hasScheduledFrame, false); RendererBinding.instance.renderView.child = RenderLimitedBox(); RendererBinding.instance.handleMetricsChanged(); expect(SchedulerBinding.instance.hasScheduledFrame, true); RendererBinding.instance.removeRenderView(RendererBinding.instance.renderView); }); test('debugDumpSemantics prints explanation when semantics are unavailable', () { RendererBinding.instance.addRenderView(RendererBinding.instance.renderView); final List<String?> log = <String?>[]; debugPrint = (String? message, {int? wrapWidth}) { log.add(message); }; debugDumpSemanticsTree(); expect(log, hasLength(1)); expect(log.single, startsWith('Semantics not generated')); expect(log.single, endsWith( 'For performance reasons, the framework only generates semantics when asked to do so by the platform.\n' 'Usually, platforms only ask for semantics when assistive technologies (like screen readers) are running.\n' 'To generate semantics, try turning on an assistive technology (like VoiceOver or TalkBack) on your device.' )); RendererBinding.instance.removeRenderView(RendererBinding.instance.renderView); }); test('root pipeline owner cannot manage root node', () { final RenderObject rootNode = RenderProxyBox(); expect( () => RendererBinding.instance.rootPipelineOwner.rootNode = rootNode, throwsA(isFlutterError.having( (FlutterError e) => e.message, 'message', contains('Cannot set a rootNode on the default root pipeline owner.'), )), ); }); }
flutter/packages/flutter/test/rendering/binding_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/binding_test.dart", "repo_id": "flutter", "token_count": 783 }
673
// 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; class TestLayout { TestLayout() { // incoming constraints are tight 800x600 root = RenderPositionedBox( child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(width: 800.0), child: RenderCustomPaint( painter: TestCallbackPainter( onPaint: () { painted = true; }, ), child: child = RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(height: 10.0, width: 10.0), ), ), ), ); } late RenderBox root; late RenderBox child; bool painted = false; } void main() { TestRenderingFlutterBinding.ensureInitialized(); final ViewConfiguration testConfiguration = ViewConfiguration( logicalConstraints: BoxConstraints.tight(const Size(800.0, 600.0)), ); test('onscreen layout does not affect offscreen', () { final TestLayout onscreen = TestLayout(); final TestLayout offscreen = TestLayout(); expect(onscreen.child.hasSize, isFalse); expect(onscreen.painted, isFalse); expect(offscreen.child.hasSize, isFalse); expect(offscreen.painted, isFalse); // Attach the offscreen to a custom render view and owner final RenderView renderView = RenderView(configuration: testConfiguration, view: RendererBinding.instance.platformDispatcher.views.single); final PipelineOwner pipelineOwner = PipelineOwner(); renderView.attach(pipelineOwner); renderView.child = offscreen.root; renderView.prepareInitialFrame(); pipelineOwner.requestVisualUpdate(); // Lay out the onscreen in the default binding layout(onscreen.root, phase: EnginePhase.paint); expect(onscreen.child.hasSize, isTrue); expect(onscreen.painted, isTrue); expect(onscreen.child.size, equals(const Size(800.0, 10.0))); // Make sure the offscreen didn't get laid out expect(offscreen.child.hasSize, isFalse); expect(offscreen.painted, isFalse); // Now lay out the offscreen pipelineOwner.flushLayout(); expect(offscreen.child.hasSize, isTrue); expect(offscreen.painted, isFalse); pipelineOwner.flushCompositingBits(); pipelineOwner.flushPaint(); expect(offscreen.painted, isTrue); }); test('offscreen layout does not affect onscreen', () { final TestLayout onscreen = TestLayout(); final TestLayout offscreen = TestLayout(); expect(onscreen.child.hasSize, isFalse); expect(onscreen.painted, isFalse); expect(offscreen.child.hasSize, isFalse); expect(offscreen.painted, isFalse); // Attach the offscreen to a custom render view and owner final RenderView renderView = RenderView(configuration: testConfiguration, view: RendererBinding.instance.platformDispatcher.views.single); final PipelineOwner pipelineOwner = PipelineOwner(); renderView.attach(pipelineOwner); renderView.child = offscreen.root; renderView.prepareInitialFrame(); pipelineOwner.requestVisualUpdate(); // Lay out the offscreen pipelineOwner.flushLayout(); expect(offscreen.child.hasSize, isTrue); expect(offscreen.painted, isFalse); pipelineOwner.flushCompositingBits(); pipelineOwner.flushPaint(); expect(offscreen.painted, isTrue); // Make sure the onscreen didn't get laid out expect(onscreen.child.hasSize, isFalse); expect(onscreen.painted, isFalse); // Now lay out the onscreen in the default binding layout(onscreen.root, phase: EnginePhase.paint); expect(onscreen.child.hasSize, isTrue); expect(onscreen.painted, isTrue); expect(onscreen.child.size, equals(const Size(800.0, 10.0))); }); }
flutter/packages/flutter/test/rendering/independent_layout_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/independent_layout_test.dart", "repo_id": "flutter", "token_count": 1314 }
674
// 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test('overflow should not affect baseline', () { RenderBox root, child, text; late double baseline1, baseline2, height1, height2; root = RenderPositionedBox( child: RenderCustomPaint( child: child = text = RenderParagraph( const TextSpan(text: 'Hello World'), textDirection: TextDirection.ltr, ), painter: TestCallbackPainter( onPaint: () { baseline1 = child.getDistanceToBaseline(TextBaseline.alphabetic)!; height1 = text.size.height; }, ), ), ); layout(root, phase: EnginePhase.paint); root = RenderPositionedBox( child: RenderCustomPaint( child: child = RenderConstrainedOverflowBox( child: text = RenderParagraph( const TextSpan(text: 'Hello World'), textDirection: TextDirection.ltr, ), maxHeight: height1 / 2.0, alignment: Alignment.topLeft, ), painter: TestCallbackPainter( onPaint: () { baseline2 = child.getDistanceToBaseline(TextBaseline.alphabetic)!; height2 = text.size.height; }, ), ), ); layout(root, phase: EnginePhase.paint); expect(baseline1, lessThan(height1)); expect(height2, equals(height1 / 2.0)); expect(baseline2, equals(baseline1)); expect(baseline2, greaterThan(height2)); }); }
flutter/packages/flutter/test/rendering/overflow_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/overflow_test.dart", "repo_id": "flutter", "token_count": 745 }
675
// 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test('nested repaint boundaries - smoke test', () { RenderOpacity a, b, c; a = RenderOpacity( child: RenderRepaintBoundary( child: b = RenderOpacity( child: RenderRepaintBoundary( child: c = RenderOpacity(), ), ), ), ); layout(a, phase: EnginePhase.flushSemantics); c.opacity = 0.9; pumpFrame(phase: EnginePhase.flushSemantics); a.opacity = 0.8; c.opacity = 0.8; pumpFrame(phase: EnginePhase.flushSemantics); a.opacity = 0.7; b.opacity = 0.7; c.opacity = 0.7; pumpFrame(phase: EnginePhase.flushSemantics); }); test('Repaint boundary can get new parent after markNeedsCompositingBitsUpdate', () { // Regression test for https://github.com/flutter/flutter/issues/24029. final RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary(); layout(repaintBoundary, phase: EnginePhase.flushSemantics); repaintBoundary.markNeedsCompositingBitsUpdate(); TestRenderingFlutterBinding.instance.renderView.child = null; final RenderPadding padding = RenderPadding( padding: const EdgeInsets.all(50), ); TestRenderingFlutterBinding.instance.renderView.child = padding; padding.child = repaintBoundary; pumpFrame(phase: EnginePhase.flushSemantics); }); test('Framework creates an OffsetLayer for a repaint boundary', () { final _TestRepaintBoundary repaintBoundary = _TestRepaintBoundary(); final RenderOpacity opacity = RenderOpacity( child: repaintBoundary, ); layout(opacity, phase: EnginePhase.flushSemantics); expect(repaintBoundary.debugLayer, isA<OffsetLayer>()); }); test('Framework does not create an OffsetLayer for a non-repaint boundary', () { final _TestNonCompositedBox nonCompositedBox = _TestNonCompositedBox(); final RenderOpacity opacity = RenderOpacity( child: nonCompositedBox, ); layout(opacity, phase: EnginePhase.flushSemantics); expect(nonCompositedBox.debugLayer, null); }); test('Framework allows a non-repaint boundary to create own layer', () { final _TestCompositedBox compositedBox = _TestCompositedBox(); final RenderOpacity opacity = RenderOpacity( child: compositedBox, ); layout(opacity, phase: EnginePhase.flushSemantics); expect(compositedBox.debugLayer, isA<OpacityLayer>()); }); test('Framework ensures repaint boundary layer is not overwritten', () { final _TestRepaintBoundaryThatOverwritesItsLayer faultyRenderObject = _TestRepaintBoundaryThatOverwritesItsLayer(); final RenderOpacity opacity = RenderOpacity( child: faultyRenderObject, ); late FlutterErrorDetails error; layout(opacity, phase: EnginePhase.flushSemantics, onErrors: () { error = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails()!; }); expect('${error.exception}', contains('Attempted to set a layer to a repaint boundary render object.')); }); } // A plain render object that's a repaint boundary. class _TestRepaintBoundary extends RenderBox { @override bool get isRepaintBoundary => true; @override void performLayout() { size = constraints.smallest; } } // A render object that's a repaint boundary and (incorrectly) creates its own layer. class _TestRepaintBoundaryThatOverwritesItsLayer extends RenderBox { @override bool get isRepaintBoundary => true; @override void performLayout() { size = constraints.smallest; } @override void paint(PaintingContext context, Offset offset) { layer = OpacityLayer(alpha: 50); } } // A render object that's neither a repaint boundary nor creates its own layer. class _TestNonCompositedBox extends RenderBox { @override bool get isRepaintBoundary => false; @override void performLayout() { size = constraints.smallest; } } // A render object that's not a repaint boundary but creates its own layer. class _TestCompositedBox extends RenderBox { @override bool get isRepaintBoundary => false; @override void performLayout() { size = constraints.smallest; } @override void paint(PaintingContext context, Offset offset) { layer = OpacityLayer(alpha: 50); } }
flutter/packages/flutter/test/rendering/repaint_boundary_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/repaint_boundary_test.dart", "repo_id": "flutter", "token_count": 1535 }
676
// 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 'dart:math' as math; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; Offset round(Offset value) { return Offset(value.dx.roundToDouble(), value.dy.roundToDouble()); } void main() { TestRenderingFlutterBinding.ensureInitialized(); test('RenderTransform - identity', () { RenderBox inner; final RenderBox sizer = RenderTransform( transform: Matrix4.identity(), alignment: Alignment.center, child: inner = RenderSizedBox(const Size(100.0, 100.0)), ); layout(sizer, constraints: BoxConstraints.tight(const Size(100.0, 100.0)), alignment: Alignment.topLeft); expect(inner.globalToLocal(Offset.zero), equals(Offset.zero)); expect(inner.globalToLocal(const Offset(100.0, 100.0)), equals(const Offset(100.0, 100.0))); expect(inner.globalToLocal(const Offset(25.0, 75.0)), equals(const Offset(25.0, 75.0))); expect(inner.globalToLocal(const Offset(50.0, 50.0)), equals(const Offset(50.0, 50.0))); expect(inner.localToGlobal(Offset.zero), equals(Offset.zero)); expect(inner.localToGlobal(const Offset(100.0, 100.0)), equals(const Offset(100.0, 100.0))); expect(inner.localToGlobal(const Offset(25.0, 75.0)), equals(const Offset(25.0, 75.0))); expect(inner.localToGlobal(const Offset(50.0, 50.0)), equals(const Offset(50.0, 50.0))); }); test('RenderTransform - identity with internal offset', () { RenderBox inner; final RenderBox sizer = RenderTransform( transform: Matrix4.identity(), alignment: Alignment.center, child: RenderPadding( padding: const EdgeInsets.only(left: 20.0), child: inner = RenderSizedBox(const Size(80.0, 100.0)), ), ); layout(sizer, constraints: BoxConstraints.tight(const Size(100.0, 100.0)), alignment: Alignment.topLeft); expect(inner.globalToLocal(Offset.zero), equals(const Offset(-20.0, 0.0))); expect(inner.globalToLocal(const Offset(100.0, 100.0)), equals(const Offset(80.0, 100.0))); expect(inner.globalToLocal(const Offset(25.0, 75.0)), equals(const Offset(5.0, 75.0))); expect(inner.globalToLocal(const Offset(50.0, 50.0)), equals(const Offset(30.0, 50.0))); expect(inner.localToGlobal(Offset.zero), equals(const Offset(20.0, 0.0))); expect(inner.localToGlobal(const Offset(100.0, 100.0)), equals(const Offset(120.0, 100.0))); expect(inner.localToGlobal(const Offset(25.0, 75.0)), equals(const Offset(45.0, 75.0))); expect(inner.localToGlobal(const Offset(50.0, 50.0)), equals(const Offset(70.0, 50.0))); }); test('RenderTransform - translation', () { RenderBox inner; final RenderBox sizer = RenderTransform( transform: Matrix4.translationValues(50.0, 200.0, 0.0), alignment: Alignment.center, child: inner = RenderSizedBox(const Size(100.0, 100.0)), ); layout(sizer, constraints: BoxConstraints.tight(const Size(100.0, 100.0)), alignment: Alignment.topLeft); expect(inner.globalToLocal(Offset.zero), equals(const Offset(-50.0, -200.0))); expect(inner.globalToLocal(const Offset(100.0, 100.0)), equals(const Offset(50.0, -100.0))); expect(inner.globalToLocal(const Offset(25.0, 75.0)), equals(const Offset(-25.0, -125.0))); expect(inner.globalToLocal(const Offset(50.0, 50.0)), equals(const Offset(0.0, -150.0))); expect(inner.localToGlobal(Offset.zero), equals(const Offset(50.0, 200.0))); expect(inner.localToGlobal(const Offset(100.0, 100.0)), equals(const Offset(150.0, 300.0))); expect(inner.localToGlobal(const Offset(25.0, 75.0)), equals(const Offset(75.0, 275.0))); expect(inner.localToGlobal(const Offset(50.0, 50.0)), equals(const Offset(100.0, 250.0))); }); test('RenderTransform - translation with internal offset', () { RenderBox inner; final RenderBox sizer = RenderTransform( transform: Matrix4.translationValues(50.0, 200.0, 0.0), alignment: Alignment.center, child: RenderPadding( padding: const EdgeInsets.only(left: 20.0), child: inner = RenderSizedBox(const Size(80.0, 100.0)), ), ); layout(sizer, constraints: BoxConstraints.tight(const Size(100.0, 100.0)), alignment: Alignment.topLeft); expect(inner.globalToLocal(Offset.zero), equals(const Offset(-70.0, -200.0))); expect(inner.globalToLocal(const Offset(100.0, 100.0)), equals(const Offset(30.0, -100.0))); expect(inner.globalToLocal(const Offset(25.0, 75.0)), equals(const Offset(-45.0, -125.0))); expect(inner.globalToLocal(const Offset(50.0, 50.0)), equals(const Offset(-20.0, -150.0))); expect(inner.localToGlobal(Offset.zero), equals(const Offset(70.0, 200.0))); expect(inner.localToGlobal(const Offset(100.0, 100.0)), equals(const Offset(170.0, 300.0))); expect(inner.localToGlobal(const Offset(25.0, 75.0)), equals(const Offset(95.0, 275.0))); expect(inner.localToGlobal(const Offset(50.0, 50.0)), equals(const Offset(120.0, 250.0))); }); test('RenderTransform - rotation', () { RenderBox inner; final RenderBox sizer = RenderTransform( transform: Matrix4.rotationZ(math.pi), alignment: Alignment.center, child: inner = RenderSizedBox(const Size(100.0, 100.0)), ); layout(sizer, constraints: BoxConstraints.tight(const Size(100.0, 100.0)), alignment: Alignment.topLeft); expect(round(inner.globalToLocal(Offset.zero)), equals(const Offset(100.0, 100.0))); expect(round(inner.globalToLocal(const Offset(100.0, 100.0))), equals(Offset.zero)); expect(round(inner.globalToLocal(const Offset(25.0, 75.0))), equals(const Offset(75.0, 25.0))); expect(round(inner.globalToLocal(const Offset(50.0, 50.0))), equals(const Offset(50.0, 50.0))); expect(round(inner.localToGlobal(Offset.zero)), equals(const Offset(100.0, 100.0))); expect(round(inner.localToGlobal(const Offset(100.0, 100.0))), equals(Offset.zero)); expect(round(inner.localToGlobal(const Offset(25.0, 75.0))), equals(const Offset(75.0, 25.0))); expect(round(inner.localToGlobal(const Offset(50.0, 50.0))), equals(const Offset(50.0, 50.0))); }); test('RenderTransform - rotation with internal offset', () { RenderBox inner; final RenderBox sizer = RenderTransform( transform: Matrix4.rotationZ(math.pi), alignment: Alignment.center, child: RenderPadding( padding: const EdgeInsets.only(left: 20.0), child: inner = RenderSizedBox(const Size(80.0, 100.0)), ), ); layout(sizer, constraints: BoxConstraints.tight(const Size(100.0, 100.0)), alignment: Alignment.topLeft); expect(round(inner.globalToLocal(Offset.zero)), equals(const Offset(80.0, 100.0))); expect(round(inner.globalToLocal(const Offset(100.0, 100.0))), equals(const Offset(-20.0, 0.0))); expect(round(inner.globalToLocal(const Offset(25.0, 75.0))), equals(const Offset(55.0, 25.0))); expect(round(inner.globalToLocal(const Offset(50.0, 50.0))), equals(const Offset(30.0, 50.0))); expect(round(inner.localToGlobal(Offset.zero)), equals(const Offset(80.0, 100.0))); expect(round(inner.localToGlobal(const Offset(100.0, 100.0))), equals(const Offset(-20.0, 0.0))); expect(round(inner.localToGlobal(const Offset(25.0, 75.0))), equals(const Offset(55.0, 25.0))); expect(round(inner.localToGlobal(const Offset(50.0, 50.0))), equals(const Offset(30.0, 50.0))); }); test('RenderTransform - perspective - globalToLocal', () { RenderBox inner; final RenderBox sizer = RenderTransform( transform: rotateAroundXAxis(math.pi * 0.25), // at pi/4, we are about 70 pixels high alignment: Alignment.center, child: inner = RenderSizedBox(const Size(100.0, 100.0)), ); layout(sizer, constraints: BoxConstraints.tight(const Size(100.0, 100.0)), alignment: Alignment.topLeft); expect(round(inner.globalToLocal(const Offset(25.0, 50.0))), equals(const Offset(25.0, 50.0))); expect(inner.globalToLocal(const Offset(25.0, 17.0)).dy, greaterThan(0.0)); expect(inner.globalToLocal(const Offset(25.0, 17.0)).dy, lessThan(10.0)); expect(inner.globalToLocal(const Offset(25.0, 83.0)).dy, greaterThan(90.0)); expect(inner.globalToLocal(const Offset(25.0, 83.0)).dy, lessThan(100.0)); expect( round(inner.globalToLocal(const Offset(25.0, 17.0))).dy, equals(100 - round(inner.globalToLocal(const Offset(25.0, 83.0))).dy), ); }); test('RenderTransform - perspective - localToGlobal', () { RenderBox inner; final RenderBox sizer = RenderTransform( transform: rotateAroundXAxis(math.pi * 0.4999), // at pi/2, we're seeing the box on its edge, alignment: Alignment.center, child: inner = RenderSizedBox(const Size(100.0, 100.0)), ); layout(sizer, constraints: BoxConstraints.tight(const Size(100.0, 100.0)), alignment: Alignment.topLeft); // the inner widget has a height of about half a pixel at this rotation, so // everything should end up around the middle of the outer box. expect(inner.localToGlobal(const Offset(25.0, 50.0)), equals(const Offset(25.0, 50.0))); expect(round(inner.localToGlobal(const Offset(25.0, 75.0))), equals(const Offset(25.0, 50.0))); expect(round(inner.localToGlobal(const Offset(25.0, 100.0))), equals(const Offset(25.0, 50.0))); }); } Matrix4 rotateAroundXAxis(double a) { // 3D rotation transform with alpha=a const double x = 1.0; const double y = 0.0; const double z = 0.0; final double sc = math.sin(a / 2.0) * math.cos(a / 2.0); final double sq = math.sin(a / 2.0) * math.sin(a / 2.0); return Matrix4.fromList(<double>[ // col 1 1.0 - 2.0 * (y * y + z * z) * sq, 2.0 * (x * y * sq + z * sc), 2.0 * (x * z * sq - y * sc), 0.0, // col 2 2.0 * (x * y * sq - z * sc), 1.0 - 2.0 * (x * x + z * z) * sq, 2.0 * (y * z * sq + x * sc), 0.0, // col 3 2.0 * (x * z * sq + y * sc), 2.0 * (y * z * sq - x * sc), 1.0 - 2.0 * (x * x + z * z) * sq, 0.0, // col 4 0.0, 0.0, 0.0, 1.0, ]); }
flutter/packages/flutter/test/rendering/transform_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/transform_test.dart", "repo_id": "flutter", "token_count": 4011 }
677
// 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/scheduler.dart'; import 'package:flutter_test/flutter_test.dart' show expect, test; // This file should not use testWidgets, and should not instantiate the binding. void main() { test('timeDilation can be set without a binding', () { expect(timeDilation, 1.0); timeDilation = 2.0; expect(timeDilation, 2.0); }); }
flutter/packages/flutter/test/scheduler/time_dilation_test.dart/0
{ "file_path": "flutter/packages/flutter/test/scheduler/time_dilation_test.dart", "repo_id": "flutter", "token_count": 168 }
678
// 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/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/clipboard_utils.dart'; void main() { final MockClipboard mockClipboard = MockClipboard(); TestWidgetsFlutterBinding.ensureInitialized() .defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); test('Clipboard.getData returns text', () async { mockClipboard.clipboardData = <String, dynamic>{ 'text': 'Hello world', }; final ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain); expect(data, isNotNull); expect(data!.text, equals('Hello world')); }); test('Clipboard.getData returns null', () async { mockClipboard.clipboardData = null; final ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain); expect(data, isNull); }); test('Clipboard.getData throws if text is missing', () async { mockClipboard.clipboardData = <String, dynamic>{}; expect(() => Clipboard.getData(Clipboard.kTextPlain), throwsA(isA<TypeError>())); }); test('Clipboard.getData throws if text is null', () async { mockClipboard.clipboardData = <String, dynamic>{ 'text': null, }; expect(() => Clipboard.getData(Clipboard.kTextPlain), throwsA(isA<TypeError>())); }); test('Clipboard.setData sets text', () async { await Clipboard.setData(const ClipboardData(text: 'Hello world')); expect(mockClipboard.clipboardData, <String, dynamic>{ 'text': 'Hello world', }); }); }
flutter/packages/flutter/test/services/clipboard_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/clipboard_test.dart", "repo_id": "flutter", "token_count": 594 }
679
// 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. @TestOn('!chrome') library; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('Mock binary message handler control test', () async { final List<ByteData?> log = <ByteData>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler('test1', (ByteData? message) async { log.add(message); return null; }); final ByteData message = ByteData(2)..setUint16(0, 0xABCD); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.send('test1', message); expect(log, equals(<ByteData>[message])); log.clear(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler('test1', null); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.send('test1', message); expect(log, isEmpty); }); }
flutter/packages/flutter/test/services/platform_messages_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/platform_messages_test.dart", "repo_id": "flutter", "token_count": 361 }
680
// 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/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); group('Undo Interactions', () { test('UndoManagerClient handleUndo', () async { // Assemble an UndoManagerClient so we can verify its change in state. final _FakeUndoManagerClient client = _FakeUndoManagerClient(); UndoManager.client = client; expect(client.latestMethodCall, isEmpty); // Send handleUndo message with "undo" as the direction. ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>['undo'], 'method': 'UndoManagerClient.handleUndo', }); await binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/undomanager', messageBytes, null, ); expect(client.latestMethodCall, 'handlePlatformUndo(${UndoDirection.undo})'); // Send handleUndo message with "undo" as the direction. messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>['redo'], 'method': 'UndoManagerClient.handleUndo', }); await binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/undomanager', messageBytes, (ByteData? _) {}, ); expect(client.latestMethodCall, 'handlePlatformUndo(${UndoDirection.redo})'); }); }); } class _FakeUndoManagerClient with UndoManagerClient { String latestMethodCall = ''; @override void undo() {} @override void redo() {} @override bool get canUndo => false; @override bool get canRedo => false; @override void handlePlatformUndo(UndoDirection direction) { latestMethodCall = 'handlePlatformUndo($direction)'; } }
flutter/packages/flutter/test/services/undo_manager_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/undo_manager_test.dart", "repo_id": "flutter", "token_count": 715 }
681
// 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/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('provides a value to the layer tree', (WidgetTester tester) async { await tester.pumpWidget( const AnnotatedRegion<int>( value: 1, child: SizedBox(width: 100.0, height: 100.0), ), ); final List<Layer> layers = tester.layers; final AnnotatedRegionLayer<int> layer = layers.whereType<AnnotatedRegionLayer<int>>().first; expect(layer.value, 1); }); testWidgets('provides a value to the layer tree in a particular region', (WidgetTester tester) async { await tester.pumpWidget( Transform.translate( offset: const Offset(25.0, 25.0), child: const AnnotatedRegion<int>( value: 1, child: SizedBox(width: 100.0, height: 100.0), ), ), ); int? result = RendererBinding.instance.renderView.debugLayer!.find<int>(Offset( 10.0 * tester.view.devicePixelRatio, 10.0 * tester.view.devicePixelRatio, )); expect(result, null); result = RendererBinding.instance.renderView.debugLayer!.find<int>(Offset( 50.0 * tester.view.devicePixelRatio, 50.0 * tester.view.devicePixelRatio, )); expect(result, 1); }); }
flutter/packages/flutter/test/widgets/annotated_region_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/annotated_region_test.dart", "repo_id": "flutter", "token_count": 580 }
682
// 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/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('attachRootWidget will schedule a frame', () async { final WidgetsFlutterBindingWithTestBinaryMessenger binding = WidgetsFlutterBindingWithTestBinaryMessenger(); expect(SchedulerBinding.instance.hasScheduledFrame, isFalse); // Framework starts with detached statue. Sends resumed signal to enable frame. final ByteData message = const StringCodec().encodeMessage('AppLifecycleState.resumed')!; await binding.defaultBinaryMessenger.handlePlatformMessage('flutter/lifecycle', message, (_) { }); binding.attachRootWidget(const Placeholder()); expect(SchedulerBinding.instance.hasScheduledFrame, isTrue); }); } class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding with TestDefaultBinaryMessengerBinding { }
flutter/packages/flutter/test/widgets/binding_attach_root_widget_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/binding_attach_root_widget_test.dart", "repo_id": "flutter", "token_count": 330 }
683
// 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/services.dart'; class MockClipboard { MockClipboard({ this.hasStringsThrows = false, }); final bool hasStringsThrows; dynamic clipboardData = <String, dynamic>{ 'text': null, }; Future<Object?> handleMethodCall(MethodCall methodCall) async { switch (methodCall.method) { case 'Clipboard.getData': return clipboardData; case 'Clipboard.hasStrings': if (hasStringsThrows) { throw Exception(); } final Map<String, dynamic>? clipboardDataMap = clipboardData as Map<String, dynamic>?; final String? text = clipboardDataMap?['text'] as String?; return <String, bool>{'value': text != null && text.isNotEmpty}; case 'Clipboard.setData': clipboardData = methodCall.arguments; } return null; } }
flutter/packages/flutter/test/widgets/clipboard_utils.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/clipboard_utils.dart", "repo_id": "flutter", "token_count": 365 }
684
// 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/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'keyboard_utils.dart'; void main() { Widget buildSpyAboveEditableText({ required FocusNode editableFocusNode, required FocusNode spyFocusNode, }) { final TextEditingController controller = TextEditingController(text: 'dummy text'); addTearDown(controller.dispose); return MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( // Softwrap at exactly 20 characters. width: 201, height: 200, child: ActionSpy( focusNode: spyFocusNode, child: EditableText( controller: controller, showSelectionHandles: true, autofocus: true, focusNode: editableFocusNode, style: const TextStyle(fontSize: 10.0), textScaleFactor: 1, // Avoid the cursor from taking up width. cursorWidth: 0, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, maxLines: null, textAlign: TextAlign.left, ), ), ), ), ); } group('iOS: do not handle delete/backspace events', () { final TargetPlatformVariant iOS = TargetPlatformVariant.only(TargetPlatform.iOS); final FocusNode editable = FocusNode(); final FocusNode spy = FocusNode(); testWidgets('backspace with and without word modifier', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown(tester.binding.testTextInput.register); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); for (int altShiftState = 0; altShiftState < 1 << 2; altShiftState += 1) { final bool alt = altShiftState & 0x1 != 0; final bool shift = altShiftState & 0x2 != 0; await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.backspace, alt: alt, shift: shift)); } await tester.pump(); expect(state.lastIntent, isNull); }, variant: iOS); testWidgets('delete with and without word modifier', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown(tester.binding.testTextInput.register); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); for (int altShiftState = 0; altShiftState < 1 << 2; altShiftState += 1) { final bool alt = altShiftState & 0x1 != 0; final bool shift = altShiftState & 0x2 != 0; await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.delete, alt: alt, shift: shift)); } await tester.pump(); expect(state.lastIntent, isNull); }, variant: iOS); testWidgets('Exception: deleting to line boundary is handled by the framework', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown(tester.binding.testTextInput.register); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); for (int keyState = 0; keyState < 1 << 2; keyState += 1) { final bool shift = keyState & 0x1 != 0; final LogicalKeyboardKey key = keyState & 0x2 != 0 ? LogicalKeyboardKey.delete : LogicalKeyboardKey.backspace; state.lastIntent = null; final SingleActivator activator = SingleActivator(key, meta: true, shift: shift); await sendKeyCombination(tester, activator); await tester.pump(); expect(state.lastIntent, isA<DeleteToLineBreakIntent>(), reason: '$activator'); } }, variant: iOS); }, skip: kIsWeb); // [intended] specific tests target non-web. group('macOS does not accept shortcuts if focus under EditableText', () { final TargetPlatformVariant macOSOnly = TargetPlatformVariant.only(TargetPlatform.macOS); testWidgets('word modifier + arrowLeft', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); await tester.pump(); expect(state.lastIntent, isNull); }, variant: macOSOnly); testWidgets('word modifier + arrowRight', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); await tester.pump(); expect(state.lastIntent, isNull); }, variant: macOSOnly); testWidgets('line modifier + arrowLeft', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); await tester.pump(); expect(state.lastIntent, isNull); }, variant: macOSOnly); testWidgets('line modifier + arrowRight', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); await tester.pump(); expect(state.lastIntent, isNull); }, variant: macOSOnly); testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); await tester.pump(); expect(state.lastIntent, isNull); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); await tester.pump(); expect(state.lastIntent, isNull); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); await tester.pump(); expect(state.lastIntent, isNull); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); await tester.pump(); expect(state.lastIntent, isNull); }, variant: macOSOnly); testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); await tester.pump(); expect(state.lastIntent, isNull); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); await tester.pump(); expect(state.lastIntent, isNull); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); await tester.pump(); expect(state.lastIntent, isNull); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); await tester.pump(); expect(state.lastIntent, isNull); }, variant: macOSOnly); }); group('macOS does accept shortcuts if focus above EditableText', () { final TargetPlatformVariant macOSOnly = TargetPlatformVariant.only(TargetPlatform.macOS); testWidgets('word modifier + arrowLeft', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); }, variant: macOSOnly); testWidgets('word modifier + arrowRight', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); }, variant: macOSOnly); testWidgets('line modifier + arrowLeft', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); }, variant: macOSOnly); testWidgets('line modifier + arrowRight', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); }, variant: macOSOnly); testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); state.lastIntent = null; await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); state.lastIntent = null; await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); state.lastIntent = null; await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); }, variant: macOSOnly); testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); addTearDown((){ tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); addTearDown(editable.dispose); final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( buildSpyAboveEditableText( editableFocusNode: editable, spyFocusNode: spy, ), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); state.lastIntent = null; await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); state.lastIntent = null; await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); state.lastIntent = null; await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); }, variant: macOSOnly); }, skip: kIsWeb); // [intended] specific tests target non-web. } class ActionSpy extends StatefulWidget { const ActionSpy({super.key, required this.focusNode, required this.child}); final FocusNode focusNode; final Widget child; @override State<ActionSpy> createState() => ActionSpyState(); } class ActionSpyState extends State<ActionSpy> { Intent? lastIntent; late final Map<Type, Action<Intent>> _actions = <Type, Action<Intent>>{ ExtendSelectionByCharacterIntent: CallbackAction<ExtendSelectionByCharacterIntent>(onInvoke: _captureIntent), ExtendSelectionToNextWordBoundaryIntent: CallbackAction<ExtendSelectionToNextWordBoundaryIntent>(onInvoke: _captureIntent), ExtendSelectionToLineBreakIntent: CallbackAction<ExtendSelectionToLineBreakIntent>(onInvoke: _captureIntent), ExpandSelectionToLineBreakIntent: CallbackAction<ExpandSelectionToLineBreakIntent>(onInvoke: _captureIntent), ExpandSelectionToDocumentBoundaryIntent: CallbackAction<ExpandSelectionToDocumentBoundaryIntent>(onInvoke: _captureIntent), ExtendSelectionVerticallyToAdjacentLineIntent: CallbackAction<ExtendSelectionVerticallyToAdjacentLineIntent>(onInvoke: _captureIntent), ExtendSelectionToDocumentBoundaryIntent: CallbackAction<ExtendSelectionToDocumentBoundaryIntent>(onInvoke: _captureIntent), ExtendSelectionToNextWordBoundaryOrCaretLocationIntent: CallbackAction<ExtendSelectionToNextWordBoundaryOrCaretLocationIntent>(onInvoke: _captureIntent), DeleteToLineBreakIntent: CallbackAction<DeleteToLineBreakIntent>(onInvoke: _captureIntent), DeleteToNextWordBoundaryIntent: CallbackAction<DeleteToNextWordBoundaryIntent>(onInvoke: _captureIntent), DeleteCharacterIntent: CallbackAction<DeleteCharacterIntent>(onInvoke: _captureIntent), }; // ignore: use_setters_to_change_properties void _captureIntent(Intent intent) { lastIntent = intent; } @override Widget build(BuildContext context) { return Actions( actions: _actions, child: Focus( focusNode: widget.focusNode, child: widget.child, ), ); } }
flutter/packages/flutter/test/widgets/default_text_editing_shortcuts_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/default_text_editing_shortcuts_test.dart", "repo_id": "flutter", "token_count": 7934 }
685
// 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 'dart:convert' show jsonDecode; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/clipboard_utils.dart'; import 'editable_text_utils.dart'; import 'live_text_utils.dart'; import 'semantics_tester.dart'; Matcher matchesMethodCall(String method, { dynamic args }) => _MatchesMethodCall(method, arguments: args == null ? null : wrapMatcher(args)); class _MatchesMethodCall extends Matcher { const _MatchesMethodCall(this.name, {this.arguments}); final String name; final Matcher? arguments; @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { if (item is MethodCall && item.method == name) { return arguments?.matches(item.arguments, matchState) ?? true; } return false; } @override Description describe(Description description) { final Description newDescription = description.add('has method name: ').addDescriptionOf(name); if (arguments != null) { newDescription.add(' with arguments: ').addDescriptionOf(arguments); } return newDescription; } } const TextStyle textStyle = TextStyle(); const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); enum HandlePositionInViewport { leftEdge, rightEdge, within, } typedef _VoidFutureCallback = Future<void> Function(); TextEditingValue collapsedAtEnd(String text) { return TextEditingValue( text: text, selection: TextSelection.collapsed(offset: text.length), ); } void main() { late TextEditingController controller; late FocusNode focusNode; late FocusScopeNode focusScopeNode; setUp(() async { final MockClipboard mockClipboard = MockClipboard(); TestWidgetsFlutterBinding.ensureInitialized() .defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); debugResetSemanticsIdCounter(); // Fill the clipboard so that the Paste option is available in the text // selection menu. await Clipboard.setData(const ClipboardData(text: 'Clipboard data')); controller = TextEditingController(); focusNode = FocusNode(debugLabel: 'EditableText Node'); focusScopeNode = FocusScopeNode(debugLabel: 'EditableText Scope Node'); }); tearDown(() { TestWidgetsFlutterBinding.ensureInitialized() .defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); controller.dispose(); focusNode.dispose(); focusScopeNode.dispose(); }); // Tests that the desired keyboard action button is requested. // // More technically, when an EditableText is given a particular [action], Flutter // requests [serializedActionName] when attaching to the platform's input // system. Future<void> desiredKeyboardActionIsRequested({ required WidgetTester tester, TextInputAction? action, String serializedActionName = '', }) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, textInputAction: action, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals(serializedActionName)); } testWidgets( 'Tapping the Live Text button calls onLiveTextInput', (WidgetTester tester) async { bool invokedLiveTextInputSuccessfully = false; final GlobalKey key = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, textAlign: TextAlign.right, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, EditableTextState editableTextState, ) { return CupertinoAdaptiveTextSelectionToolbar.editable( key: key, clipboardStatus: ClipboardStatus.pasteable, onCopy: null, onCut: null, onPaste: null, onSelectAll: null, onLookUp: null, onSearchWeb: null, onShare: null, onLiveTextInput: () { invokedLiveTextInputSuccessfully = true; }, anchors: const TextSelectionToolbarAnchors(primaryAnchor: Offset.zero), ); }, ), ), ), ), ); await tester.pump(); // Wait for autofocus to take effect. expect(find.byKey(key), findsNothing); // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(find.byKey(key), findsOneWidget); expect(findLiveTextButton(), findsOneWidget); await tester.tap(findLiveTextButton()); await tester.pump(); expect(invokedLiveTextInputSuccessfully, isTrue); }, skip: kIsWeb, // [intended] ); // Regression test for https://github.com/flutter/flutter/issues/126312. testWidgets('when open input connection in didUpdateWidget, should not throw', (WidgetTester tester) async { final Key key = GlobalKey(); final TextEditingController controller1 = TextEditingController(text: 'blah blah'); addTearDown(controller1.dispose); final TextEditingController controller2 = TextEditingController(text: 'blah blah'); addTearDown(controller2.dispose); await tester.pumpWidget( MaterialApp( home: EditableText( key: key, backgroundCursorColor: Colors.grey, controller: controller1, focusNode: focusNode, readOnly: true, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); focusNode.requestFocus(); await tester.pump(); // Reparent the EditableText, so that the parent has not yet been laid // out when didUpdateWidget is called. await tester.pumpWidget( MaterialApp( home: FractionalTranslation( translation: const Offset(0.1, 0.1), child: EditableText( key: key, backgroundCursorColor: Colors.grey, controller: controller2, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ), ); }); testWidgets('Text with selection can be shown on the screen when the keyboard shown', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/119628 addTearDown(tester.view.reset); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); controller.value = const TextEditingValue(text: 'I love flutter'); final Widget widget = MaterialApp( home: Scaffold( body: SingleChildScrollView( controller: scrollController, child: Column( children: <Widget>[ const SizedBox(height: 1000.0), SizedBox( height: 20.0, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.red, ), ), ], ), ), ), ); await tester.pumpWidget(widget); await tester.showKeyboard(find.byType(EditableText)); tester.view.viewInsets = const FakeViewPadding(bottom: 500); controller.selection = TextSelection( baseOffset: 0, extentOffset: controller.text.length, ); await tester.pump(); // The offset of the scrollController should change immediately after view changes its metrics. final double offsetAfter = scrollController.offset; expect(offsetAfter, isNot(0.0)); }); // Related issue: https://github.com/flutter/flutter/issues/98115 testWidgets('ScheduleShowCaretOnScreen with no animation when the view changes metrics', (WidgetTester tester) async { addTearDown(tester.view.reset); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final Widget widget = MaterialApp( home: Scaffold( body: SingleChildScrollView( controller: scrollController, child: Column( children: <Widget>[ Column( children: List<Widget>.generate( 5, (_) { return Container( height: 1200.0, color: Colors.black12, ); }, ), ), SizedBox( height: 20, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.red, ), ), ], ), ), ), ); await tester.pumpWidget(widget); await tester.showKeyboard(find.byType(EditableText)); tester.view.viewInsets = const FakeViewPadding(bottom: 500); await tester.pump(); // The offset of the scrollController should change immediately after view changes its metrics. final double offsetAfter = scrollController.offset; expect(offsetAfter, isNot(0.0)); }); // Regression test for https://github.com/flutter/flutter/issues/34538. testWidgets('RTL arabic correct caret placement after trailing whitespace', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.rtl, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.blue, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.idle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Simulates Gboard Persian input. state.updateEditingValue(const TextEditingValue(text: 'گ', selection: TextSelection.collapsed(offset: 1))); await tester.pump(); double previousCaretXPosition = state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; state.updateEditingValue(const TextEditingValue(text: 'گی', selection: TextSelection.collapsed(offset: 2))); await tester.pump(); double caretXPosition = state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; expect(caretXPosition, lessThan(previousCaretXPosition)); previousCaretXPosition = caretXPosition; state.updateEditingValue(const TextEditingValue(text: 'گیگ', selection: TextSelection.collapsed(offset: 3))); await tester.pump(); caretXPosition = state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; expect(caretXPosition, lessThan(previousCaretXPosition)); previousCaretXPosition = caretXPosition; // Enter a whitespace in a RTL input field moves the caret to the left. state.updateEditingValue(const TextEditingValue(text: 'گیگ ', selection: TextSelection.collapsed(offset: 4))); await tester.pump(); caretXPosition = state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; expect(caretXPosition, lessThan(previousCaretXPosition)); expect(state.currentTextEditingValue.text, equals('گیگ ')); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/78550. testWidgets('has expected defaults', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ); final EditableText editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.maxLines, equals(1)); expect(editableText.obscureText, isFalse); expect(editableText.autocorrect, isTrue); expect(editableText.enableSuggestions, isTrue); expect(editableText.enableIMEPersonalizedLearning, isTrue); expect(editableText.textAlign, TextAlign.start); expect(editableText.cursorWidth, 2.0); expect(editableText.cursorHeight, isNull); expect(editableText.textHeightBehavior, isNull); }); testWidgets('when backgroundCursorColor is updated, RenderEditable should be updated', (WidgetTester tester) async { Widget buildWidget(Color backgroundCursorColor) { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( controller: controller, backgroundCursorColor: backgroundCursorColor, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ); } await tester.pumpWidget(buildWidget(Colors.red)); await tester.pumpWidget(buildWidget(Colors.green)); final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; expect(render.backgroundCursorColor, Colors.green); }); testWidgets('text keyboard is requested when maxLines is default', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); final EditableText editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.maxLines, equals(1)); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); testWidgets('Keyboard is configured for "unspecified" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.unspecified, serializedActionName: 'TextInputAction.unspecified', ); }); testWidgets('Keyboard is configured for "none" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.none, serializedActionName: 'TextInputAction.none', ); }); testWidgets('Keyboard is configured for "done" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.done, serializedActionName: 'TextInputAction.done', ); }); testWidgets('Keyboard is configured for "send" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.send, serializedActionName: 'TextInputAction.send', ); }); testWidgets('Keyboard is configured for "go" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.go, serializedActionName: 'TextInputAction.go', ); }); testWidgets('Keyboard is configured for "search" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.search, serializedActionName: 'TextInputAction.search', ); }); testWidgets('Keyboard is configured for "send" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.send, serializedActionName: 'TextInputAction.send', ); }); testWidgets('Keyboard is configured for "next" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.next, serializedActionName: 'TextInputAction.next', ); }); testWidgets('Keyboard is configured for "previous" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.previous, serializedActionName: 'TextInputAction.previous', ); }); testWidgets('Keyboard is configured for "continue" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.continueAction, serializedActionName: 'TextInputAction.continueAction', ); }); testWidgets('Keyboard is configured for "join" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.join, serializedActionName: 'TextInputAction.join', ); }); testWidgets('Keyboard is configured for "route" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.route, serializedActionName: 'TextInputAction.route', ); }); testWidgets('Keyboard is configured for "emergencyCall" action when explicitly requested', (WidgetTester tester) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.emergencyCall, serializedActionName: 'TextInputAction.emergencyCall', ); }); testWidgets('insertContent does not throw and parses data correctly', (WidgetTester tester) async { String? latestUri; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, contentInsertionConfiguration: ContentInsertionConfiguration( onContentInserted: (KeyboardInsertedContent content) { latestUri = content.uri; }, allowedMimeTypes: const <String>['image/gif'], ), ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.enterText(find.byType(EditableText), 'test'); await tester.idle(); const String uri = 'content://com.google.android.inputmethod.latin.fileprovider/test.gif'; final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[ -1, 'TextInputAction.commitContent', jsonDecode('{"mimeType": "image/gif", "data": [0,1,0,1,0,1,0,0,0], "uri": "$uri"}'), ], 'method': 'TextInputClient.performAction', }); Object? error; try { await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/textinput', messageBytes, (ByteData? _) {}, ); } catch (e) { error = e; } expect(error, isNull); expect(latestUri, equals(uri)); }); testWidgets('onAppPrivateCommand does not throw', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[ -1, // The magic clint id that points to the current client. jsonDecode('{"action": "actionCommand", "data": {"input_context" : "abcdefg"}}'), ], 'method': 'TextInputClient.performPrivateCommand', }); Object? error; try { await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/textinput', messageBytes, (ByteData? _) {}, ); } catch (e) { error = e; } expect(error, isNull); }); group('Infer keyboardType from autofillHints', () { testWidgets( 'infer keyboard types from autofillHints: ios', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, autofillHints: const <String>[AutofillHints.streetAddressLine1], ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect( (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], // On web, we don't infer the keyboard type as "name". We only infer // on iOS and macOS. kIsWeb ? equals('TextInputType.address') : equals('TextInputType.name'), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'infer keyboard types from autofillHints: non-ios', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, autofillHints: const <String>[AutofillHints.streetAddressLine1], ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.address')); }, ); testWidgets( 'inferred keyboard types can be overridden: ios', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, keyboardType: TextInputType.text, autofillHints: const <String>[AutofillHints.streetAddressLine1], ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'inferred keyboard types can be overridden: non-ios', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, keyboardType: TextInputType.text, autofillHints: const <String>[AutofillHints.streetAddressLine1], ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); }, ); }); testWidgets('multiline keyboard is requested when set explicitly', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, keyboardType: TextInputType.multiline, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.multiline')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.newline')); }); testWidgets('EditableText sends enableInteractiveSelection to config', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( enableInteractiveSelection: true, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, keyboardType: TextInputType.multiline, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.textInputConfiguration.enableInteractiveSelection, isTrue); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( enableInteractiveSelection: false, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, keyboardType: TextInputType.multiline, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.textInputConfiguration.enableInteractiveSelection, isFalse); }); testWidgets('selection persists when unfocused', (WidgetTester tester) async { const TextEditingValue value = TextEditingValue( text: 'test test', selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 5, extentOffset: 7), ); controller.value = value; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, keyboardType: TextInputType.multiline, style: textStyle, cursorColor: cursorColor, ), ), ), ); expect(controller.value, value); expect(focusNode.hasFocus, isFalse); focusNode.requestFocus(); await tester.pump(); // On web, focusing a single-line input selects the entire field. final TextEditingValue webValue = value.copyWith( selection: TextSelection( baseOffset: 0, extentOffset: controller.value.text.length, ), ); if (kIsWeb) { expect(controller.value, webValue); } else { expect(controller.value, value); } expect(focusNode.hasFocus, isTrue); focusNode.unfocus(); await tester.pump(); if (kIsWeb) { expect(controller.value, webValue); } else { expect(controller.value, value); } expect(focusNode.hasFocus, isFalse); }); testWidgets('selection rects re-sent when refocused', (WidgetTester tester) async { final List<List<SelectionRect>> log = <List<SelectionRect>>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { if (methodCall.method == 'TextInput.setSelectionRects') { final List<dynamic> args = methodCall.arguments as List<dynamic>; final List<SelectionRect> selectionRects = <SelectionRect>[]; for (final dynamic rect in args) { selectionRects.add(SelectionRect( position: (rect as List<dynamic>)[4] as int, bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), )); } log.add(selectionRects); } return null; }); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); controller.text = 'Text1'; Future<void> pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: width, height: height, child: EditableText( controller: controller, textAlign: textAlign, scrollController: scrollController, maxLines: null, focusNode: focusNode, cursorWidth: 0, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ), ), ), ); } const List<SelectionRect> expectedRects = <SelectionRect>[ SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)) ]; await pumpEditableText(); expect(log, isEmpty); await tester.showKeyboard(find.byType(EditableText)); // First update. expect(log.single, expectedRects); log.clear(); await tester.pumpAndSettle(); expect(log, isEmpty); focusNode.unfocus(); await tester.pumpAndSettle(); expect(log, isEmpty); focusNode.requestFocus(); //await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); // Should re-receive the same rects. expect(log.single, expectedRects); log.clear(); // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] testWidgets('EditableText does not derive selection color from DefaultSelectionStyle', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/103341. const TextEditingValue value = TextEditingValue( text: 'test test', selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 5, extentOffset: 7), ); const Color selectionColor = Colors.orange; controller.value = value; await tester.pumpWidget( DefaultSelectionStyle( selectionColor: selectionColor, child: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, keyboardType: TextInputType.multiline, style: textStyle, cursorColor: cursorColor, ), ), ) ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.renderEditable.selectionColor, null); }); testWidgets('visiblePassword keyboard is requested when set explicitly', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, keyboardType: TextInputType.visiblePassword, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.visiblePassword')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); testWidgets('enableSuggestions flag is sent to the engine properly', (WidgetTester tester) async { const bool enableSuggestions = false; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, enableSuggestions: enableSuggestions, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.idle(); expect(tester.testTextInput.setClientArgs!['enableSuggestions'], enableSuggestions); }); testWidgets('enableIMEPersonalizedLearning flag is sent to the engine properly', (WidgetTester tester) async { const bool enableIMEPersonalizedLearning = false; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, enableIMEPersonalizedLearning: enableIMEPersonalizedLearning, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.idle(); expect(tester.testTextInput.setClientArgs!['enableIMEPersonalizedLearning'], enableIMEPersonalizedLearning); }); group('smartDashesType and smartQuotesType', () { testWidgets('sent to the engine properly', (WidgetTester tester) async { const SmartDashesType smartDashesType = SmartDashesType.disabled; const SmartQuotesType smartQuotesType = SmartQuotesType.disabled; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, smartDashesType: smartDashesType, smartQuotesType: smartQuotesType, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.idle(); expect(tester.testTextInput.setClientArgs!['smartDashesType'], smartDashesType.index.toString()); expect(tester.testTextInput.setClientArgs!['smartQuotesType'], smartQuotesType.index.toString()); }); testWidgets('default to true when obscureText is false', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.idle(); expect(tester.testTextInput.setClientArgs!['smartDashesType'], '1'); expect(tester.testTextInput.setClientArgs!['smartQuotesType'], '1'); }); testWidgets('default to false when obscureText is true', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, obscureText: true, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.idle(); expect(tester.testTextInput.setClientArgs!['smartDashesType'], '0'); expect(tester.testTextInput.setClientArgs!['smartQuotesType'], '0'); }); }); testWidgets('selection overlay will update when text grow bigger', (WidgetTester tester) async { controller.value = const TextEditingValue(text: 'initial value'); Future<void> pumpEditableTextWithTextStyle(TextStyle style) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: style, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, showSelectionHandles: true, ), ), ); } await pumpEditableTextWithTextStyle(const TextStyle(fontSize: 18)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.longPress, ); await tester.pumpAndSettle(); await tester.idle(); List<RenderBox> handles = List<RenderBox>.from( tester.renderObjectList<RenderBox>( find.descendant( of: find.byType(CompositedTransformFollower), matching: find.byType(Padding), ), ), ); expect(handles[0].localToGlobal(Offset.zero), const Offset(-35.0, 5.0)); expect(handles[1].localToGlobal(Offset.zero), const Offset(113.0, 5.0)); await pumpEditableTextWithTextStyle(const TextStyle(fontSize: 30)); await tester.pumpAndSettle(); // Handles should be updated with bigger font size. handles = List<RenderBox>.from( tester.renderObjectList<RenderBox>( find.descendant( of: find.byType(CompositedTransformFollower), matching: find.byType(Padding), ), ), ); // First handle should have the same dx but bigger dy. expect(handles[0].localToGlobal(Offset.zero), const Offset(-35.0, 17.0)); expect(handles[1].localToGlobal(Offset.zero), const Offset(197.0, 17.0)); }); testWidgets('can update style of previous activated EditableText', (WidgetTester tester) async { final TextEditingController controller1 = TextEditingController(); addTearDown(controller1.dispose); final TextEditingController controller2 = TextEditingController(); addTearDown(controller2.dispose); final TextEditingController controller3 = TextEditingController(); addTearDown(controller3.dispose); final TextEditingController controller4 = TextEditingController(); addTearDown(controller4.dispose); final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: Column( children: <Widget>[ EditableText( key: key1, controller: controller1, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: const TextStyle(fontSize: 9), cursorColor: cursorColor, ), EditableText( key: key2, controller: controller2, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: const TextStyle(fontSize: 9), cursorColor: cursorColor, ), ], ), ), ), ), ); await tester.tap(find.byKey(key1)); await tester.showKeyboard(find.byKey(key1)); controller.text = 'test'; await tester.idle(); RenderBox renderEditable = tester.renderObject(find.byKey(key1)); expect(renderEditable.size.height, 9.0); // Taps the other EditableText to deactivate the first one. await tester.tap(find.byKey(key2)); await tester.showKeyboard(find.byKey(key2)); // Updates the style. await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: Column( children: <Widget>[ EditableText( key: key1, controller: controller3, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: const TextStyle(fontSize: 20), cursorColor: cursorColor, ), EditableText( key: key2, controller: controller4, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: const TextStyle(fontSize: 9), cursorColor: cursorColor, ), ], ), ), ), ), ); renderEditable = tester.renderObject(find.byKey(key1)); expect(renderEditable.size.height, 20.0); expect(tester.takeException(), null); }); testWidgets('Multiline keyboard with newline action is requested when maxLines = null', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, maxLines: null, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.multiline')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.newline')); }); testWidgets('Text keyboard is requested when explicitly set and maxLines = null', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, maxLines: null, keyboardType: TextInputType.text, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); testWidgets('Correct keyboard is requested when set explicitly and maxLines > 1', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, keyboardType: TextInputType.phone, maxLines: 3, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.phone')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); testWidgets('multiline keyboard is requested when set implicitly', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, maxLines: 3, // Sets multiline keyboard implicitly. style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.multiline')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.newline')); }); testWidgets('single line inputs have correct default keyboard', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); // Test case for // https://github.com/flutter/flutter/issues/123523 // https://github.com/flutter/flutter/issues/134846 . testWidgets( 'The focus and callback behavior are correct when TextInputClient.onConnectionClosed message received', (WidgetTester tester) async { bool onSubmittedInvoked = false; bool onEditingCompleteInvoked = false; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, autofocus: true, cursorColor: cursorColor, onSubmitted: (String text) { onSubmittedInvoked = true; }, onEditingComplete: () { onEditingCompleteInvoked = true; }, ), ), ), ), ); expect(focusNode.hasFocus, isTrue); final EditableTextState editableText = tester.state(find.byType(EditableText)); editableText.connectionClosed(); await tester.pump(); expect(focusNode.hasFocus, isFalse); expect(onEditingCompleteInvoked, isFalse); expect(onSubmittedInvoked, isFalse); }); testWidgets('connection is closed when TextInputClient.onConnectionClosed message received', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('test')); expect(state.wantKeepAlive, true); tester.testTextInput.log.clear(); tester.testTextInput.closeConnection(); await tester.idle(); // Widget does not have focus anymore. expect(state.wantKeepAlive, false); // No method calls are sent from the framework. // This makes sure hide/clearClient methods are not called after connection // closed. expect(tester.testTextInput.log, isEmpty); }); testWidgets('closed connection reopened when user focused', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test3'; await tester.idle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('test3')); expect(state.wantKeepAlive, true); tester.testTextInput.log.clear(); tester.testTextInput.closeConnection(); await tester.pumpAndSettle(); // Widget does not have focus anymore. expect(state.wantKeepAlive, false); // No method calls are sent from the framework. // This makes sure hide/clearClient methods are not called after connection // closed. expect(tester.testTextInput.log, isEmpty); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.pump(); controller.text = 'test2'; expect(tester.testTextInput.editingState!['text'], equals('test2')); // Widget regained the focus. expect(state.wantKeepAlive, true); }); testWidgets('closed connection reopened when user focused on another field', (WidgetTester tester) async { final EditableText testNameField = EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, maxLines: null, keyboardType: TextInputType.text, style: textStyle, cursorColor: cursorColor, ); final EditableText testPhoneField = EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, keyboardType: TextInputType.phone, maxLines: 3, style: textStyle, cursorColor: cursorColor, ); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: ListView( children: <Widget>[ testNameField, testPhoneField, ], ), ), ), ), ); // Tap, enter text. await tester.tap(find.byWidget(testNameField)); await tester.showKeyboard(find.byWidget(testNameField)); controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); final EditableTextState state = tester.state<EditableTextState>(find.byWidget(testNameField)); expect(state.wantKeepAlive, true); tester.testTextInput.log.clear(); tester.testTextInput.closeConnection(); // A pump is needed to allow the focus change (unfocus) to be resolved. await tester.pump(); // Widget does not have focus anymore. expect(state.wantKeepAlive, false); // No method calls are sent from the framework. // This makes sure hide/clearClient methods are not called after connection // closed. expect(tester.testTextInput.log, isEmpty); // For the next fields, tap, enter text. await tester.tap(find.byWidget(testPhoneField)); await tester.showKeyboard(find.byWidget(testPhoneField)); controller.text = '650123123'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('650123123')); // Widget regained the focus. expect(state.wantKeepAlive, true); }); testWidgets( 'kept-alive EditableText does not crash when layout is skipped', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/84896. EditableText.debugDeterministicCursor = true; const Key key = ValueKey<String>('EditableText'); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: ListView( children: <Widget>[ EditableText( key: key, backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, autofocus: true, maxLines: null, keyboardType: TextInputType.text, style: textStyle, textAlign: TextAlign.left, cursorColor: cursorColor, showCursor: false, ), ], ), ), ), ); // Wait for autofocus. await tester.pump(); expect(focusNode.hasFocus, isTrue); // Prepend an additional item to make EditableText invisible. It's still // kept in the tree via the keepalive mechanism. Change the text alignment // and showCursor. The RenderEditable now needs to relayout and repaint. await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: ListView( children: <Widget>[ const SizedBox(height: 6000), EditableText( key: key, backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, autofocus: true, maxLines: null, keyboardType: TextInputType.text, style: textStyle, textAlign: TextAlign.right, cursorColor: cursorColor, showCursor: true, ), ], ), ), ), ); EditableText.debugDeterministicCursor = false; expect(tester.takeException(), isNull); }); // Toolbar is not used in Flutter Web unless the browser context menu is // explicitly disabled. Skip this check. // // Web is using native DOM elements (it is also used as platform input) // to enable clipboard functionality of the toolbar: copy, paste, select, // cut. It might also provide additional functionality depending on the // browser (such as translation). Due to this, in browsers, we should not // show a Flutter toolbar for the editable text elements. testWidgets('can show toolbar when there is text and a selection', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Can't show the toolbar when there's no focus. expect(state.showToolbar(), false); await tester.pumpAndSettle(); expect(find.text('Paste'), findsNothing); // Can show the toolbar when focused even though there's no text. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), kIsWeb ? findsNothing : findsOneWidget); // Hide the menu again. state.hideToolbar(); await tester.pump(); expect(find.text('Paste'), findsNothing); // Can show the menu with text and a selection. controller.text = 'blah'; await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), kIsWeb ? findsNothing : findsOneWidget); }); group('BrowserContextMenu', () { setUp(() async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.contextMenu, (MethodCall call) { // Just complete successfully, so that BrowserContextMenu thinks that // the engine successfully received its call. return Future<void>.value(); }, ); await BrowserContextMenu.disableContextMenu(); }); tearDown(() async { await BrowserContextMenu.enableContextMenu(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null); }); testWidgets('web can show flutter context menu when the browser context menu is disabled', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Can't show the toolbar when there's no focus. expect(state.showToolbar(), false); await tester.pumpAndSettle(); expect(find.text('Paste'), findsNothing); // Can show the toolbar when focused even though there's no text. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); expect(state.showToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); // Hide the menu again. state.hideToolbar(); await tester.pump(); expect(find.text('Paste'), findsNothing); // Can show the menu with text and a selection. controller.text = 'blah'; await tester.pump(); expect(state.showToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); }, skip: !kIsWeb, // [intended] ); }); testWidgets('can hide toolbar with DismissIntent', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Show the toolbar state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), kIsWeb ? findsNothing : findsOneWidget); // Hide the menu using the DismissIntent. await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pump(); expect(find.text('Paste'), findsNothing); }); testWidgets('toolbar hidden on mobile when orientation changes', (WidgetTester tester) async { addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Show the toolbar state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); expect(state.showToolbar(), true); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); // Hide the menu by changing orientation. tester.view.physicalSize = const Size(1800.0, 2400.0); await tester.pumpAndSettle(); expect(find.text('Paste'), findsNothing); // Handles should be hidden as well on Android expect( find.descendant( of: find.byType(CompositedTransformFollower), matching: find.byType(Padding), ), defaultTargetPlatform == TargetPlatform.android ? findsNothing : findsOneWidget, ); // On web, we don't show the Flutter toolbar and instead rely on the browser // toolbar. Until we change that, this test should remain skipped. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android })); // [intended] testWidgets('Paste is shown only when there is something to paste', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Make sure the clipboard has a valid string on it. await Clipboard.setData(const ClipboardData(text: 'Clipboard data')); // Show the toolbar. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); // The Paste button is shown (except on web, which doesn't show the Flutter // toolbar). expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), kIsWeb ? findsNothing : findsOneWidget); // Hide the menu again. state.hideToolbar(); await tester.pump(); expect(find.text('Paste'), findsNothing); // Clear the clipboard await Clipboard.setData(const ClipboardData(text: '')); // Show the toolbar again. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pumpAndSettle(); // Paste is not shown. await tester.pumpAndSettle(); expect(find.text('Paste'), findsNothing); }); testWidgets('Copy selection does not collapse selection on desktop and iOS', (WidgetTester tester) async { final TextEditingController localController = TextEditingController(text: 'Hello world'); addTearDown(localController.dispose); await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: localController, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Show the toolbar. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); final TextSelection copySelectionRange = localController.selection; state.showToolbar(); await tester.pumpAndSettle(); expect(find.text('Copy'), findsOneWidget); await tester.tap(find.text('Copy')); await tester.pumpAndSettle(); expect(copySelectionRange, localController.selection); expect(find.text('Copy'), findsNothing); }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.linux, TargetPlatform.windows })); // [intended] testWidgets('Copy selection collapses selection and hides the toolbar on Android and Fuchsia', (WidgetTester tester) async { final TextEditingController localController = TextEditingController(text: 'Hello world'); addTearDown(localController.dispose); await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: localController, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Show the toolbar. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); final TextSelection copySelectionRange = localController.selection; expect(find.byType(TextSelectionToolbar), findsNothing); state.showToolbar(); await tester.pumpAndSettle(); expect(find.byType(TextSelectionToolbar), findsOneWidget); expect(find.text('Copy'), findsOneWidget); await tester.tap(find.text('Copy')); await tester.pumpAndSettle(); expect(localController.selection, TextSelection.collapsed(offset: copySelectionRange.extentOffset)); expect(find.text('Copy'), findsNothing); }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia })); // [intended] testWidgets('can show the toolbar after clearing all text', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/35998. await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Add text and an empty selection. controller.text = 'blah'; await tester.pump(); state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); // Clear the text and selection. expect(find.text('Paste'), findsNothing); state.updateEditingValue(TextEditingValue.empty); await tester.pump(); // Should be able to show the toolbar. // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), kIsWeb ? findsNothing : findsOneWidget); }); testWidgets('can dynamically disable options in toolbar', (WidgetTester tester) async { controller.text = 'blah blah'; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, toolbarOptions: const ToolbarOptions( copy: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select something. Doesn't really matter what. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pump(); expect(find.text('Select all'), kIsWeb ? findsNothing : findsOneWidget); expect(find.text('Copy'), kIsWeb ? findsNothing : findsOneWidget); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); }); testWidgets('can dynamically disable select all option in toolbar - cupertino', (WidgetTester tester) async { // Regression test: https://github.com/flutter/flutter/issues/40711 controller.text = 'blah blah'; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, toolbarOptions: ToolbarOptions.empty, style: textStyle, cursorColor: cursorColor, selectionControls: cupertinoTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); await tester.tap(find.byType(EditableText)); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pump(); expect(find.text('Select All'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); }); testWidgets('can dynamically disable select all option in toolbar - material', (WidgetTester tester) async { // Regression test: https://github.com/flutter/flutter/issues/40711 controller.text = 'blah blah'; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, toolbarOptions: const ToolbarOptions( copy: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select something. Doesn't really matter what. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pump(); expect(find.text('Select all'), findsNothing); expect(find.text('Copy'), kIsWeb ? findsNothing : findsOneWidget); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); }); testWidgets('cut and paste are disabled in read only mode even if explicitly set', (WidgetTester tester) async { controller.text = 'blah blah'; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, readOnly: true, toolbarOptions: const ToolbarOptions( copy: true, cut: true, paste: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select something. Doesn't really matter what. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pump(); expect(find.text('Select all'), kIsWeb ? findsNothing : findsOneWidget); expect(find.text('Copy'), kIsWeb ? findsNothing : findsOneWidget); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); }); testWidgets('cut and copy are disabled in obscured mode even if explicitly set', (WidgetTester tester) async { controller.text = 'blah blah'; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, toolbarOptions: const ToolbarOptions( copy: true, cut: true, paste: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); await tester.tap(find.byType(EditableText)); await tester.pump(); // Select something, but not the whole thing. state.renderEditable.selectWord(cause: SelectionChangedCause.tap); await tester.pump(); expect(state.selectAllEnabled, isTrue); expect(state.pasteEnabled, isTrue); expect(state.cutEnabled, isFalse); expect(state.copyEnabled, isFalse); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pump(); expect(find.text('Select all'), kIsWeb ? findsNothing : findsOneWidget); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), kIsWeb ? findsNothing : findsOneWidget); expect(find.text('Cut'), findsNothing); }); testWidgets('cut and copy do nothing in obscured mode even if explicitly called', (WidgetTester tester) async { controller.text = 'blah blah'; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.selectAllEnabled, isTrue); expect(state.pasteEnabled, isTrue); expect(state.cutEnabled, isFalse); expect(state.copyEnabled, isFalse); // Select all. state.selectAll(SelectionChangedCause.toolbar); await tester.pump(); await Clipboard.setData(const ClipboardData(text: '')); state.cutSelection(SelectionChangedCause.toolbar); ClipboardData? data = await Clipboard.getData('text/plain'); expect(data, isNotNull); expect(data!.text, isEmpty); state.selectAll(SelectionChangedCause.toolbar); await tester.pump(); await Clipboard.setData(const ClipboardData(text: '')); state.copySelection(SelectionChangedCause.toolbar); data = await Clipboard.getData('text/plain'); expect(data, isNotNull); expect(data!.text, isEmpty); }); testWidgets('select all does nothing if obscured and read-only, even if explicitly called', (WidgetTester tester) async { controller.text = 'blah blah'; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, readOnly: true, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select all. state.selectAll(SelectionChangedCause.toolbar); expect(state.selectAllEnabled, isFalse); expect(state.textEditingValue.selection.isCollapsed, isTrue); }); group('buttonItemsForToolbarOptions', () { testWidgets('returns null when toolbarOptions are empty', (WidgetTester tester) async { controller.text = 'TEXT'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: ToolbarOptions.empty, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); expect(state.buttonItemsForToolbarOptions(), isNull); }); testWidgets('returns empty array when only cut is selected in toolbarOptions but cut is not enabled', (WidgetTester tester) async { controller.text = 'TEXT'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: const ToolbarOptions(cut: true), readOnly: true, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); expect(state.cutEnabled, isFalse); expect(state.buttonItemsForToolbarOptions(), isEmpty); }); testWidgets('returns only cut button when only cut is selected in toolbarOptions and cut is enabled', (WidgetTester tester) async { const String text = 'TEXT'; controller.text = text; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: const ToolbarOptions(cut: true), focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); // Selecting all. controller.selection = TextSelection( baseOffset: 0, extentOffset: controller.text.length, ); expect(state.cutEnabled, isTrue); final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); expect(items, isNotNull); expect(items, hasLength(1)); final ContextMenuButtonItem cutButton = items!.first; expect(cutButton.type, ContextMenuButtonType.cut); cutButton.onPressed?.call(); await tester.pump(); expect(controller.text, isEmpty); final ClipboardData? data = await Clipboard.getData('text/plain'); expect(data, isNotNull); expect(data!.text, equals(text)); }); testWidgets('returns empty array when only copy is selected in toolbarOptions but copy is not enabled', (WidgetTester tester) async { controller.text = 'TEXT'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: const ToolbarOptions(copy: true), obscureText: true, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); expect(state.copyEnabled, isFalse); expect(state.buttonItemsForToolbarOptions(), isEmpty); }); testWidgets('returns only copy button when only copy is selected in toolbarOptions and copy is enabled', (WidgetTester tester) async { const String text = 'TEXT'; controller.text = text; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: const ToolbarOptions(copy: true), focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); // Selecting all. controller.selection = TextSelection( baseOffset: 0, extentOffset: controller.text.length, ); expect(state.copyEnabled, isTrue); final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); expect(items, isNotNull); expect(items, hasLength(1)); final ContextMenuButtonItem copyButton = items!.first; expect(copyButton.type, ContextMenuButtonType.copy); copyButton.onPressed?.call(); await tester.pump(); expect(controller.text, equals(text)); final ClipboardData? data = await Clipboard.getData('text/plain'); expect(data, isNotNull); expect(data!.text, equals(text)); }); testWidgets('returns empty array when only paste is selected in toolbarOptions but paste is not enabled', (WidgetTester tester) async { controller.text = 'TEXT'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: const ToolbarOptions(paste: true), readOnly: true, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); expect(state.pasteEnabled, isFalse); expect(state.buttonItemsForToolbarOptions(), isEmpty); }); testWidgets('returns only paste button when only paste is selected in toolbarOptions and paste is enabled', (WidgetTester tester) async { const String text = 'TEXT'; controller.text = text; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: const ToolbarOptions(paste: true), focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); // Moving caret to the end. controller.selection = TextSelection.collapsed(offset: controller.text.length); expect(state.pasteEnabled, isTrue); final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); expect(items, isNotNull); expect(items, hasLength(1)); final ContextMenuButtonItem pasteButton = items!.first; expect(pasteButton.type, ContextMenuButtonType.paste); // Setting data which will be pasted into the clipboard. await Clipboard.setData(const ClipboardData(text: text)); pasteButton.onPressed?.call(); await tester.pump(); expect(controller.text, equals(text + text)); }); testWidgets('returns empty array when only selectAll is selected in toolbarOptions but selectAll is not enabled', (WidgetTester tester) async { controller.text = 'TEXT'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: const ToolbarOptions(selectAll: true), readOnly: true, obscureText: true, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); expect(state.selectAllEnabled, isFalse); expect(state.buttonItemsForToolbarOptions(), isEmpty); }); testWidgets('returns only selectAll button when only selectAll is selected in toolbarOptions and selectAll is enabled', (WidgetTester tester) async { const String text = 'TEXT'; controller.text = text; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, toolbarOptions: const ToolbarOptions(selectAll: true), focusNode: focusNode, style: textStyle, cursorColor: cursorColor, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText), ); final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); expect(items, isNotNull); expect(items, hasLength(1)); final ContextMenuButtonItem selectAllButton = items!.first; expect(selectAllButton.type, ContextMenuButtonType.selectAll); selectAllButton.onPressed?.call(); await tester.pump(); expect(controller.text, equals(text)); expect(state.textEditingValue.selection.textInside(text), equals(text)); }); }); testWidgets('Handles the read-only flag correctly', (WidgetTester tester) async { controller.text = 'Lorem ipsum dolor sit amet'; await tester.pumpWidget( MaterialApp( home: EditableText( readOnly: true, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); controller.selection = const TextSelection(baseOffset: 0, extentOffset: 5); await tester.pump(); if (kIsWeb) { // On the web, a regular connection to the platform should've been made // with the `readOnly` flag set to true. expect(tester.testTextInput.hasAnyClients, isTrue); expect(tester.testTextInput.setClientArgs!['readOnly'], isTrue); expect( tester.testTextInput.editingState!['text'], 'Lorem ipsum dolor sit amet', ); expect(tester.testTextInput.editingState!['selectionBase'], 0); expect(tester.testTextInput.editingState!['selectionExtent'], 5); } else { // On non-web platforms, a read-only field doesn't need a connection with // the platform. expect(tester.testTextInput.hasAnyClients, isFalse); } }); testWidgets('Does not accept updates when read-only', (WidgetTester tester) async { controller.text = 'Lorem ipsum dolor sit amet'; await tester.pumpWidget( MaterialApp( home: EditableText( readOnly: true, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); expect(tester.testTextInput.hasAnyClients, kIsWeb ? isTrue : isFalse); if (kIsWeb) { // On the web, the input connection exists, but text updates should be // ignored. tester.testTextInput.updateEditingValue(const TextEditingValue( text: 'Foo bar', selection: TextSelection(baseOffset: 0, extentOffset: 3), composing: TextRange(start: 3, end: 4), )); // Only selection should change. expect( controller.value, const TextEditingValue( text: 'Lorem ipsum dolor sit amet', selection: TextSelection(baseOffset: 0, extentOffset: 3), ), ); } }); testWidgets('Read-only fields do not format text', (WidgetTester tester) async { controller.text = 'Lorem ipsum dolor sit amet'; late SelectionChangedCause selectionCause; await tester.pumpWidget( MaterialApp( home: EditableText( readOnly: true, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { selectionCause = cause!; }, ), ), ); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); expect(tester.testTextInput.hasAnyClients, kIsWeb ? isTrue : isFalse); if (kIsWeb) { tester.testTextInput.updateEditingValue(const TextEditingValue( text: 'Foo bar', selection: TextSelection(baseOffset: 0, extentOffset: 3), )); // On web, the only way a text field can be updated from the engine is if // a keyboard is used. expect(selectionCause, SelectionChangedCause.keyboard); } }); testWidgets('Selection changes during Scribble interaction should have the scribble cause', (WidgetTester tester) async { controller.text = 'Lorem ipsum dolor sit amet'; late SelectionChangedCause selectionCause; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { if (cause != null) { selectionCause = cause; } }, ), ), ); await tester.showKeyboard(find.byType(EditableText)); // A normal selection update from the framework has 'keyboard' as the cause. tester.testTextInput.updateEditingValue(TextEditingValue( text: controller.text, selection: const TextSelection(baseOffset: 2, extentOffset: 3), )); await tester.pumpAndSettle(); expect(selectionCause, SelectionChangedCause.keyboard); // A selection update during a scribble interaction has 'scribble' as the cause. await tester.testTextInput.startScribbleInteraction(); tester.testTextInput.updateEditingValue(TextEditingValue( text: controller.text, selection: const TextSelection(baseOffset: 3, extentOffset: 4), )); await tester.pumpAndSettle(); expect(selectionCause, SelectionChangedCause.scribble); await tester.testTextInput.finishScribbleInteraction(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets('Requests focus and changes the selection when onScribbleFocus is called', (WidgetTester tester) async { controller.text = 'Lorem ipsum dolor sit amet'; late SelectionChangedCause selectionCause; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { if (cause != null) { selectionCause = cause; } }, ), ), ); await tester.testTextInput.scribbleFocusElement(TextInput.scribbleClients.keys.first, Offset.zero); expect(focusNode.hasFocus, true); expect(selectionCause, SelectionChangedCause.scribble); // On web, we should rely on the browser's implementation of Scribble, so the selection changed cause // will never be SelectionChangedCause.scribble. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] testWidgets('Declares itself for Scribble interaction if the bounds overlap the scribble rect and the widget is touchable', (WidgetTester tester) async { controller.text = 'Lorem ipsum dolor sit amet'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); final List<dynamic> elementEntry = <dynamic>[TextInput.scribbleClients.keys.first, 0.0, 0.0, 800.0, 600.0]; List<List<dynamic>> elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); expect(elements.first, containsAll(elementEntry)); // Touch is outside the bounds of the widget. elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(-1, -1, 1, 1)); expect(elements.length, 0); // Widget is read only. await tester.pumpWidget( MaterialApp( home: EditableText( readOnly: true, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); expect(elements.length, 0); // Widget is not touchable. await tester.pumpWidget( MaterialApp( home: Stack(children: <Widget>[ EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), Positioned( left: 0, top: 0, right: 0, bottom: 0, child: Container(color: Colors.black), ), ], ), ), ); elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); expect(elements.length, 0); // Widget has scribble disabled. await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, scribbleEnabled: false, ), ), ); elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); expect(elements.length, 0); // On web, we should rely on the browser's implementation of Scribble, so the engine will // never request the scribble elements. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] testWidgets('single line Scribble fields can show a horizontal placeholder', (WidgetTester tester) async { controller.text = 'Lorem ipsum dolor sit amet'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); await tester.showKeyboard(find.byType(EditableText)); tester.testTextInput.updateEditingValue(TextEditingValue( text: controller.text, selection: const TextSelection(baseOffset: 5, extentOffset: 5), )); await tester.pumpAndSettle(); await tester.testTextInput.scribbleInsertPlaceholder(); await tester.pumpAndSettle(); TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; expect(textSpan.children!.length, 3); expect((textSpan.children![0] as TextSpan).text, 'Lorem'); expect(textSpan.children![1] is WidgetSpan, true); expect((textSpan.children![2] as TextSpan).text, ' ipsum dolor sit amet'); await tester.testTextInput.scribbleRemovePlaceholder(); await tester.pumpAndSettle(); textSpan = findRenderEditable(tester).text! as TextSpan; expect(textSpan.children, null); expect(textSpan.text, 'Lorem ipsum dolor sit amet'); // Widget has scribble disabled. await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, scribbleEnabled: false, ), ), ); await tester.showKeyboard(find.byType(EditableText)); tester.testTextInput.updateEditingValue(TextEditingValue( text: controller.text, selection: const TextSelection(baseOffset: 5, extentOffset: 5), )); await tester.pumpAndSettle(); await tester.testTextInput.scribbleInsertPlaceholder(); await tester.pumpAndSettle(); textSpan = findRenderEditable(tester).text! as TextSpan; expect(textSpan.children, null); expect(textSpan.text, 'Lorem ipsum dolor sit amet'); // On web, we should rely on the browser's implementation of Scribble, so the framework // will not handle placeholders. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] testWidgets('multiline Scribble fields can show a vertical placeholder', (WidgetTester tester) async { controller.text = 'Lorem ipsum dolor sit amet'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, maxLines: 2, ), ), ); await tester.showKeyboard(find.byType(EditableText)); tester.testTextInput.updateEditingValue(TextEditingValue( text: controller.text, selection: const TextSelection(baseOffset: 5, extentOffset: 5), )); await tester.pumpAndSettle(); await tester.testTextInput.scribbleInsertPlaceholder(); await tester.pumpAndSettle(); TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; expect(textSpan.children!.length, 4); expect((textSpan.children![0] as TextSpan).text, 'Lorem'); expect(textSpan.children![1] is WidgetSpan, true); expect(textSpan.children![2] is WidgetSpan, true); expect((textSpan.children![3] as TextSpan).text, ' ipsum dolor sit amet'); await tester.testTextInput.scribbleRemovePlaceholder(); await tester.pumpAndSettle(); textSpan = findRenderEditable(tester).text! as TextSpan; expect(textSpan.children, null); expect(textSpan.text, 'Lorem ipsum dolor sit amet'); // Widget has scribble disabled. await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, maxLines: 2, scribbleEnabled: false, ), ), ); await tester.showKeyboard(find.byType(EditableText)); tester.testTextInput.updateEditingValue(TextEditingValue( text: controller.text, selection: const TextSelection(baseOffset: 5, extentOffset: 5), )); await tester.pumpAndSettle(); await tester.testTextInput.scribbleInsertPlaceholder(); await tester.pumpAndSettle(); textSpan = findRenderEditable(tester).text! as TextSpan; expect(textSpan.children, null); expect(textSpan.text, 'Lorem ipsum dolor sit amet'); // On web, we should rely on the browser's implementation of Scribble, so the framework // will not handle placeholders. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] testWidgets('Sends "updateConfig" when read-only flag is flipped', (WidgetTester tester) async { bool readOnly = true; late StateSetter setState; controller.text = 'Lorem ipsum dolor sit amet'; await tester.pumpWidget( MaterialApp( home: StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { setState = stateSetter; return EditableText( readOnly: readOnly, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ); }), ), ); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); expect(tester.testTextInput.hasAnyClients, kIsWeb ? isTrue : isFalse); if (kIsWeb) { expect(tester.testTextInput.setClientArgs!['readOnly'], isTrue); } setState(() { readOnly = false; }); await tester.pump(); expect(tester.testTextInput.hasAnyClients, isTrue); expect(tester.testTextInput.setClientArgs!['readOnly'], isFalse); }); testWidgets('Sends "updateConfig" when obscureText is flipped', (WidgetTester tester) async { bool obscureText = true; late StateSetter setState; controller.text = 'Lorem'; await tester.pumpWidget( MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter stateSetter) { setState = stateSetter; return EditableText( obscureText: obscureText, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ); }, ), ), ); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); expect(tester.testTextInput.setClientArgs!['obscureText'], isTrue); setState(() { obscureText = false; }); await tester.pump(); expect(tester.testTextInput.setClientArgs!['obscureText'], isFalse); }); testWidgets('Fires onChanged when text changes via TextSelectionOverlay', (WidgetTester tester) async { late String changedValue; final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, onChanged: (String value) { changedValue = value; }, ), ); await tester.pumpWidget(widget); // Populate a fake clipboard. const String clipboardContent = 'Dobunezumi mitai ni utsukushiku naritai'; Clipboard.setData(const ClipboardData(text: clipboardContent)); // Long-press to bring up the text editing controls. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); await tester.tap(find.text('Paste')); await tester.pump(); expect(changedValue, clipboardContent); // On web, we don't show the Flutter toolbar and instead rely on the browser // toolbar. Until we change that, this test should remain skipped. }, skip: kIsWeb); // [intended] // The variants to test in the focus handling test. final ValueVariant<TextInputAction> focusVariants = ValueVariant< TextInputAction>( TextInputAction.values.toSet(), ); testWidgets('Handles focus correctly when action is invoked', (WidgetTester tester) async { // The expectations for each of the types of TextInputAction. const Map<TextInputAction, bool> actionShouldLoseFocus = <TextInputAction, bool>{ TextInputAction.none: false, TextInputAction.unspecified: false, TextInputAction.done: true, TextInputAction.go: true, TextInputAction.search: true, TextInputAction.send: true, TextInputAction.continueAction: false, TextInputAction.join: false, TextInputAction.route: false, TextInputAction.emergencyCall: false, TextInputAction.newline: true, TextInputAction.next: true, TextInputAction.previous: true, }; final TextInputAction action = focusVariants.currentValue!; expect(actionShouldLoseFocus.containsKey(action), isTrue); Future<void> ensureCorrectFocusHandlingForAction( TextInputAction action, { required bool shouldLoseFocus, bool shouldFocusNext = false, bool shouldFocusPrevious = false, }) async { final GlobalKey previousKey = GlobalKey(); final GlobalKey nextKey = GlobalKey(); final Widget widget = MaterialApp( home: Column( children: <Widget>[ TextButton( child: Text('Previous Widget', key: previousKey), onPressed: () {}, ), EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, autofocus: true, ), TextButton( child: Text('Next Widget', key: nextKey), onPressed: () {}, ), ], ), ); await tester.pumpWidget(widget); assert(focusNode.hasFocus); await tester.testTextInput.receiveAction(action); await tester.pump(); expect(Focus.of(nextKey.currentContext!).hasFocus, equals(shouldFocusNext)); expect(Focus.of(previousKey.currentContext!).hasFocus, equals(shouldFocusPrevious)); expect(focusNode.hasFocus, equals(!shouldLoseFocus)); } try { await ensureCorrectFocusHandlingForAction( action, shouldLoseFocus: actionShouldLoseFocus[action]!, shouldFocusNext: action == TextInputAction.next, shouldFocusPrevious: action == TextInputAction.previous, ); } on PlatformException { // on Android, continueAction isn't supported. expect(action, equals(TextInputAction.continueAction)); } }, variant: focusVariants); testWidgets('Does not lose focus by default when "done" action is pressed and onEditingComplete is provided', (WidgetTester tester) async { final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, onEditingComplete: () { // This prevents the default focus change behavior on submission. }, ), ); await tester.pumpWidget(widget); // Select EditableText to give it focus. final Finder textFinder = find.byType(EditableText); await tester.tap(textFinder); await tester.pump(); assert(focusNode.hasFocus); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); // Still has focus even though "done" was pressed because onEditingComplete // was provided and it overrides the default behavior. expect(focusNode.hasFocus, true); }); testWidgets('When "done" is pressed callbacks are invoked: onEditingComplete > onSubmitted', (WidgetTester tester) async { bool onEditingCompleteCalled = false; bool onSubmittedCalled = false; final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, onEditingComplete: () { onEditingCompleteCalled = true; expect(onSubmittedCalled, false); }, onSubmitted: (String value) { onSubmittedCalled = true; expect(onEditingCompleteCalled, true); }, ), ); await tester.pumpWidget(widget); // Select EditableText to give it focus. final Finder textFinder = find.byType(EditableText); await tester.tap(textFinder); await tester.pump(); assert(focusNode.hasFocus); // The execution path starting with receiveAction() will trigger the // onEditingComplete and onSubmission callbacks. await tester.testTextInput.receiveAction(TextInputAction.done); // The expectations we care about are up above in the onEditingComplete // and onSubmission callbacks. }); testWidgets('When "next" is pressed callbacks are invoked: onEditingComplete > onSubmitted', (WidgetTester tester) async { bool onEditingCompleteCalled = false; bool onSubmittedCalled = false; final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, onEditingComplete: () { onEditingCompleteCalled = true; assert(!onSubmittedCalled); }, onSubmitted: (String value) { onSubmittedCalled = true; assert(onEditingCompleteCalled); }, ), ); await tester.pumpWidget(widget); // Select EditableText to give it focus. final Finder textFinder = find.byType(EditableText); await tester.tap(textFinder); await tester.pump(); assert(focusNode.hasFocus); // The execution path starting with receiveAction() will trigger the // onEditingComplete and onSubmission callbacks. await tester.testTextInput.receiveAction(TextInputAction.done); // The expectations we care about are up above in the onEditingComplete // and onSubmission callbacks. }); testWidgets('When "newline" action is called on a Editable text with maxLines == 1 callbacks are invoked: onEditingComplete > onSubmitted', (WidgetTester tester) async { bool onEditingCompleteCalled = false; bool onSubmittedCalled = false; final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, onEditingComplete: () { onEditingCompleteCalled = true; assert(!onSubmittedCalled); }, onSubmitted: (String value) { onSubmittedCalled = true; assert(onEditingCompleteCalled); }, ), ); await tester.pumpWidget(widget); // Select EditableText to give it focus. final Finder textFinder = find.byType(EditableText); await tester.tap(textFinder); await tester.pump(); assert(focusNode.hasFocus); // The execution path starting with receiveAction() will trigger the // onEditingComplete and onSubmission callbacks. await tester.testTextInput.receiveAction(TextInputAction.newline); // The expectations we care about are up above in the onEditingComplete // and onSubmission callbacks. }); testWidgets('When "newline" action is called on a Editable text with maxLines != 1, onEditingComplete and onSubmitted callbacks are not invoked.', (WidgetTester tester) async { bool onEditingCompleteCalled = false; bool onSubmittedCalled = false; final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, maxLines: 3, onEditingComplete: () { onEditingCompleteCalled = true; }, onSubmitted: (String value) { onSubmittedCalled = true; }, ), ); await tester.pumpWidget(widget); // Select EditableText to give it focus. final Finder textFinder = find.byType(EditableText); await tester.tap(textFinder); await tester.pump(); assert(focusNode.hasFocus); // The execution path starting with receiveAction() will trigger the // onEditingComplete and onSubmission callbacks. await tester.testTextInput.receiveAction(TextInputAction.newline); // These callbacks shouldn't have been triggered. assert(!onSubmittedCalled); assert(!onEditingCompleteCalled); }); testWidgets( 'finalizeEditing should reset the input connection when shouldUnfocus is true but the unfocus is cancelled', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/84240 . Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, focusNode: focusNode, controller: controller, onSubmitted: (String value) {}, ), ); await tester.pumpWidget(widget); focusNode.requestFocus(); await tester.pump(); assert(focusNode.hasFocus); tester.testTextInput.log.clear(); // This should unfocus the field. Don't restart the input. await tester.testTextInput.receiveAction(TextInputAction.done); expect(tester.testTextInput.log, isNot(containsAllInOrder(<Matcher>[ matchesMethodCall('TextInput.clearClient'), matchesMethodCall('TextInput.setClient'), ]))); widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, focusNode: focusNode, controller: controller, onSubmitted: (String value) { focusNode.requestFocus(); }, ), ); await tester.pumpWidget(widget); focusNode.requestFocus(); await tester.pump(); assert(focusNode.hasFocus); tester.testTextInput.log.clear(); // This will attempt to unfocus the field but the onSubmitted callback // will cancel that. Restart the input connection in this case. await tester.testTextInput.receiveAction(TextInputAction.done); expect(tester.testTextInput.log, containsAllInOrder(<Matcher>[ matchesMethodCall('TextInput.clearClient'), matchesMethodCall('TextInput.setClient'), ])); tester.testTextInput.log.clear(); // TextInputAction.unspecified does not unfocus the input field by default. await tester.testTextInput.receiveAction(TextInputAction.unspecified); expect(tester.testTextInput.log, isNot(containsAllInOrder(<Matcher>[ matchesMethodCall('TextInput.clearClient'), matchesMethodCall('TextInput.setClient'), ]))); }); testWidgets( 'requesting focus in the onSubmitted callback should keep the onscreen keyboard visible', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/95154 . final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, focusNode: focusNode, controller: controller, onSubmitted: (String value) { focusNode.requestFocus(); }, ), ); await tester.pumpWidget(widget); focusNode.requestFocus(); await tester.pump(); assert(focusNode.hasFocus); tester.testTextInput.log.clear(); // This will attempt to unfocus the field but the onSubmitted callback // will cancel that. Restart the input connection in this case. await tester.testTextInput.receiveAction(TextInputAction.done); expect(tester.testTextInput.log, containsAllInOrder(<Matcher>[ matchesMethodCall('TextInput.clearClient'), matchesMethodCall('TextInput.setClient'), matchesMethodCall('TextInput.show'), ])); tester.testTextInput.log.clear(); // TextInputAction.unspecified does not unfocus the input field by default. await tester.testTextInput.receiveAction(TextInputAction.unspecified); expect(tester.testTextInput.log, isNot(containsAllInOrder(<Matcher>[ matchesMethodCall('TextInput.clearClient'), matchesMethodCall('TextInput.setClient'), matchesMethodCall('TextInput.show'), ]))); }); testWidgets( 'iOS autocorrection rectangle should appear on demand and dismiss when the text changes or when focus is lost', (WidgetTester tester) async { const Color rectColor = Color(0xFFFF0000); controller.text = 'ABCDEFG'; void verifyAutocorrectionRectVisibility({ required bool expectVisible }) { PaintPattern evaluate() { if (expectVisible) { return paints..something((Symbol method, List<dynamic> arguments) { if (method != #drawRect) { return false; } final Paint paint = arguments[1] as Paint; return paint.color == rectColor; }); } else { return paints..everything((Symbol method, List<dynamic> arguments) { if (method != #drawRect) { return true; } final Paint paint = arguments[1] as Paint; if (paint.color != rectColor) { return true; } throw 'Expected: autocorrection rect not visible, found: ${arguments[0]}'; }); } } expect(findRenderEditable(tester), evaluate()); } final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, autocorrectionTextRectColor: rectColor, showCursor: false, onEditingComplete: () { }, ), ); await tester.pumpWidget(widget); await tester.tap(find.byType(EditableText)); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); assert(focusNode.hasFocus); // The prompt rect should be invisible initially. verifyAutocorrectionRectVisibility(expectVisible: false); state.showAutocorrectionPromptRect(0, 1); await tester.pump(); // Show prompt rect when told to. verifyAutocorrectionRectVisibility(expectVisible: true); await tester.enterText(find.byType(EditableText), '12345'); await tester.pump(); verifyAutocorrectionRectVisibility(expectVisible: false); state.showAutocorrectionPromptRect(0, 1); await tester.pump(); verifyAutocorrectionRectVisibility(expectVisible: true); // Unfocus, prompt rect should go away. focusNode.unfocus(); await tester.pumpAndSettle(); verifyAutocorrectionRectVisibility(expectVisible: false); }, ); testWidgets('Changing controller updates EditableText', (WidgetTester tester) async { final TextEditingController controller1 = TextEditingController(text: 'Wibble'); addTearDown(controller1.dispose); final TextEditingController controller2 = TextEditingController(text: 'Wobble'); addTearDown(controller2.dispose); TextEditingController currentController = controller1; late StateSetter setState; Widget builder() { return StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( backgroundCursorColor: Colors.grey, controller: currentController, focusNode: focusNode, style: Typography.material2018() .black .titleMedium!, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, onChanged: (String value) { }, ), ), ), ), ), ); }, ); } await tester.pumpWidget(builder()); await tester.pump(); // An extra pump to allow focus request to go through. final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.showKeyboard(find.byType(EditableText)); // Verify TextInput.setEditingState and TextInput.setEditableSizeAndTransform are // both fired with updated text when controller is replaced. setState(() { currentController = controller2; }); await tester.pump(); expect( log.lastWhere((MethodCall m) => m.method == 'TextInput.setEditingState'), isMethodCall( 'TextInput.setEditingState', arguments: const <String, dynamic>{ 'text': 'Wobble', 'selectionBase': -1, 'selectionExtent': -1, 'selectionAffinity': 'TextAffinity.downstream', 'selectionIsDirectional': false, 'composingBase': -1, 'composingExtent': -1, }, ), ); expect( log.lastWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'), isMethodCall( 'TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ 'width': 800, 'height': 14, 'transform': Matrix4.translationValues(0.0, 293.0, 0.0).storage.toList(), }, ), ); }); testWidgets('EditableText identifies as text field (w/ focus) in semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.isTextField])); await tester.tap(find.byType(EditableText)); await tester.idle(); await tester.pump(); expect( semantics, includesNodeWith(flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isFocused, ]), ); semantics.dispose(); }); testWidgets('EditableText sets multi-line flag in semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); expect( semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.isTextField]), ); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, maxLines: 3, ), ), ), ), ); expect( semantics, includesNodeWith(flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isMultiline, ]), ); semantics.dispose(); }); testWidgets('EditableText includes text as value in semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const String value1 = 'EditableText content'; controller.text = value1; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ); expect( semantics, includesNodeWith( flags: <SemanticsFlag>[SemanticsFlag.isTextField], value: value1, ), ); const String value2 = 'Changed the EditableText content'; controller.text = value2; await tester.idle(); await tester.pump(); expect( semantics, includesNodeWith( flags: <SemanticsFlag>[SemanticsFlag.isTextField], value: value2, ), ); semantics.dispose(); }); testWidgets('exposes correct cursor movement semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); controller.text = 'test'; await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); focusNode.requestFocus(); await tester.pump(); expect( semantics, includesNodeWith( value: 'test', ), ); controller.selection = TextSelection.collapsed(offset: controller.text.length); await tester.pumpAndSettle(); // At end, can only go backwards. expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, ], ), ); controller.selection = TextSelection.collapsed(offset:controller.text.length - 2); await tester.pumpAndSettle(); // Somewhere in the middle, can go in both directions. expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, ], ), ); controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpAndSettle(); // At beginning, can only go forward. expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorForwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, ], ), ); semantics.dispose(); }); testWidgets('can move cursor with a11y means - character', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const bool doNotExtendSelection = false; controller.text = 'test'; controller.selection = TextSelection.collapsed(offset:controller.text.length); await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, ], ), ); final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; final int semanticsId = render.debugSemantics!.id; expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 4); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByCharacter, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 3); expect(controller.selection.extentOffset, 3); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, ], ), ); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByCharacter, doNotExtendSelection, ); await tester.pumpAndSettle(); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByCharacter, doNotExtendSelection, ); await tester.pumpAndSettle(); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByCharacter, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 0); await tester.pumpAndSettle(); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorForwardByWord, ], ), ); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorForwardByCharacter, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 1); expect(controller.selection.extentOffset, 1); semantics.dispose(); }); testWidgets('can move cursor with a11y means - word', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const bool doNotExtendSelection = false; controller.text = 'test for words'; controller.selection = TextSelection.collapsed(offset:controller.text.length); await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); expect( semantics, includesNodeWith( value: 'test for words', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, ], ), ); final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; final int semanticsId = render.debugSemantics!.id; expect(controller.selection.baseOffset, 14); expect(controller.selection.extentOffset, 14); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByWord, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 9); expect(controller.selection.extentOffset, 9); expect( semantics, includesNodeWith( value: 'test for words', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, ], ), ); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByWord, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 5); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByWord, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 0); await tester.pumpAndSettle(); expect( semantics, includesNodeWith( value: 'test for words', actions: <SemanticsAction>[ SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorForwardByWord, ], ), ); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorForwardByWord, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 5); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorForwardByWord, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 9); expect(controller.selection.extentOffset, 9); semantics.dispose(); }); testWidgets('can extend selection with a11y means - character', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const bool extendSelection = true; const bool doNotExtendSelection = false; controller.text = 'test'; controller.selection = TextSelection.collapsed(offset:controller.text.length); await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, ], ), ); final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; final int semanticsId = render.debugSemantics!.id; expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 4); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByCharacter, extendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 3); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, ], ), ); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByCharacter, extendSelection, ); await tester.pumpAndSettle(); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByCharacter, extendSelection, ); await tester.pumpAndSettle(); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByCharacter, extendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 0); await tester.pumpAndSettle(); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorForwardByWord, ], ), ); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorForwardByCharacter, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 1); expect(controller.selection.extentOffset, 1); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorForwardByCharacter, extendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 1); expect(controller.selection.extentOffset, 2); semantics.dispose(); }); testWidgets('can extend selection with a11y means - word', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const bool extendSelection = true; const bool doNotExtendSelection = false; controller.text = 'test for words'; controller.selection = TextSelection.collapsed(offset:controller.text.length); await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); expect( semantics, includesNodeWith( value: 'test for words', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, ], ), ); final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; final int semanticsId = render.debugSemantics!.id; expect(controller.selection.baseOffset, 14); expect(controller.selection.extentOffset, 14); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByWord, extendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 14); expect(controller.selection.extentOffset, 9); expect( semantics, includesNodeWith( value: 'test for words', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, ], ), ); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByWord, extendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 14); expect(controller.selection.extentOffset, 5); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorBackwardByWord, extendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 14); expect(controller.selection.extentOffset, 0); await tester.pumpAndSettle(); expect( semantics, includesNodeWith( value: 'test for words', actions: <SemanticsAction>[ SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorForwardByWord, ], ), ); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorForwardByWord, doNotExtendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 5); tester.binding.pipelineOwner.semanticsOwner!.performAction( semanticsId, SemanticsAction.moveCursorForwardByWord, extendSelection, ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 9); semantics.dispose(); }); testWidgets('password fields have correct semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); controller.text = 'super-secret-password!!1'; await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, obscureText: true, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); final String expectedValue = '•' *controller.text.length; expect( semantics, hasSemantics( TestSemantics( children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isObscured, ], value: expectedValue, textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true, ignoreId: true, ), ); semantics.dispose(); }); testWidgets('password fields become obscured with the right semantics when set', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const String originalText = 'super-secret-password!!1'; controller.text = originalText; await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); final String expectedValue = '•' * originalText.length; expect( semantics, hasSemantics( TestSemantics( children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( children:<TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isTextField, ], value: originalText, textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true, ignoreId: true, ), ); focusNode.requestFocus(); // Now change it to make it obscure text. await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, obscureText: true, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); expect((findRenderEditable(tester).text! as TextSpan).text, expectedValue); expect( semantics, hasSemantics( TestSemantics( children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( children:<TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isObscured, SemanticsFlag.isFocused, ], actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.moveCursorBackwardByWord, ], value: expectedValue, textDirection: TextDirection.ltr, // Focusing a single-line field on web selects it. textSelection: kIsWeb ? const TextSelection(baseOffset: 0, extentOffset: 24) : const TextSelection.collapsed(offset: 24), ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true, ignoreId: true, ), ); semantics.dispose(); }); testWidgets('password fields can have their obscuring character customized', (WidgetTester tester) async { const String originalText = 'super-secret-password!!1'; controller.text = originalText; const String obscuringCharacter = '#'; await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, obscuringCharacter: obscuringCharacter, obscureText: true, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); final String expectedValue = obscuringCharacter * originalText.length; expect((findRenderEditable(tester).text! as TextSpan).text, expectedValue); }); testWidgets('password briefly shows last character when entered on mobile', (WidgetTester tester) async { final bool debugDeterministicCursor = EditableText.debugDeterministicCursor; EditableText.debugDeterministicCursor = false; addTearDown(() { EditableText.debugDeterministicCursor = debugDeterministicCursor; }); await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, obscureText: true, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); await tester.enterText(find.byType(EditableText), 'AA'); await tester.pump(); await tester.enterText(find.byType(EditableText), 'AAA'); await tester.pump(); expect((findRenderEditable(tester).text! as TextSpan).text, '••A'); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect((findRenderEditable(tester).text! as TextSpan).text, '•••'); }); group('a11y copy/cut/paste', () { Future<void> buildApp(MockTextSelectionControls controls, WidgetTester tester) { return tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: controls, ), )); } late MockTextSelectionControls controls; setUp(() { controller.text = 'test'; controller.selection = TextSelection.collapsed(offset:controller.text.length); controls = MockTextSelectionControls(); }); testWidgets('are exposed', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); controls.testCanCopy = false; controls.testCanCut = false; controls.testCanPaste = false; await buildApp(controls, tester); await tester.tap(find.byType(EditableText)); await tester.pump(); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, ], ), ); controls.testCanCopy = true; await buildApp(controls, tester); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.copy, ], ), ); controls.testCanCopy = false; controls.testCanPaste = true; await buildApp(controls, tester); await tester.pumpAndSettle(); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.paste, ], ), ); controls.testCanPaste = false; controls.testCanCut = true; await buildApp(controls, tester); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.cut, ], ), ); controls.testCanCopy = true; controls.testCanCut = true; controls.testCanPaste = true; await buildApp(controls, tester); expect( semantics, includesNodeWith( value: 'test', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.cut, SemanticsAction.copy, SemanticsAction.paste, ], ), ); semantics.dispose(); }); testWidgets('can copy/cut/paste with a11y', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); controls.testCanCopy = true; controls.testCanCut = true; controls.testCanPaste = true; await buildApp(controls, tester); await tester.tap(find.byType(EditableText)); await tester.pump(); final SemanticsOwner owner = tester.binding.pipelineOwner.semanticsOwner!; const int expectedNodeId = 5; expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics.rootChild( id: expectedNodeId, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isFocused, ], actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.setText, SemanticsAction.copy, SemanticsAction.cut, SemanticsAction.paste, ], value: 'test', textSelection: TextSelection.collapsed(offset: controller.text.length), textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, ), ); owner.performAction(expectedNodeId, SemanticsAction.copy); expect(controls.copyCount, 1); owner.performAction(expectedNodeId, SemanticsAction.cut); expect(controls.cutCount, 1); owner.performAction(expectedNodeId, SemanticsAction.paste); expect(controls.pasteCount, 1); semantics.dispose(); }); // Regression test for b/201218542. testWidgets('copying with a11y works even when toolbar is hidden', (WidgetTester tester) async { Future<void> testByControls(TextSelectionControls controls) async { final SemanticsTester semantics = SemanticsTester(tester); final TextEditingController controller = TextEditingController(text: 'ABCDEFG'); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: controls, ), )); await tester.tap(find.byType(EditableText)); await tester.pump(); final SemanticsOwner owner = tester.binding.pipelineOwner.semanticsOwner!; const int expectedNodeId = 5; expect(controller.value.selection.isCollapsed, isTrue); controller.selection = TextSelection( baseOffset: 0, extentOffset: controller.value.text.length, ); await tester.pump(); expect(find.text('Copy'), findsNothing); owner.performAction(expectedNodeId, SemanticsAction.copy); expect(tester.takeException(), isNull); expect( (await Clipboard.getData(Clipboard.kTextPlain))!.text, equals('ABCDEFG'), ); semantics.dispose(); } await testByControls(materialTextSelectionControls); await testByControls(cupertinoTextSelectionControls); }); }); testWidgets('can set text with a11y', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); await tester.tap(find.byType(EditableText)); await tester.pump(); final SemanticsOwner owner = tester.binding.pipelineOwner.semanticsOwner!; const int expectedNodeId = 4; expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics.rootChild( id: expectedNodeId, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isFocused, ], actions: <SemanticsAction>[ SemanticsAction.setSelection, SemanticsAction.setText, ], textSelection: TextSelection.collapsed(offset: controller.text.length), textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, ), ); expect(controller.text, ''); owner.performAction(expectedNodeId, SemanticsAction.setText, 'how are you'); expect(controller.text, 'how are you'); semantics.dispose(); }); testWidgets('allows customizing text style in subclasses', (WidgetTester tester) async { controller.text = 'Hello World'; await tester.pumpWidget(MaterialApp( home: CustomStyleEditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), )); // Simulate selection change via tap to show handles. final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; expect(render.text!.style!.fontStyle, FontStyle.italic); }); testWidgets('onChanged callback only invoked on text changes', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/111651 . int onChangedCount = 0; bool preventInput = false; final TextInputFormatter formatter = TextInputFormatter.withFunction((TextEditingValue oldValue, TextEditingValue newValue) { return preventInput ? oldValue : newValue; }); final Widget widget = MediaQuery( data: const MediaQueryData(), child: EditableText( controller: controller, backgroundCursorColor: Colors.red, cursorColor: Colors.red, focusNode: focusNode, style: textStyle, onChanged: (String newString) { onChangedCount += 1; }, inputFormatters: <TextInputFormatter>[formatter], textDirection: TextDirection.ltr, ), ); await tester.pumpWidget(widget); final EditableTextState state = tester.firstState(find.byType(EditableText)); state.updateEditingValue( const TextEditingValue(text: 'a', composing: TextRange(start: 0, end: 1)), ); expect(onChangedCount , 1); state.updateEditingValue( const TextEditingValue(text: 'a'), ); expect(onChangedCount , 1); state.updateEditingValue( const TextEditingValue(text: 'ab'), ); expect(onChangedCount , 2); preventInput = true; state.updateEditingValue( const TextEditingValue(text: 'abc'), ); expect(onChangedCount , 2); }); testWidgets('Formatters are skipped if text has not changed', (WidgetTester tester) async { int called = 0; final TextInputFormatter formatter = TextInputFormatter.withFunction((TextEditingValue oldValue, TextEditingValue newValue) { called += 1; return newValue; }); final MediaQuery mediaQuery = MediaQuery( data: const MediaQueryData(), child: EditableText( controller: controller, backgroundCursorColor: Colors.red, cursorColor: Colors.red, focusNode: focusNode, style: textStyle, inputFormatters: <TextInputFormatter>[ formatter, ], textDirection: TextDirection.ltr, ), ); await tester.pumpWidget(mediaQuery); final EditableTextState state = tester.firstState(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue( text: 'a', )); expect(called, 1); // same value. state.updateEditingValue(const TextEditingValue( text: 'a', )); expect(called, 1); // same value with different selection. state.updateEditingValue(const TextEditingValue( text: 'a', selection: TextSelection.collapsed(offset: 1), )); // different value. state.updateEditingValue(const TextEditingValue( text: 'b', )); expect(called, 2); }); testWidgets('default keyboardAppearance is respected', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/22212. final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ), ); await tester.showKeyboard(find.byType(EditableText)); final MethodCall setClient = log.first; expect(setClient.method, 'TextInput.setClient'); expect(((setClient.arguments as Iterable<dynamic>).last as Map<String, dynamic>)['keyboardAppearance'], 'Brightness.light'); }); testWidgets('location of widget is sent on show keyboard', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ), ); await tester.showKeyboard(find.byType(EditableText)); final MethodCall methodCall = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); expect( methodCall, isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ 'width': 800, 'height': 600, 'transform': Matrix4.identity().storage.toList(), }), ); }); testWidgets('transform and size is reset when text connection opens', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); final TextEditingController controller1 = TextEditingController(); addTearDown(controller1.dispose); final FocusNode focusNode1 = FocusNode(); addTearDown(focusNode1.dispose); final TextEditingController controller2 = TextEditingController(); addTearDown(controller2.dispose); final FocusNode focusNode2 = FocusNode(); addTearDown(focusNode2.dispose); controller1.text = 'Text1'; controller2.text = 'Text2'; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ EditableText( key: ValueKey<String>(controller1.text), controller: controller1, focusNode: focusNode1, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), const SizedBox(height: 200.0), EditableText( key: ValueKey<String>(controller2.text), controller: controller2, focusNode: focusNode2, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, minLines: 10, maxLines: 20, ), const SizedBox(height: 100.0), ], ), ), ), ); await tester.showKeyboard(find.byKey(ValueKey<String>(controller1.text))); final MethodCall methodCall = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); expect( methodCall, isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ 'width': 800, 'height': 14, 'transform': Matrix4.identity().storage.toList(), }), ); log.clear(); // Move to the next editable text. await tester.showKeyboard(find.byKey(ValueKey<String>(controller2.text))); final MethodCall methodCall2 = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); expect( methodCall2, isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ 'width': 800, 'height': 140.0, 'transform': <double>[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 214.0, 0.0, 1.0], }), ); log.clear(); // Move back to the first editable text. await tester.showKeyboard(find.byKey(ValueKey<String>(controller1.text))); final MethodCall methodCall3 = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); expect( methodCall3, isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ 'width': 800, 'height': 14, 'transform': Matrix4.identity().storage.toList(), }), ); }); testWidgets('size and transform are sent when they change', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); const Offset offset = Offset(10.0, 20.0); const Key transformButtonKey = Key('transformButton'); await tester.pumpWidget( const TransformedEditableText( offset: offset, transformButtonKey: transformButtonKey, ), ); await tester.showKeyboard(find.byType(EditableText)); MethodCall methodCall = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); expect( methodCall, isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ 'width': 800, 'height': 14, 'transform': Matrix4.identity().storage.toList(), }), ); log.clear(); await tester.tap(find.byKey(transformButtonKey)); await tester.pumpAndSettle(); // There should be a new platform message updating the transform. methodCall = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); expect( methodCall, isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ 'width': 800, 'height': 14, 'transform': Matrix4.translationValues(offset.dx, offset.dy, 0.0).storage.toList(), }), ); }); testWidgets('selection rects are sent when they change', (WidgetTester tester) async { addTearDown(tester.view.reset); // Ensure selection rects are sent on iPhone (using SE 3rd gen size) tester.view.physicalSize = const Size(750.0, 1334.0); final List<List<SelectionRect>> log = <List<SelectionRect>>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) { if (methodCall.method == 'TextInput.setSelectionRects') { final List<dynamic> args = methodCall.arguments as List<dynamic>; final List<SelectionRect> selectionRects = <SelectionRect>[]; for (final dynamic rect in args) { selectionRects.add(SelectionRect( position: (rect as List<dynamic>)[4] as int, bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), )); } log.add(selectionRects); } return null; }); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); controller.text = 'Text1'; Future<void> pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: width, height: height, child: EditableText( controller: controller, textAlign: textAlign, scrollController: scrollController, maxLines: null, focusNode: focusNode, cursorWidth: 0, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ), ), ), ); } await pumpEditableText(); expect(log, isEmpty); await tester.showKeyboard(find.byType(EditableText)); // First update. expect(log.single, const <SelectionRect>[ SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)) ]); log.clear(); await tester.pumpAndSettle(); expect(log, isEmpty); await pumpEditableText(); expect(log, isEmpty); // Change the width such that each character occupies a line. await pumpEditableText(width: 20); expect(log.single, const <SelectionRect>[ SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)) ]); log.clear(); await tester.enterText(find.byType(EditableText), 'Text1👨‍👩‍👦'); await tester.pump(); expect(log.single, const <SelectionRect>[ SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)), SelectionRect(position: 5, bounds: Rect.fromLTRB(0.0, 70.0, 42.0, 84.0)), ]); log.clear(); // The 4th line will be partially visible. await pumpEditableText(width: 20, height: 45); expect(log.single, const <SelectionRect>[ SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), ]); log.clear(); await pumpEditableText(width: 20, height: 45, textAlign: TextAlign.right); // This is 1px off from being completely right-aligned. The 1px width is // reserved for caret. expect(log.single, const <SelectionRect>[ SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), // These 2 lines will be out of bounds. // SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 56.0, 19.0, 70.0)), // SelectionRect(position: 5, bounds: Rect.fromLTRB(-23.0, 70.0, 19.0, 84.0)), ]); log.clear(); expect(scrollController.offset, 0); // Scrolling also triggers update. scrollController.jumpTo(14); await tester.pumpAndSettle(); expect(log.single, const <SelectionRect>[ SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, -14.0, 19.0, 0.0)), SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), // This line is skipped because it's below the bottom edge of the render // object. // SelectionRect(position: 5, bounds: Rect.fromLTRB(5.0, 56.0, 47.0, 70.0)), ]); log.clear(); // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] testWidgets('selection rects are not sent if scribbleEnabled is false', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); controller.text = 'Text1'; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ EditableText( key: ValueKey<String>(controller.text), controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, scribbleEnabled: false, ), ], ), ), ), ); await tester.showKeyboard(find.byKey(ValueKey<String>(controller.text))); // There should be a new platform message updating the selection rects. expect(log.where((MethodCall m) => m.method == 'TextInput.setSelectionRects').length, 0); // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] testWidgets('selection rects sent even when character corners are outside of paintBounds', (WidgetTester tester) async { final List<List<SelectionRect>> log = <List<SelectionRect>>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) { if (methodCall.method == 'TextInput.setSelectionRects') { final List<dynamic> args = methodCall.arguments as List<dynamic>; final List<SelectionRect> selectionRects = <SelectionRect>[]; for (final dynamic rect in args) { selectionRects.add(SelectionRect( position: (rect as List<dynamic>)[4] as int, bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), )); } log.add(selectionRects); } return null; }); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); controller.text = 'Text1'; final GlobalKey<EditableTextState> editableTextKey = GlobalKey(); Future<void> pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: width, height: height, child: EditableText( controller: controller, textAlign: textAlign, scrollController: scrollController, maxLines: null, focusNode: focusNode, cursorWidth: 0, key: editableTextKey, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ), ), ), ); } // Set height to 1 pixel less than full height. await pumpEditableText(height: 13); expect(log, isEmpty); // Scroll so that the top of each character is above the top of the renderEditable // and the bottom of each character is below the bottom of the renderEditable. final ViewportOffset offset = ViewportOffset.fixed(0.5); addTearDown(offset.dispose); editableTextKey.currentState!.renderEditable.offset = offset; await tester.showKeyboard(find.byType(EditableText)); // We should get all the rects. expect(log.single, const <SelectionRect>[ SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, -0.5, 14.0, 13.5)), SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, -0.5, 28.0, 13.5)), SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, -0.5, 42.0, 13.5)), SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, -0.5, 56.0, 13.5)), SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, -0.5, 70.0, 13.5)) ]); log.clear(); // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] testWidgets('text styling info is sent on show keyboard', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: EditableText( textDirection: TextDirection.rtl, controller: controller, focusNode: focusNode, style: const TextStyle( fontSize: 20.0, fontFamily: 'Roboto', fontWeight: FontWeight.w600, ), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ); await tester.showKeyboard(find.byType(EditableText)); final MethodCall setStyle = log.firstWhere((MethodCall m) => m.method == 'TextInput.setStyle'); expect( setStyle, isMethodCall('TextInput.setStyle', arguments: <String, dynamic>{ 'fontSize': 20.0, 'fontFamily': 'Roboto', 'fontWeightIndex': 5, 'textAlignIndex': 4, 'textDirectionIndex': 0, }), ); }); testWidgets('text styling info is sent on show keyboard (bold override)', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(boldText: true), child: EditableText( textDirection: TextDirection.rtl, controller: controller, focusNode: focusNode, style: const TextStyle( fontSize: 20.0, fontFamily: 'Roboto', fontWeight: FontWeight.w600, ), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ); await tester.showKeyboard(find.byType(EditableText)); final MethodCall setStyle = log.firstWhere((MethodCall m) => m.method == 'TextInput.setStyle'); expect( setStyle, isMethodCall('TextInput.setStyle', arguments: <String, dynamic>{ 'fontSize': 20.0, 'fontFamily': 'Roboto', 'fontWeightIndex': FontWeight.bold.index, 'textAlignIndex': 4, 'textDirectionIndex': 0, }), ); }); testWidgets('text styling info is sent on style update', (WidgetTester tester) async { final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); late StateSetter setState; const TextStyle textStyle1 = TextStyle( fontSize: 20.0, fontFamily: 'RobotoMono', fontWeight: FontWeight.w600, ); const TextStyle textStyle2 = TextStyle( fontSize: 20.0, fontFamily: 'Raleway', fontWeight: FontWeight.w700, ); TextStyle currentTextStyle = textStyle1; Widget builder() { return StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( backgroundCursorColor: Colors.grey, key: editableTextKey, controller: controller, focusNode: focusNode, style: currentTextStyle, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, onChanged: (String value) {}, ), ), ), ), ), ); }, ); } await tester.pumpWidget(builder()); await tester.showKeyboard(find.byType(EditableText)); final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); setState(() { currentTextStyle = textStyle2; }); await tester.pump(); // Updated styling information should be sent via TextInput.setStyle method. final MethodCall setStyle = log.firstWhere((MethodCall m) => m.method == 'TextInput.setStyle'); expect( setStyle, isMethodCall('TextInput.setStyle', arguments: <String, dynamic>{ 'fontSize': 20.0, 'fontFamily': 'Raleway', 'fontWeightIndex': 6, 'textAlignIndex': 4, 'textDirectionIndex': 1, }), ); }); group('setCaretRect', () { Widget builder() { return MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, onChanged: (String value) {}, ), ), ), ), ), ); } testWidgets( 'called with proper coordinates', (WidgetTester tester) async { controller.value = TextEditingValue(text: 'a' * 50); await tester.pumpWidget(builder()); await tester.showKeyboard(find.byType(EditableText)); expect(tester.testTextInput.log, contains( matchesMethodCall( 'TextInput.setCaretRect', args: allOf( // No composing text so the width should not be too wide because // it's empty. containsPair('x', equals(700)), containsPair('y', equals(0)), containsPair('width', equals(2)), containsPair('height', equals(14)), ), ), )); tester.testTextInput.log.clear(); controller.value = TextEditingValue( text: 'a' * 50, selection: const TextSelection(baseOffset: 0, extentOffset: 0), ); await tester.pump(); expect(tester.testTextInput.log, contains( matchesMethodCall( 'TextInput.setCaretRect', // Now the composing range is not empty. args: allOf( containsPair('x', equals(0)), containsPair('y', equals(0)), ), ), )); }, ); testWidgets( 'only send updates when necessary', (WidgetTester tester) async { controller.value = TextEditingValue(text: 'a' * 100); await tester.pumpWidget(builder()); await tester.showKeyboard(find.byType(EditableText)); expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.setCaretRect'))); tester.testTextInput.log.clear(); // Should not send updates every frame. await tester.pump(); expect(tester.testTextInput.log, isNot(contains(matchesMethodCall('TextInput.setCaretRect')))); }, ); testWidgets( 'set to selection start on forward selection', (WidgetTester tester) async { controller.value = TextEditingValue( text: 'a' * 100, selection: const TextSelection(baseOffset: 10, extentOffset: 30), ); await tester.pumpWidget(builder()); await tester.showKeyboard(find.byType(EditableText)); expect(tester.testTextInput.log, contains( matchesMethodCall( 'TextInput.setCaretRect', // Now the composing range is not empty. args: allOf( containsPair('x', equals(140)), containsPair('y', equals(0)), ), ), )); }, ); testWidgets( 'set to selection start on reversed selection', (WidgetTester tester) async { controller.value = TextEditingValue( text: 'a' * 100, selection: const TextSelection(baseOffset: 30, extentOffset: 10), ); await tester.pumpWidget(builder()); await tester.showKeyboard(find.byType(EditableText)); expect(tester.testTextInput.log, contains( matchesMethodCall( 'TextInput.setCaretRect', // Now the composing range is not empty. args: allOf( containsPair('x', equals(140)), containsPair('y', equals(0)), ), ), )); }, ); }); group('setMarkedTextRect', () { Widget builder() { return MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, onChanged: (String value) {}, ), ), ), ), ), ); } testWidgets( 'called when the composing range changes', (WidgetTester tester) async { controller.value = TextEditingValue(text: 'a' * 100); await tester.pumpWidget(builder()); await tester.showKeyboard(find.byType(EditableText)); expect(tester.testTextInput.log, contains( matchesMethodCall( 'TextInput.setMarkedTextRect', args: allOf( // No composing text so the width should not be too wide because // it's empty. containsPair('width', lessThanOrEqualTo(5)), containsPair('x', lessThanOrEqualTo(1)), ), ), )); tester.testTextInput.log.clear(); controller.value = collapsedAtEnd('a' * 100).copyWith(composing: const TextRange(start: 0, end: 10)); await tester.pump(); expect(tester.testTextInput.log, contains( matchesMethodCall( 'TextInput.setMarkedTextRect', // Now the composing range is not empty. args: containsPair('width', greaterThanOrEqualTo(10)), ), )); }, ); testWidgets( 'only send updates when necessary', (WidgetTester tester) async { controller.value = TextEditingValue(text: 'a' * 100, composing: const TextRange(start: 0, end: 10)); await tester.pumpWidget(builder()); await tester.showKeyboard(find.byType(EditableText)); expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.setMarkedTextRect'))); tester.testTextInput.log.clear(); // Should not send updates every frame. await tester.pump(); expect(tester.testTextInput.log, isNot(contains(matchesMethodCall('TextInput.setMarkedTextRect')))); }, ); testWidgets( 'zero matrix paint transform', (WidgetTester tester) async { controller.value = TextEditingValue(text: 'a' * 100, composing: const TextRange(start: 0, end: 10)); // Use a FittedBox with an zero-sized child to set the paint transform // to the zero matrix. await tester.pumpWidget(FittedBox(child: SizedBox.fromSize(size: Size.zero, child: builder()))); await tester.showKeyboard(find.byType(EditableText)); expect(tester.testTextInput.log, contains(matchesMethodCall( 'TextInput.setMarkedTextRect', args: allOf( containsPair('width', isNotNaN), containsPair('height', isNotNaN), containsPair('x', isNotNaN), containsPair('y', isNotNaN), ), ))); }, ); }); testWidgets('custom keyboardAppearance is respected', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/22212. final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardAppearance: Brightness.dark, ), ), ), ); await tester.showKeyboard(find.byType(EditableText)); final MethodCall setClient = log.first; expect(setClient.method, 'TextInput.setClient'); expect(((setClient.arguments as Iterable<dynamic>).last as Map<String, dynamic>)['keyboardAppearance'], 'Brightness.dark'); }); testWidgets('Composing text is underlined and underline is cleared when losing focus', (WidgetTester tester) async { controller.value = const TextEditingValue( text: 'text composing text', selection: TextSelection.collapsed(offset: 14), composing: TextRange(start: 5, end: 14), ); await tester.pumpWidget(MaterialApp( // So we can show overlays. home: EditableText( autofocus: true, backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, onEditingComplete: () { // This prevents the default focus change behavior on submission. }, ), )); assert(focusNode.hasFocus); // Autofocus has a one frame delay. await tester.pump(); final RenderEditable renderEditable = findRenderEditable(tester); // The actual text span is split into 3 parts with the middle part underlined. expect((renderEditable.text! as TextSpan).children!.length, 3); final TextSpan textSpan = (renderEditable.text! as TextSpan).children![1] as TextSpan; expect(textSpan.text, 'composing'); expect(textSpan.style!.decoration, TextDecoration.underline); focusNode.unfocus(); // Drain microtasks. await tester.idle(); await tester.pump(); expect((renderEditable.text! as TextSpan).children, isNull); // Everything's just formatted the same way now. expect((renderEditable.text! as TextSpan).text, 'text composing text'); expect(renderEditable.text!.style!.decoration, isNull); }); testWidgets('text selection toolbar visibility', (WidgetTester tester) async { controller.text = 'hello \n world \n this \n is \n text'; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: Container( height: 50, color: Colors.white, child: EditableText( showSelectionHandles: true, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, selectionColor: Colors.lightBlueAccent, maxLines: 3, ), ), ), )); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); // Select the first word. And show the toolbar. await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); expect(state.showToolbar(), true); await tester.pumpAndSettle(); // Find the toolbar fade transition while the toolbar is still visible. final List<FadeTransition> transitionsBefore = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionToolbarWrapper'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitionsBefore.length, 1); final FadeTransition toolbarBefore = transitionsBefore[0]; expect(toolbarBefore.opacity.value, 1.0); // Scroll until the selection is no longer within view. scrollable.controller!.jumpTo(50.0); await tester.pumpAndSettle(); // Try to find the toolbar fade transition after the toolbar has been hidden // as a result of a scroll. This removes the toolbar overlay entry so no fade // transition should be found. final List<FadeTransition> transitionsAfter = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionToolbarWrapper'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitionsAfter.length, 0); expect(state.selectionOverlay, isNotNull); expect(state.selectionOverlay!.toolbarIsVisible, false); // On web, we don't show the Flutter toolbar and instead rely on the browser // toolbar. Until we change that, this test should remain skipped. }, skip: kIsWeb); // [intended] testWidgets('text selection handle visibility', (WidgetTester tester) async { // Text with two separate words to select. controller.text = 'XXXXX XXXXX'; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 100, child: EditableText( showSelectionHandles: true, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, ), ), ), )); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); bool expectedLeftVisibleBefore = false; bool expectedRightVisibleBefore = false; Future<void> verifyVisibility( HandlePositionInViewport leftPosition, bool expectedLeftVisible, HandlePositionInViewport rightPosition, bool expectedRightVisible, ) async { await tester.pump(); // Check the signal from RenderEditable about whether they're within the // viewport. expect(renderEditable.selectionStartInViewport.value, equals(expectedLeftVisible)); expect(renderEditable.selectionEndInViewport.value, equals(expectedRightVisible)); // Check that the animations are functional and going in the right // direction. final List<FadeTransition> transitions = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0]; final FadeTransition right = transitions[1]; if (expectedLeftVisibleBefore) { expect(left.opacity.value, equals(1.0)); } if (expectedRightVisibleBefore) { expect(right.opacity.value, equals(1.0)); } await tester.pump(SelectionOverlay.fadeDuration ~/ 2); if (expectedLeftVisible != expectedLeftVisibleBefore) { expect(left.opacity.value, equals(0.5)); } if (expectedRightVisible != expectedRightVisibleBefore) { expect(right.opacity.value, equals(0.5)); } await tester.pump(SelectionOverlay.fadeDuration ~/ 2); if (expectedLeftVisible) { expect(left.opacity.value, equals(1.0)); } if (expectedRightVisible) { expect(right.opacity.value, equals(1.0)); } expectedLeftVisibleBefore = expectedLeftVisible; expectedRightVisibleBefore = expectedRightVisible; // Check that the handles' positions are correct. final List<RenderBox> handles = List<RenderBox>.from( tester.renderObjectList<RenderBox>( find.descendant( of: find.byType(CompositedTransformFollower), matching: find.byType(Padding), ), ), ); final Size viewport = renderEditable.size; void testPosition(double pos, HandlePositionInViewport expected) { switch (expected) { case HandlePositionInViewport.leftEdge: expect( pos, inExclusiveRange( 0 - kMinInteractiveDimension, 0 + kMinInteractiveDimension, ), ); case HandlePositionInViewport.rightEdge: expect( pos, inExclusiveRange( viewport.width - kMinInteractiveDimension, viewport.width + kMinInteractiveDimension, ), ); case HandlePositionInViewport.within: expect( pos, inExclusiveRange( 0 - kMinInteractiveDimension, viewport.width + kMinInteractiveDimension, ), ); } } expect(state.selectionOverlay!.handlesAreVisible, isTrue); testPosition(handles[0].localToGlobal(Offset.zero).dx, leftPosition); testPosition(handles[1].localToGlobal(Offset.zero).dx, rightPosition); } // Select the first word. Both handles should be visible. await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pump(); await verifyVisibility(HandlePositionInViewport.leftEdge, true, HandlePositionInViewport.within, true); // Drag the text slightly so the first word is partially visible. Only the // right handle should be visible. scrollable.controller!.jumpTo(20.0); await verifyVisibility(HandlePositionInViewport.leftEdge, false, HandlePositionInViewport.within, true); // Drag the text all the way to the left so the first word is not visible at // all (and the second word is fully visible). Both handles should be // invisible now. scrollable.controller!.jumpTo(200.0); await verifyVisibility(HandlePositionInViewport.leftEdge, false, HandlePositionInViewport.leftEdge, false); // Tap to unselect. await tester.tap(find.byType(EditableText)); await tester.pump(); // Now that the second word has been dragged fully into view, select it. await tester.tapAt(const Offset(80, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pump(); await verifyVisibility(HandlePositionInViewport.within, true, HandlePositionInViewport.within, true); // Drag the text slightly to the right. Only the left handle should be // visible. scrollable.controller!.jumpTo(150); await verifyVisibility(HandlePositionInViewport.within, true, HandlePositionInViewport.rightEdge, false); // Drag the text all the way to the right, so the second word is not visible // at all. Again, both handles should be invisible. scrollable.controller!.jumpTo(0); await verifyVisibility(HandlePositionInViewport.rightEdge, false, HandlePositionInViewport.rightEdge, false); // On web, we don't show the Flutter toolbar and instead rely on the browser // toolbar. Until we change that, this test should remain skipped. }, skip: kIsWeb); // [intended] testWidgets('text selection handle visibility RTL', (WidgetTester tester) async { // Text with two separate words to select. controller.text = 'XXXXX XXXXX'; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 100, child: EditableText( controller: controller, showSelectionHandles: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select the first word. Both handles should be visible. await tester.tapAt(const Offset(20, 10)); state.renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pump(); final List<RenderBox> handles = List<RenderBox>.from( tester.renderObjectList<RenderBox>( find.descendant( of: find.byType(CompositedTransformFollower), matching: find.byType(Padding), ), ), ); expect( handles[0].localToGlobal(Offset.zero).dx, inExclusiveRange( -kMinInteractiveDimension, kMinInteractiveDimension, ), ); expect( handles[1].localToGlobal(Offset.zero).dx, inExclusiveRange( 70.0 - kMinInteractiveDimension, 70.0 + kMinInteractiveDimension, ), ); expect(state.selectionOverlay!.handlesAreVisible, isTrue); expect(controller.selection.base.offset, 0); expect(controller.selection.extent.offset, 5); // On web, we don't show the Flutter toolbar and instead rely on the browser // toolbar. Until we change that, this test should remain skipped. }, skip: kIsWeb); // [intended] const String testText = 'Now is the time for\n' // 20 'all good people\n' // 20 + 16 => 36 'to come to the aid\n' // 36 + 19 => 55 'of their country.'; // 55 + 17 => 72 Future<void> testTextEditing(WidgetTester tester, {required TargetPlatform targetPlatform}) async { final String targetPlatformString = targetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); late TextSelection selection; late SelectionChangedCause cause; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; cause = newCause!; }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. // Select a few characters using shift right arrow await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 3, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Select fewer characters using shift left arrow await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 0, ), ), reason: 'on $platform', ); // Try to select before the first character, nothing should change. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 0, ), ), reason: 'on $platform', ); // Select the first two words. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 6, ), ), reason: 'on $platform', ); // Unselect the second word. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 4, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Select the next line. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 20, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 20, extentOffset: 20, ), ), reason: 'on $platform', ); // Select the next line. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 20, extentOffset: 39, ), ), reason: 'on $platform', ); // Select to the end of the string by going down. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowDown, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 20, extentOffset: testText.length, ), ), reason: 'on $platform', ); // Go back up one line to set selection up to part of the last line. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowUp, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 20, extentOffset: 39, ), ), reason: 'on $platform', ); // Select to the end of the selection. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 20, extentOffset: 54, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms extend by line. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect( selection, equals( const TextSelection( baseOffset: 20, extentOffset: 36, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Mac and iOS expand by line. case TargetPlatform.iOS: case TargetPlatform.macOS: expect( selection, equals( const TextSelection( baseOffset: 20, extentOffset: 54, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); } // Select All await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyA, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: testText.length, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Jump to beginning of selection. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 0, ), ), reason: 'on $platform', ); // Jump to end. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, ], lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection.collapsed( offset: testText.length, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); // Jump to start. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowUp, ], lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection.collapsed( offset: 0, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); // Move forward a few letters await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection.collapsed( offset: 3, ), ), reason: 'on $platform', ); // Select to end. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 3, extentOffset: testText.length, ), ), reason: 'on $platform', ); // Select to start, which extends the selection. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowUp, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // Extend selection. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect( selection, equals( const TextSelection( baseOffset: 3, extentOffset: 0, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // On macOS/iOS expand selection. case TargetPlatform.iOS: case TargetPlatform.macOS: expect( selection, equals( const TextSelection( baseOffset: 72, extentOffset: 0, ), ), reason: 'on $platform', ); } // Move to start again. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowUp, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection.collapsed( offset: 0, ), ), reason: 'on $platform', ); // Move down by page. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageDown, ], targetPlatform: defaultTargetPlatform, ); // On macOS, pageDown/Up don't change selection. expect( selection, equals( defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS ? const TextSelection.collapsed(offset: 0) : const TextSelection.collapsed(offset: 55), ), reason: 'on $platform', ); // Move up by page (to start). await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection.collapsed( offset: 0, ), ), reason: 'on $platform', ); // Select towards end by page. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageDown, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 55, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Change selection extent towards start by page. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection.collapsed( offset: 0, ), ), reason: 'on $platform', ); // Jump forward three words. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 10, ), ), reason: 'on $platform', ); // Select some characters backward. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 7, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Select a word backward. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 4, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); // Cut await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyX, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 4, extentOffset: 4, ), ), reason: 'on $platform', ); expect( controller.text, equals( 'Now time for\n' 'all good people\n' 'to come to the aid\n' 'of their country.', ), reason: 'on $platform', ); expect( (await Clipboard.getData(Clipboard.kTextPlain))!.text, equals('is the'), reason: 'on $platform', ); // Paste await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyV, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 10, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); final bool platformIsApple = defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS; // Move down one paragraph. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 20, ), ), reason: 'on $platform', ); // Move down another paragraph. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 36, ), ), reason: 'on $platform', ); // Move down another paragraph. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 55, ), ), reason: 'on $platform', ); // Move up a paragraph. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowUp, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 36, ), ), reason: 'on $platform', ); // Move up a paragraph. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowUp, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 20, ), ), reason: 'on $platform', ); // Move up. This will collapse the selection to the origin on Apple platforms, and // extend to the previous paragraph boundary on other platforms. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowUp, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( TextSelection( baseOffset: 10, extentOffset: platformIsApple ? 10 : 0, ), ), reason: 'on $platform', ); // Move up, extending the selection backwards to the previous paragraph on Apple platforms. // On other platforms this does nothing since our extent is already at 0 from the previous // set of keys sent. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowUp, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 10, extentOffset: 0, ), ), reason: 'on $platform', ); // Move down, collapsing the selection to the origin on Apple platforms. // On other platforms this moves the selection's extent to the next paragraph boundary. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, ], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( TextSelection( baseOffset: 10, extentOffset: platformIsApple ? 10 : 20, affinity: platformIsApple ? TextAffinity.upstream : TextAffinity.downstream, ), ), reason: 'on $platform', ); // Copy All await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyC, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: testText.length, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); expect((await Clipboard.getData(Clipboard.kTextPlain))!.text, equals(testText)); if (defaultTargetPlatform != TargetPlatform.iOS) { // Delete await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.delete, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 0, ), ), reason: 'on $platform', ); expect(controller.text, isEmpty, reason: 'on $platform'); controller.text = 'abc'; controller.selection = const TextSelection(baseOffset: 2, extentOffset: 2); // Backspace await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.backspace, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 1, extentOffset: 1, ), ), reason: 'on $platform', ); expect(controller.text, 'ac', reason: 'on $platform'); // Shift-backspace (same as backspace) await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.backspace, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 0, ), ), reason: 'on $platform', ); expect(controller.text, 'c', reason: 'on $platform'); } } testWidgets('keyboard text selection works (RawKeyEvent)', (WidgetTester tester) async { debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.rawKeyData; await testTextEditing(tester, targetPlatform: defaultTargetPlatform); debugKeyEventSimulatorTransitModeOverride = null; // On web, using keyboard for selection is handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('keyboard text selection works (ui.KeyData then RawKeyEvent)', (WidgetTester tester) async { debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.keyDataThenRawKeyData; await testTextEditing(tester, targetPlatform: defaultTargetPlatform); debugKeyEventSimulatorTransitModeOverride = null; // On web, using keyboard for selection is handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets( 'keyboard shortcuts respect read-only', (WidgetTester tester) async { final String platform = defaultTargetPlatform.name.toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: testText.length ~/2, affinity: TextAffinity.upstream, ); TextSelection? selection; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( readOnly: true, controller: controller, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. const String clipboardContent = 'read-only'; await Clipboard.setData(const ClipboardData(text: clipboardContent)); // Paste await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyV, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect(selection, isNull, reason: 'on $platform'); expect(controller.text, equals(testText), reason: 'on $platform'); // Select All await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyA, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: testText.length, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); // Cut await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyX, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: testText.length, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); expect( (await Clipboard.getData(Clipboard.kTextPlain))!.text, equals(clipboardContent), reason: 'on $platform', ); // Copy await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyC, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: testText.length, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); expect( (await Clipboard.getData(Clipboard.kTextPlain))!.text, equals(testText), reason: 'on $platform', ); // Delete await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.delete, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: testText.length, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); // Backspace await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.backspace, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: testText.length, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); }, // On web, using keyboard for selection is handled by the browser. skip: kIsWeb, // [intended] variant: TargetPlatformVariant.all(), ); testWidgets('home/end keys', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); late TextSelection selection; late SelectionChangedCause cause; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; cause = newCause!; }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. // Move near the middle of the document. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); expect( selection, equals( const TextSelection.collapsed( offset: 23, ), ), reason: 'on $platform', ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all. case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.fuchsia: case TargetPlatform.macOS: expect( selection, equals( const TextSelection.collapsed( offset: 23, ), ), reason: 'on $platform', ); // These platforms go to the line start/end. case TargetPlatform.linux: case TargetPlatform.windows: expect( selection, equals( const TextSelection.collapsed( offset: 20, ), ), reason: 'on $platform', ); } expect(controller.text, equals(testText), reason: 'on $platform'); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all. case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.fuchsia: case TargetPlatform.macOS: expect( selection, equals( const TextSelection.collapsed( offset: 23, ), ), reason: 'on $platform', ); // These platforms go to the line start/end. case TargetPlatform.linux: case TargetPlatform.windows: expect( selection, equals( const TextSelection.collapsed( offset: 35, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); } expect(controller.text, equals(testText), reason: 'on $platform'); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); testWidgets('home keys and wordwraps', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); late TextSelection selection; late SelectionChangedCause cause; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; cause = newCause!; }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. // Move near the middle of the document. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all. case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.fuchsia: case TargetPlatform.macOS: expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); // These platforms go to the line start/end. case TargetPlatform.linux: case TargetPlatform.windows: expect( selection, equals( const TextSelection.collapsed( offset: 29, ), ), reason: 'on $platform', ); } expect(controller.text, equals(testText), reason: 'on $platform'); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all still. case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.fuchsia: case TargetPlatform.macOS: expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); // Linux does nothing at a wordwrap with subsequent presses. case TargetPlatform.linux: expect( selection, equals( const TextSelection.collapsed( offset: 29, ), ), reason: 'on $platform', ); // Windows jumps to the previous wordwrapped line. case TargetPlatform.windows: expect( selection, equals( const TextSelection.collapsed( offset: 0, ), ), reason: 'on $platform', ); } }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); testWidgets('end keys and wordwraps', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); late TextSelection selection; late SelectionChangedCause cause; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; cause = newCause!; }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. // Move near the middle of the document. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all. case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.fuchsia: case TargetPlatform.macOS: expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); // These platforms go to the line start/end. case TargetPlatform.linux: case TargetPlatform.windows: expect( selection, equals( const TextSelection.collapsed( offset: 58, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); } expect(controller.text, equals(testText), reason: 'on $platform'); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all still. case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.fuchsia: case TargetPlatform.macOS: expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); // Linux does nothing at a wordwrap with subsequent presses. case TargetPlatform.linux: expect( selection, equals( const TextSelection.collapsed( offset: 58, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Windows jumps to the next wordwrapped line. case TargetPlatform.windows: expect( selection, equals( const TextSelection.collapsed( offset: 84, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); } }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); testWidgets('shift + home/end keys', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); late TextSelection selection; late SelectionChangedCause cause; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; cause = newCause!; }, ), ), ), )); await tester.pump(); // Move near the middle of the document. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); expect( selection, equals( const TextSelection.collapsed( offset: 23, ), ), reason: 'on $platform', ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect(controller.text, equals(testText), reason: 'on $platform'); final TextSelection selectionAfterHome = selection; // Move back to position 23. controller.selection = const TextSelection.collapsed( offset: 23, ); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect(controller.text, equals(testText), reason: 'on $platform'); final TextSelection selectionAfterEnd = selection; switch (defaultTargetPlatform) { // These platforms don't handle shift + home/end at all. case TargetPlatform.android: case TargetPlatform.fuchsia: expect( selectionAfterHome, equals( const TextSelection( baseOffset: 23, extentOffset: 23, ), ), reason: 'on $platform', ); expect( selectionAfterEnd, equals( const TextSelection( baseOffset: 23, extentOffset: 23, ), ), reason: 'on $platform', ); // Linux extends to the line start/end. case TargetPlatform.linux: expect( selectionAfterHome, equals( const TextSelection( baseOffset: 23, extentOffset: 20, ), ), reason: 'on $platform', ); expect( selectionAfterEnd, equals( const TextSelection( baseOffset: 23, extentOffset: 35, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Windows expands to the line start/end. case TargetPlatform.windows: expect( selectionAfterHome, equals( const TextSelection( baseOffset: 23, extentOffset: 20, ), ), reason: 'on $platform', ); expect( selectionAfterEnd, equals( const TextSelection( baseOffset: 23, extentOffset: 35, ), ), reason: 'on $platform', ); // Mac and iOS go to the start/end of the document. case TargetPlatform.iOS: case TargetPlatform.macOS: expect( selectionAfterHome, equals( const TextSelection( baseOffset: 23, extentOffset: 0, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); expect( selectionAfterEnd, equals( const TextSelection( baseOffset: 23, extentOffset: 72, ), ), reason: 'on $platform', ); } }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); testWidgets('shift + home/end keys (Windows only)', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Move the selection away from the start so it can invert. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection.collapsed( offset: 4, )), ); // Press shift + end and extend the selection to the end of the line. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shift: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection( baseOffset: 4, extentOffset: 19, affinity: TextAffinity.upstream, )), ); // Press shift + home and the selection inverts and extends to the start, it // does not collapse and stop at the inversion. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], shift: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection( baseOffset: 4, extentOffset: 0, )), ); // Press shift + end again and the selection inverts and extends to the end, // again it does not stop at the inversion. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shift: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection( baseOffset: 4, extentOffset: 19, )), ); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows }) ); testWidgets('home/end keys scrolling (Mac only)', (WidgetTester tester) async { const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); expect(scrollable.controller!.offset, 0.0); // Scroll to the end of the document with the end key. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], targetPlatform: defaultTargetPlatform, ); final double maxScrollExtent = scrollable.controller!.position.maxScrollExtent; expect(scrollable.controller!.offset, maxScrollExtent); // Scroll back to the beginning of the document with the home key. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], targetPlatform: defaultTargetPlatform, ); expect(scrollable.controller!.offset, 0.0); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) ); testWidgets('shift + home keys and wordwraps', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); late TextSelection selection; late SelectionChangedCause cause; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; cause = newCause!; }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. // Move near the middle of the document. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], shift: true, targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with shift + home/end at all. case TargetPlatform.android: case TargetPlatform.fuchsia: expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); // Mac and iOS select to the start of the document. case TargetPlatform.iOS: case TargetPlatform.macOS: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 0, ), ), reason: 'on $platform', ); // These platforms select to the line start. case TargetPlatform.linux: case TargetPlatform.windows: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 29, ), ), reason: 'on $platform', ); } expect(controller.text, equals(testText), reason: 'on $platform'); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], shift: true, targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all still. case TargetPlatform.android: case TargetPlatform.fuchsia: expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); // Mac and iOS select to the start of the document. case TargetPlatform.iOS: case TargetPlatform.macOS: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 0, ), ), reason: 'on $platform', ); // Linux does nothing at a wordwrap with subsequent presses. case TargetPlatform.linux: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 29, ), ), reason: 'on $platform', ); // Windows jumps to the previous wordwrapped line. case TargetPlatform.windows: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 0, ), ), reason: 'on $platform', ); } }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); testWidgets('shift + end keys and wordwraps', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); late TextSelection selection; late SelectionChangedCause cause; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; cause = newCause!; }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. // Move near the middle of the document. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shift: true, targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all. case TargetPlatform.android: case TargetPlatform.fuchsia: expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); // Mac and iOS select to the end of the document. case TargetPlatform.iOS: case TargetPlatform.macOS: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 145, ), ), reason: 'on $platform', ); // These platforms select to the line end. case TargetPlatform.linux: case TargetPlatform.windows: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 58, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); } expect(controller.text, equals(testText), reason: 'on $platform'); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shift: true, targetPlatform: defaultTargetPlatform, ); switch (defaultTargetPlatform) { // These platforms don't move the selection with home/end at all still. case TargetPlatform.android: case TargetPlatform.fuchsia: expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), reason: 'on $platform', ); // Mac and iOS stay at the end of the document. case TargetPlatform.iOS: case TargetPlatform.macOS: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 145, ), ), reason: 'on $platform', ); // Linux does nothing at a wordwrap with subsequent presses. case TargetPlatform.linux: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 58, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Windows jumps to the previous wordwrapped line. case TargetPlatform.windows: expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 84, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); } }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); testWidgets('shift + home/end keys to document boundary (Mac only)', (WidgetTester tester) async { const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); late TextSelection selection; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { selection = newSelection; }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); expect(scrollable.controller!.offset, 0.0); // Move near the middle of the document. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); expect( selection, equals( const TextSelection.collapsed( offset: 32, ), ), ); // Expand to the start of the document with the home key. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect(scrollable.controller!.offset, 0.0); expect( selection, equals( const TextSelection( baseOffset: 32, extentOffset: 0, ), ), ); // Expand to the end of the document with the end key. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shift: true, targetPlatform: defaultTargetPlatform, ); final double maxScrollExtent = scrollable.controller!.position.maxScrollExtent; expect(scrollable.controller!.offset, maxScrollExtent); expect( selection, equals( const TextSelection( baseOffset: 0, extentOffset: 145, ), ), ); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) ); testWidgets('control + home/end keys (Windows only)', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection.collapsed( offset: testText.length, )), ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection.collapsed(offset: 0)), ); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows }) ); testWidgets('control + shift + home/end keys (Windows only)', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shortcutModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection( baseOffset: 0, extentOffset: testText.length, )), ); // Collapse the selection at the end. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection.collapsed( offset: testText.length, )), ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], shortcutModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); expect( controller.selection, equals(const TextSelection( baseOffset: testText.length, extentOffset: 0, )), ); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows }) ); testWidgets('pageup/pagedown keys on Apple platforms', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); const int lines = 2; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( minLines: lines, maxLines: lines, controller: controller, scrollController: scrollController, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.value.selection.isCollapsed, isTrue); expect(controller.value.selection.baseOffset, 0); expect(scrollController.position.pixels, 0.0); final double lineHeight = findRenderEditable(tester).preferredLineHeight; expect(scrollController.position.viewportDimension, lineHeight * lines); // Page Up does nothing at the top. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, ], targetPlatform: defaultTargetPlatform, ); expect(scrollController.position.pixels, 0.0); // Page Down scrolls proportionally to the height of the viewport. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageDown, ], targetPlatform: defaultTargetPlatform, ); expect(scrollController.position.pixels, lineHeight * lines * 0.8); // Another Page Down reaches the bottom. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageDown, ], targetPlatform: defaultTargetPlatform, ); expect(scrollController.position.pixels, lineHeight * lines); // Page Up now scrolls back up proportionally to the height of the viewport. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, ], targetPlatform: defaultTargetPlatform, ); expect(scrollController.position.pixels, lineHeight * lines - lineHeight * lines * 0.8); // Another Page Up reaches the top. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, ], targetPlatform: defaultTargetPlatform, ); expect(scrollController.position.pixels, 0.0); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('pageup/pagedown keys in a one line field on Apple platforms', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( minLines: 1, controller: controller, scrollController: scrollController, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.value.selection.isCollapsed, isTrue); expect(controller.value.selection.baseOffset, 0); expect(scrollController.position.pixels, 0.0); // Page Up scrolls to the end. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, ], targetPlatform: defaultTargetPlatform, ); expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); expect(controller.value.selection.isCollapsed, isTrue); expect(controller.value.selection.baseOffset, 0); // Return scroll to the start. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], targetPlatform: defaultTargetPlatform, ); expect(scrollController.position.pixels, 0.0); expect(controller.value.selection.isCollapsed, isTrue); expect(controller.value.selection.baseOffset, 0); // Page Down also scrolls to the end. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageDown, ], targetPlatform: defaultTargetPlatform, ); expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); expect(controller.value.selection.isCollapsed, isTrue); expect(controller.value.selection.baseOffset, 0); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); // Regression test for https://github.com/flutter/flutter/issues/31287 testWidgets('text selection handle visibility', (WidgetTester tester) async { // Text with two separate words to select. controller.text = 'XXXXX XXXXX'; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 100, child: EditableText( showSelectionHandles: true, controller: controller, focusNode: focusNode, style: Typography.material2018(platform: TargetPlatform.iOS).black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: cupertinoTextSelectionControls, keyboardType: TextInputType.text, ), ), ), )); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); bool expectedLeftVisibleBefore = false; bool expectedRightVisibleBefore = false; Future<void> verifyVisibility( HandlePositionInViewport leftPosition, bool expectedLeftVisible, HandlePositionInViewport rightPosition, bool expectedRightVisible, ) async { await tester.pump(); // Check the signal from RenderEditable about whether they're within the // viewport. expect(renderEditable.selectionStartInViewport.value, equals(expectedLeftVisible)); expect(renderEditable.selectionEndInViewport.value, equals(expectedRightVisible)); // Check that the animations are functional and going in the right // direction. final List<FadeTransition> transitions = find.byType(FadeTransition).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); final FadeTransition left = transitions[0]; final FadeTransition right = transitions[1]; if (expectedLeftVisibleBefore) { expect(left.opacity.value, equals(1.0)); } if (expectedRightVisibleBefore) { expect(right.opacity.value, equals(1.0)); } await tester.pump(SelectionOverlay.fadeDuration ~/ 2); if (expectedLeftVisible != expectedLeftVisibleBefore) { expect(left.opacity.value, equals(0.5)); } if (expectedRightVisible != expectedRightVisibleBefore) { expect(right.opacity.value, equals(0.5)); } await tester.pump(SelectionOverlay.fadeDuration ~/ 2); if (expectedLeftVisible) { expect(left.opacity.value, equals(1.0)); } if (expectedRightVisible) { expect(right.opacity.value, equals(1.0)); } expectedLeftVisibleBefore = expectedLeftVisible; expectedRightVisibleBefore = expectedRightVisible; // Check that the handles' positions are correct. final List<RenderBox> handles = List<RenderBox>.from( tester.renderObjectList<RenderBox>( find.descendant( of: find.byType(CompositedTransformFollower), matching: find.byType(Padding), ), ), ); final Size viewport = renderEditable.size; void testPosition(double pos, HandlePositionInViewport expected) { switch (expected) { case HandlePositionInViewport.leftEdge: expect( pos, inExclusiveRange( 0 - kMinInteractiveDimension, 0 + kMinInteractiveDimension, ), ); case HandlePositionInViewport.rightEdge: expect( pos, inExclusiveRange( viewport.width - kMinInteractiveDimension, viewport.width + kMinInteractiveDimension, ), ); case HandlePositionInViewport.within: expect( pos, inExclusiveRange( 0 - kMinInteractiveDimension, viewport.width + kMinInteractiveDimension, ), ); } } expect(state.selectionOverlay!.handlesAreVisible, isTrue); testPosition(handles[0].localToGlobal(Offset.zero).dx, leftPosition); testPosition(handles[1].localToGlobal(Offset.zero).dx, rightPosition); } // Select the first word. Both handles should be visible. await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pump(); await verifyVisibility(HandlePositionInViewport.leftEdge, true, HandlePositionInViewport.within, true); // Drag the text slightly so the first word is partially visible. Only the // right handle should be visible. scrollable.controller!.jumpTo(20.0); await verifyVisibility(HandlePositionInViewport.leftEdge, false, HandlePositionInViewport.within, true); // Drag the text all the way to the left so the first word is not visible at // all (and the second word is fully visible). Both handles should be // invisible now. scrollable.controller!.jumpTo(200.0); await verifyVisibility(HandlePositionInViewport.leftEdge, false, HandlePositionInViewport.leftEdge, false); // Tap to unselect. await tester.tap(find.byType(EditableText)); await tester.pump(); // Now that the second word has been dragged fully into view, select it. await tester.tapAt(const Offset(80, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pump(); await verifyVisibility(HandlePositionInViewport.within, true, HandlePositionInViewport.within, true); // Drag the text slightly to the right. Only the left handle should be // visible. scrollable.controller!.jumpTo(150); await verifyVisibility(HandlePositionInViewport.within, true, HandlePositionInViewport.rightEdge, false); // Drag the text all the way to the right, so the second word is not visible // at all. Again, both handles should be invisible. scrollable.controller!.jumpTo(0); await verifyVisibility(HandlePositionInViewport.rightEdge, false, HandlePositionInViewport.rightEdge, false); }, // On web, we don't show the Flutter toolbar and instead rely on the browser // toolbar. Until we change that, this test should remain skipped. skip: kIsWeb, // [intended] variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }) ); testWidgets("scrolling doesn't bounce", (WidgetTester tester) async { // 3 lines of text, where the last line overflows and requires scrolling. controller.text = 'XXXXX\nXXXXX\nXXXXX'; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 100, child: EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, ), ), ), )); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); expect(scrollable.controller!.position.viewportDimension, equals(28)); expect(scrollable.controller!.position.pixels, equals(0)); expect(renderEditable.maxScrollExtent, equals(14)); scrollable.controller!.jumpTo(20.0); await tester.pump(); expect(scrollable.controller!.position.pixels, equals(20)); state.bringIntoView(const TextPosition(offset: 0)); await tester.pump(); expect(scrollable.controller!.position.pixels, equals(0)); state.bringIntoView(const TextPosition(offset: 13)); await tester.pump(); expect(scrollable.controller!.position.pixels, equals(14)); expect(scrollable.controller!.position.pixels, equals(renderEditable.maxScrollExtent)); }); testWidgets('bringIntoView brings the caret into view when in a viewport', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/55547. controller.text = testText * 20; final ScrollController editableScrollController = ScrollController(); addTearDown(editableScrollController.dispose); final ScrollController outerController = ScrollController(); addTearDown(outerController.dispose); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 200, height: 200, child: SingleChildScrollView( controller: outerController, child: EditableText( maxLines: null, controller: controller, scrollController: editableScrollController, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ), ), )); expect(outerController.offset, 0); expect(editableScrollController.offset, 0); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.bringIntoView(TextPosition(offset: controller.text.length)); await tester.pumpAndSettle(); // The SingleChildScrollView is scrolled instead of the EditableText to // reveal the caret. expect(outerController.offset, outerController.position.maxScrollExtent); expect(editableScrollController.offset, 0); }); testWidgets('bringIntoView does nothing if the physics prohibits implicit scrolling', (WidgetTester tester) async { controller.text = testText * 20; final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); Future<void> buildWithPhysics({ ScrollPhysics? physics }) async { await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 200, height: 200, child: EditableText( maxLines: null, controller: controller, scrollController: scrollController, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, scrollPhysics: physics, ), ), ), )); } await buildWithPhysics(); expect(scrollController.offset, 0); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.bringIntoView(TextPosition(offset: controller.text.length)); await tester.pumpAndSettle(); // Scrolled to the maxScrollExtent to reveal to caret. expect(scrollController.offset, scrollController.position.maxScrollExtent); scrollController.jumpTo(0); await buildWithPhysics(physics: const NoImplicitScrollPhysics()); expect(scrollController.offset, 0); state.bringIntoView(TextPosition(offset: controller.text.length)); await tester.pumpAndSettle(); expect(scrollController.offset, 0); }); testWidgets('can change scroll controller', (WidgetTester tester) async { controller.text = 'A' * 1000; final _TestScrollController scrollController1 = _TestScrollController(); addTearDown(scrollController1.dispose); final _TestScrollController scrollController2 = _TestScrollController(); addTearDown(scrollController2.dispose); await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, scrollController: scrollController1, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.widget.scrollController, scrollController1); // Change scrollController to controller 2. await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, scrollController: scrollController2, ), ), ); expect(state.widget.scrollController, scrollController2); // Changing scrollController to null. await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ); expect(state.widget.scrollController, isNull); // Change scrollController to back controller 2. await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, scrollController: scrollController2, ), ), ); expect(state.widget.scrollController, scrollController2); }); testWidgets('getLocalRectForCaret does not throw when it sees an infinite point', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: SkipPainting( child: Transform( transform: Matrix4.zero(), child: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final Rect rect = state.renderEditable.getLocalRectForCaret(const TextPosition(offset: 0)); expect(rect.isFinite, true); expect(tester.takeException(), isNull); }); testWidgets('obscured multiline fields throw an exception', (WidgetTester tester) async { expect( () { EditableText( backgroundCursorColor: cursorColor, controller: controller, cursorColor: cursorColor, focusNode: focusNode, obscureText: true, style: textStyle, ); }, returnsNormally, ); expect( () { EditableText( backgroundCursorColor: cursorColor, controller: controller, cursorColor: cursorColor, focusNode: focusNode, maxLines: 2, obscureText: true, style: textStyle, ); }, throwsAssertionError, ); }); group('batch editing', () { Widget buildWidget() { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ), ), ); } testWidgets('batch editing works', (WidgetTester tester) async { await tester.pumpWidget(buildWidget()); // Connect. await tester.showKeyboard(find.byType(EditableText)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'remote value')); tester.testTextInput.log.clear(); state.beginBatchEdit(); controller.text = 'new change 1'; expect(state.currentTextEditingValue.text, 'new change 1'); expect(tester.testTextInput.log, isEmpty); // Nesting. state.beginBatchEdit(); controller.text = 'new change 2'; expect(state.currentTextEditingValue.text, 'new change 2'); expect(tester.testTextInput.log, isEmpty); // End the innermost batch edit. Not yet. state.endBatchEdit(); expect(tester.testTextInput.log, isEmpty); controller.text = 'new change 3'; expect(state.currentTextEditingValue.text, 'new change 3'); expect(tester.testTextInput.log, isEmpty); // Finish the outermost batch edit. state.endBatchEdit(); expect(tester.testTextInput.log, hasLength(1)); expect( tester.testTextInput.log, contains(matchesMethodCall('TextInput.setEditingState', args: containsPair('text', 'new change 3'))), ); }); testWidgets('batch edits need to be nested properly', (WidgetTester tester) async { await tester.pumpWidget(buildWidget()); // Connect. await tester.showKeyboard(find.byType(EditableText)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'remote value')); tester.testTextInput.log.clear(); String? errorString; try { state.endBatchEdit(); } catch (e) { errorString = e.toString(); } expect(errorString, contains('Unbalanced call to endBatchEdit')); }); testWidgets('catch unfinished batch edits on disposal', (WidgetTester tester) async { await tester.pumpWidget(buildWidget()); // Connect. await tester.showKeyboard(find.byType(EditableText)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'remote value')); tester.testTextInput.log.clear(); state.beginBatchEdit(); expect(tester.takeException(), isNull); await tester.pumpWidget(Container()); expect(tester.takeException(), isAssertionError); }); }); group('EditableText does not send editing values more than once', () { Widget boilerplate() { final EditableText editableText = EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, inputFormatters: <TextInputFormatter>[LengthLimitingTextInputFormatter(6)], onChanged: (String s) { controller.value = collapsedAtEnd('${controller.text} onChanged'); }, ); controller.addListener(() { if (!controller.text.endsWith('listener')) { controller.value = collapsedAtEnd('${controller.text} listener'); } }); return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: editableText, ), ); } testWidgets('input from text input plugin', (WidgetTester tester) async { controller.text = testText; await tester.pumpWidget(boilerplate()); // Connect. await tester.showKeyboard(find.byType(EditableText)); tester.testTextInput.log.clear(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(collapsedAtEnd('remoteremoteremote')); // Apply in order: length formatter -> listener -> onChanged -> listener. const String expectedText = 'remote listener onChanged listener'; expect(controller.text, expectedText); final List<TextEditingValue> updates = tester.testTextInput.log .where((MethodCall call) => call.method == 'TextInput.setEditingState') .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) .toList(growable: false); expect(updates, <TextEditingValue>[collapsedAtEnd(expectedText)]); tester.testTextInput.log.clear(); // If by coincidence the text input plugin sends the same value back, // do nothing. state.updateEditingValue(collapsedAtEnd(expectedText)); expect(controller.text, 'remote listener onChanged listener'); expect(tester.testTextInput.log, isEmpty); }); testWidgets('input from text selection menu', (WidgetTester tester) async { controller.text = testText; await tester.pumpWidget(boilerplate()); // Connect. await tester.showKeyboard(find.byType(EditableText)); tester.testTextInput.log.clear(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.userUpdateTextEditingValue( collapsedAtEnd('remoteremoteremote'), SelectionChangedCause.keyboard, ); final List<TextEditingValue> updates = tester.testTextInput.log .where((MethodCall call) => call.method == 'TextInput.setEditingState') .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) .toList(growable: false); const String expectedText = 'remote listener onChanged listener'; expect(updates, <TextEditingValue>[collapsedAtEnd(expectedText)]); tester.testTextInput.log.clear(); }); testWidgets('input from controller', (WidgetTester tester) async { controller.text = testText; await tester.pumpWidget(boilerplate()); // Connect. await tester.showKeyboard(find.byType(EditableText)); tester.testTextInput.log.clear(); controller.text = 'remoteremoteremote'; final List<TextEditingValue> updates = tester.testTextInput.log .where((MethodCall call) => call.method == 'TextInput.setEditingState') .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) .toList(growable: false); expect(updates, <TextEditingValue>[collapsedAtEnd('remoteremoteremote listener')]); }); testWidgets('input from changing controller', (WidgetTester tester) async { Widget build({ TextEditingController? textEditingController }) { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( showSelectionHandles: true, maxLines: 2, controller: textEditingController ?? controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, inputFormatters: <TextInputFormatter>[LengthLimitingTextInputFormatter(6)], ), ), ); } await tester.pumpWidget(build()); // Connect. await tester.showKeyboard(find.byType(EditableText)); tester.testTextInput.log.clear(); final TextEditingController controller1 = TextEditingController(text: 'new text'); addTearDown(controller1.dispose); await tester.pumpWidget(build(textEditingController: controller1)); List<TextEditingValue> updates = tester.testTextInput.log .where((MethodCall call) => call.method == 'TextInput.setEditingState') .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) .toList(growable: false); expect(updates, const <TextEditingValue>[TextEditingValue(text: 'new text')]); tester.testTextInput.log.clear(); final TextEditingController controller2 = TextEditingController(text: 'new new text'); addTearDown(controller2.dispose); await tester.pumpWidget(build(textEditingController: controller2)); updates = tester.testTextInput.log .where((MethodCall call) => call.method == 'TextInput.setEditingState') .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) .toList(growable: false); expect(updates, const <TextEditingValue>[TextEditingValue(text: 'new new text')]); }); }); testWidgets('input imm channel calls are ordered correctly', (WidgetTester tester) async { controller.text = 'flutter is the best!'; final EditableText et = EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 100, child: et, ), ), )); await tester.showKeyboard(find.byType(EditableText)); // TextInput.show should be after TextInput.setEditingState. // On Android setEditingState triggers an IME restart which may prevent // the keyboard from showing if the show keyboard request comes before the // restart. // See: https://github.com/flutter/flutter/issues/68571. final List<String> logOrder = <String>[ 'TextInput.setClient', 'TextInput.setEditableSizeAndTransform', 'TextInput.setMarkedTextRect', 'TextInput.setStyle', 'TextInput.setEditingState', 'TextInput.show', 'TextInput.requestAutofill', 'TextInput.setEditingState', 'TextInput.show', 'TextInput.setCaretRect', ]; expect( tester.testTextInput.log.map((MethodCall m) => m.method), logOrder, ); }); testWidgets( 'keyboard is requested after setEditingState after switching to a new text field', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/68571. final TextEditingController controller1 = TextEditingController(); addTearDown(controller1.dispose); final FocusNode focusNode1 = FocusNode(); addTearDown(focusNode1.dispose); final EditableText editableText1 = EditableText( showSelectionHandles: true, maxLines: 2, controller: controller1, focusNode: focusNode1, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ); final TextEditingController controller2 = TextEditingController(); addTearDown(controller2.dispose); final FocusNode focusNode2 = FocusNode(); addTearDown(focusNode2.dispose); final EditableText editableText2 = EditableText( showSelectionHandles: true, maxLines: 2, controller: controller2, focusNode: focusNode2, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ); await tester.pumpWidget(MaterialApp( home: Center( child: Column( children: <Widget>[editableText1, editableText2], ), ), )); await tester.tap(find.byWidget(editableText1)); await tester.pumpAndSettle(); tester.testTextInput.log.clear(); await tester.tap(find.byWidget(editableText2)); await tester.pumpAndSettle(); // Send TextInput.show after TextInput.setEditingState. Otherwise // some Android keyboards ignore the "show keyboard" request, as the // Android text input plugin restarts the input method when setEditingState // is sent by the framework. final List<String> logOrder = <String>[ 'TextInput.clearClient', 'TextInput.setClient', 'TextInput.setEditableSizeAndTransform', 'TextInput.setMarkedTextRect', 'TextInput.setStyle', 'TextInput.setEditingState', 'TextInput.show', 'TextInput.requestAutofill', 'TextInput.setCaretRect', ]; expect( tester.testTextInput.log.map((MethodCall m) => m.method), logOrder, ); }); testWidgets( 'Autofill does not request focus', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/91354 . final TextEditingController controller1 = TextEditingController(); addTearDown(controller1.dispose); final FocusNode focusNode1 = FocusNode(); addTearDown(focusNode1.dispose); final EditableText editableText1 = EditableText( showSelectionHandles: true, maxLines: 2, controller: controller1, focusNode: focusNode1, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ); final TextEditingController controller2 = TextEditingController(); addTearDown(controller2.dispose); final FocusNode focusNode2 = FocusNode(); addTearDown(focusNode2.dispose); final EditableText editableText2 = EditableText( showSelectionHandles: true, maxLines: 2, controller: controller2, focusNode: focusNode2, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ); await tester.pumpWidget(MaterialApp( home: Center( child: Column( children: <Widget>[editableText1, editableText2], ), ), )); // editableText1 has the focus. await tester.tap(find.byWidget(editableText1)); await tester.pumpAndSettle(); final EditableTextState state2 = tester.state<EditableTextState>(find.byWidget(editableText2)); // Update editableText2 when it's not focused. It should not request focus. state2.updateEditingValue( const TextEditingValue(text: 'password', selection: TextSelection.collapsed(offset: 8)), ); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); }); testWidgets('setEditingState is not called when text changes', (WidgetTester tester) async { // We shouldn't get a message here because this change is owned by the platform side. controller.text = 'flutter is the best!'; final EditableText et = EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 100, child: et, ), ), )); await tester.enterText(find.byType(EditableText), '...'); final List<String> logOrder = <String>[ 'TextInput.setClient', 'TextInput.setEditableSizeAndTransform', 'TextInput.setMarkedTextRect', 'TextInput.setStyle', 'TextInput.setEditingState', 'TextInput.show', 'TextInput.requestAutofill', 'TextInput.setEditingState', 'TextInput.show', 'TextInput.setCaretRect', 'TextInput.show', ]; expect(tester.testTextInput.log.length, logOrder.length); int index = 0; for (final MethodCall m in tester.testTextInput.log) { expect(m.method, logOrder[index]); index++; } expect(tester.testTextInput.editingState!['text'], 'flutter is the best!'); }); testWidgets('setEditingState is called when text changes on controller', (WidgetTester tester) async { // We should get a message here because this change is owned by the framework side. controller.text = 'flutter is the best!'; final EditableText et = EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 100, child: et, ), ), )); await tester.showKeyboard(find.byType(EditableText)); controller.value = collapsedAtEnd('${controller.text}...'); await tester.idle(); final List<String> logOrder = <String>[ 'TextInput.setClient', 'TextInput.setEditableSizeAndTransform', 'TextInput.setMarkedTextRect', 'TextInput.setStyle', 'TextInput.setEditingState', 'TextInput.show', 'TextInput.requestAutofill', 'TextInput.setEditingState', 'TextInput.show', 'TextInput.setCaretRect', 'TextInput.setEditingState', ]; expect( tester.testTextInput.log.map((MethodCall m) => m.method), logOrder, ); expect(tester.testTextInput.editingState!['text'], 'flutter is the best!...'); }); testWidgets('Synchronous test of local and remote editing values', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/65059 final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); final TextInputFormatter formatter = TextInputFormatter.withFunction((TextEditingValue oldValue, TextEditingValue newValue) { if (newValue.text == 'I will be modified by the formatter.') { newValue = collapsedAtEnd('Flutter is the best!'); } return newValue; }); late StateSetter setState; Widget builder() { return StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, inputFormatters: <TextInputFormatter>[ formatter, ], onChanged: (String value) { }, ), ), ), ), ), ); }, ); } await tester.pumpWidget(builder()); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.pump(); log.clear(); final EditableTextState state = tester.firstState(find.byType(EditableText)); // setEditingState is not called when only the remote changes state.updateEditingValue(TextEditingValue( text: 'a', selection: controller.selection, )); expect(log.length, 0); // setEditingState is called when remote value modified by the formatter. state.updateEditingValue(TextEditingValue( text: 'I will be modified by the formatter.', selection: controller.selection, )); expect(log.length, 1); MethodCall methodCall = log[0]; expect( methodCall, isMethodCall('TextInput.setEditingState', arguments: <String, dynamic>{ 'text': 'Flutter is the best!', 'selectionBase': 20, 'selectionExtent': 20, 'selectionAffinity': 'TextAffinity.downstream', 'selectionIsDirectional': false, 'composingBase': -1, 'composingExtent': -1, }), ); log.clear(); // setEditingState is called when the [controller.value] is modified by local. String text = 'I love flutter!'; setState(() { controller.value = collapsedAtEnd(text); }); expect(log.length, 1); methodCall = log[0]; expect( methodCall, isMethodCall('TextInput.setEditingState', arguments: <String, dynamic>{ 'text': 'I love flutter!', 'selectionBase': text.length, 'selectionExtent': text.length, 'selectionAffinity': 'TextAffinity.downstream', 'selectionIsDirectional': false, 'composingBase': -1, 'composingExtent': -1, }), ); log.clear(); // Currently `_receivedRemoteTextEditingValue` equals 'I will be modified by the formatter.', // setEditingState will be called when set the [controller.value] to `_receivedRemoteTextEditingValue` by local. text = 'I will be modified by the formatter.'; setState(() { controller.value = collapsedAtEnd(text); }); expect(log.length, 1); methodCall = log[0]; expect( methodCall, isMethodCall('TextInput.setEditingState', arguments: <String, dynamic>{ 'text': 'I will be modified by the formatter.', 'selectionBase': text.length, 'selectionExtent': text.length, 'selectionAffinity': 'TextAffinity.downstream', 'selectionIsDirectional': false, 'composingBase': -1, 'composingExtent': -1, }), ); }); testWidgets('Send text input state to engine when the input formatter rejects user input', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/67828 final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); final TextInputFormatter formatter = TextInputFormatter.withFunction((TextEditingValue oldValue, TextEditingValue newValue) { return collapsedAtEnd('Flutter is the best!'); }); Widget builder() { return StatefulBuilder( builder: (BuildContext context, StateSetter setter) { return MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, inputFormatters: <TextInputFormatter>[ formatter, ], onChanged: (String value) { }, ), ), ), ), ), ); }, ); } await tester.pumpWidget(builder()); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.pump(); log.clear(); final EditableTextState state = tester.firstState(find.byType(EditableText)); // setEditingState is called when remote value modified by the formatter. state.updateEditingValue(collapsedAtEnd('I will be modified by the formatter.')); expect(log.length, 2); expect(log, contains(matchesMethodCall( 'TextInput.setEditingState', args: allOf( containsPair('text', 'Flutter is the best!'), ), ))); log.clear(); state.updateEditingValue(collapsedAtEnd('I will be modified by the formatter.')); expect(log.length, 2); expect(log, contains(matchesMethodCall( 'TextInput.setEditingState', args: allOf( containsPair('text', 'Flutter is the best!'), ), ))); }); testWidgets('Repeatedly receiving [TextEditingValue] will not trigger a keyboard request', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/66036 final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); Widget builder() { return StatefulBuilder( builder: (BuildContext context, StateSetter setter) { return MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, onChanged: (String value) { }, ), ), ), ), ), ); }, ); } await tester.pumpWidget(builder()); await tester.tap(find.byType(EditableText)); await tester.pump(); // The keyboard is shown after tap the EditableText. expect(focusNode.hasFocus, true); log.clear(); final EditableTextState state = tester.firstState(find.byType(EditableText)); state.updateEditingValue(TextEditingValue( text: 'a', selection: controller.selection, )); await tester.pump(); // Nothing called when only the remote changes. expect(log.length, 0); // Hide the keyboard. focusNode.unfocus(); await tester.pump(); expect(log.length, 2); MethodCall methodCall = log[0]; // Close the InputConnection. expect(methodCall, isMethodCall('TextInput.clearClient', arguments: null)); methodCall = log[1]; expect(methodCall, isMethodCall('TextInput.hide', arguments: null)); // The keyboard loses focus. expect(focusNode.hasFocus, false); log.clear(); // Send repeat value from the engine. state.updateEditingValue(TextEditingValue( text: 'a', selection: controller.selection, )); await tester.pump(); // Nothing called when only the remote changes. expect(log.length, 0); // The keyboard is not be requested after a repeat value from the engine. expect(focusNode.hasFocus, false); }); group('TextEditingController', () { testWidgets('TextEditingController.text set to empty string clears field', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, onChanged: (String value) { }, ), ), ), ), ), ), ); controller.text = '...'; await tester.pump(); expect(find.text('...'), findsOneWidget); controller.text = ''; await tester.pump(); expect(find.text('...'), findsNothing); }); testWidgets('TextEditingController.clear() behavior test', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/66316 final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); Widget builder() { return StatefulBuilder( builder: (BuildContext context, StateSetter setter) { return MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: Material( child: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, onChanged: (String value) { }, ), ), ), ), ), ); }, ); } await tester.pumpWidget(builder()); await tester.tap(find.byType(EditableText)); await tester.pump(); // The keyboard is shown after tap the EditableText. expect(focusNode.hasFocus, true); log.clear(); final EditableTextState state = tester.firstState(find.byType(EditableText)); state.updateEditingValue(TextEditingValue( text: 'a', selection: controller.selection, )); await tester.pump(); // Nothing called when only the remote changes. expect(log, isEmpty); controller.clear(); expect(log.length, 1); expect( log[0], isMethodCall('TextInput.setEditingState', arguments: <String, dynamic>{ 'text': '', 'selectionBase': 0, 'selectionExtent': 0, 'selectionAffinity': 'TextAffinity.downstream', 'selectionIsDirectional': false, 'composingBase': -1, 'composingExtent': -1, }), ); }); testWidgets('TextEditingController.buildTextSpan receives build context', (WidgetTester tester) async { final _AccentColorTextEditingController controller = _AccentColorTextEditingController('a'); addTearDown(controller.dispose); const Color color = Color.fromARGB(255, 1, 2, 3); final ThemeData lightTheme = ThemeData.light(); await tester.pumpWidget(MaterialApp( theme: lightTheme.copyWith( colorScheme: lightTheme.colorScheme.copyWith(secondary: color), ), home: EditableText( controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), )); final RenderEditable renderEditable = findRenderEditable(tester); final TextSpan textSpan = renderEditable.text! as TextSpan; expect(textSpan.style!.color, color); }); testWidgets('controller listener changes value', (WidgetTester tester) async { const double maxValue = 5.5555; controller.addListener(() { final double value = double.tryParse(controller.text.trim()) ?? .0; if (value > maxValue) { controller.text = maxValue.toString(); controller.selection = TextSelection.fromPosition( TextPosition(offset: maxValue.toString().length)); } }); await tester.pumpWidget(MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), )); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1))); await tester.pump(); state.updateEditingValue(const TextEditingValue(text: '12', selection: TextSelection.collapsed(offset: 2))); await tester.pump(); expect(controller.text, '5.5555'); expect(controller.selection.baseOffset, 6); expect(controller.selection.extentOffset, 6); }); }); testWidgets('autofocus:true on first frame does not throw', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), )); await tester.pumpAndSettle(); // Wait for autofocus to take effect. final dynamic exception = tester.takeException(); expect(exception, isNull); }); testWidgets('updateEditingValue filters multiple calls from formatter', (WidgetTester tester) async { final MockTextFormatter formatter = MockTextFormatter(); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, inputFormatters: <TextInputFormatter>[formatter], ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = ''; await tester.idle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('')); expect(state.wantKeepAlive, true); state.updateEditingValue(TextEditingValue.empty); state.updateEditingValue(const TextEditingValue(text: 'a')); state.updateEditingValue(const TextEditingValue(text: 'aa')); state.updateEditingValue(const TextEditingValue(text: 'aaa')); state.updateEditingValue(const TextEditingValue(text: 'aa')); state.updateEditingValue(const TextEditingValue(text: 'aaa')); state.updateEditingValue(const TextEditingValue(text: 'aaaa')); state.updateEditingValue(const TextEditingValue(text: 'aa')); state.updateEditingValue(const TextEditingValue(text: 'aaaaaaa')); state.updateEditingValue(const TextEditingValue(text: 'aa')); state.updateEditingValue(const TextEditingValue(text: 'aaaaaaaaa')); state.updateEditingValue(const TextEditingValue(text: 'aaaaaaaaa')); // Skipped const List<String> referenceLog = <String>[ '[1]: , a', '[1]: normal aa', '[2]: a, aa', '[2]: normal aaaa', '[3]: aa, aaa', '[3]: normal aaaaaa', '[4]: aaa, aa', '[4]: deleting aa', '[5]: aa, aaa', '[5]: normal aaaaaaaaaa', '[6]: aaa, aaaa', '[6]: normal aaaaaaaaaaaa', '[7]: aaaa, aa', '[7]: deleting aaaaa', '[8]: aa, aaaaaaa', '[8]: normal aaaaaaaaaaaaaaaa', '[9]: aaaaaaa, aa', '[9]: deleting aaaaaaa', '[10]: aa, aaaaaaaaa', '[10]: normal aaaaaaaaaaaaaaaaaaaa', ]; expect(formatter.log, referenceLog); }); testWidgets('formatter logic handles repeat filtering', (WidgetTester tester) async { final MockTextFormatter formatter = MockTextFormatter(); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, inputFormatters: <TextInputFormatter>[formatter], ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = ''; await tester.idle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('')); expect(state.wantKeepAlive, true); // We no longer perform full repeat filtering in framework, it is now left // to the engine to prevent repeat calls from being sent in the first place. // Engine preventing repeats is far more reliable and avoids many of the ambiguous // filtering we performed before. expect(formatter.formatCallCount, 0); state.updateEditingValue(const TextEditingValue(text: '01')); expect(formatter.formatCallCount, 1); state.updateEditingValue(const TextEditingValue(text: '012')); expect(formatter.formatCallCount, 2); state.updateEditingValue(const TextEditingValue(text: '0123')); // Text change causes reformat expect(formatter.formatCallCount, 3); state.updateEditingValue(const TextEditingValue(text: '0123')); // No text change, does not format expect(formatter.formatCallCount, 3); state.updateEditingValue(const TextEditingValue(text: '0123')); // No text change, does not format expect(formatter.formatCallCount, 3); state.updateEditingValue(const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2))); // Selection change does not reformat expect(formatter.formatCallCount, 3); state.updateEditingValue(const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2))); // No text change, does not format expect(formatter.formatCallCount, 3); state.updateEditingValue(const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2))); // No text change, does not format expect(formatter.formatCallCount, 3); // Composing changes should not trigger reformat, as it could cause infinite loops on some IMEs. state.updateEditingValue(const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2), composing: TextRange(start: 1, end: 2))); expect(formatter.formatCallCount, 3); expect(formatter.lastOldValue.composing, TextRange.empty); expect(formatter.lastNewValue.composing, TextRange.empty); // The new composing was registered in formatter. // Clearing composing region should trigger reformat. state.updateEditingValue(const TextEditingValue(text: '01234', selection: TextSelection.collapsed(offset: 2))); // Formats, with oldValue containing composing region. expect(formatter.formatCallCount, 4); expect(formatter.lastOldValue.composing, const TextRange(start: 1, end: 2)); expect(formatter.lastNewValue.composing, TextRange.empty); const List<String> referenceLog = <String>[ '[1]: , 01', '[1]: normal aa', '[2]: 01, 012', '[2]: normal aaaa', '[3]: 012, 0123', '[3]: normal aaaaaa', '[4]: 0123, 01234', '[4]: normal aaaaaaaa', ]; expect(formatter.log, referenceLog); }); // Regression test for https://github.com/flutter/flutter/issues/53612 testWidgets('formatter logic handles initial repeat edge case', (WidgetTester tester) async { final MockTextFormatter formatter = MockTextFormatter(); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, inputFormatters: <TextInputFormatter>[formatter], ), ), ), ), ); await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('test')); expect(state.wantKeepAlive, true); expect(formatter.formatCallCount, 0); state.updateEditingValue(collapsedAtEnd('test')); state.updateEditingValue(collapsedAtEnd('test').copyWith(composing: const TextRange(start: 1, end: 2))); // Pass to formatter once to check the values. state.updateEditingValue(collapsedAtEnd('test')); expect(formatter.lastOldValue.composing, const TextRange(start: 1, end: 2)); expect(formatter.lastOldValue.text, 'test'); }); testWidgets('EditableText changes mouse cursor when hovered', (WidgetTester tester) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, mouseCursor: SystemMouseCursors.click, ), ), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: tester.getCenter(find.byType(EditableText))); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); // Test default cursor await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: EditableText( controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); }); testWidgets('Can access characters on editing string', (WidgetTester tester) async { late int charactersLength; final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, onChanged: (String value) { charactersLength = value.characters.length; }, ), ); await tester.pumpWidget(widget); // Enter an extended grapheme cluster whose string length is different than // its characters length. await tester.enterText(find.byType(EditableText), '👨‍👩‍👦'); await tester.pump(); expect(charactersLength, 1); }); testWidgets('EditableText can set and update clipBehavior', (WidgetTester tester) async { await tester.pumpWidget(MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), )); final RenderEditable renderObject = tester.allRenderObjects.whereType<RenderEditable>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); await tester.pumpWidget(MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, clipBehavior: Clip.antiAlias, ), ), ), )); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); }); testWidgets('EditableText inherits DefaultTextHeightBehavior', (WidgetTester tester) async { const TextHeightBehavior customTextHeightBehavior = TextHeightBehavior( applyHeightToFirstAscent: false, ); await tester.pumpWidget(MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: DefaultTextHeightBehavior( textHeightBehavior: customTextHeightBehavior, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ), )); final RenderEditable renderObject = tester.allRenderObjects.whereType<RenderEditable>().first; expect(renderObject.textHeightBehavior, equals(customTextHeightBehavior)); }); testWidgets('EditableText defaultTextHeightBehavior is used over inherited widget', (WidgetTester tester) async { const TextHeightBehavior inheritedTextHeightBehavior = TextHeightBehavior( applyHeightToFirstAscent: false, ); const TextHeightBehavior customTextHeightBehavior = TextHeightBehavior( applyHeightToLastDescent: false, applyHeightToFirstAscent: false, ); await tester.pumpWidget(MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, child: DefaultTextHeightBehavior( textHeightBehavior: inheritedTextHeightBehavior, child: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, textHeightBehavior: customTextHeightBehavior, ), ), ), ), )); final RenderEditable renderObject = tester.allRenderObjects.whereType<RenderEditable>().first; expect(renderObject.textHeightBehavior, isNot(equals(inheritedTextHeightBehavior))); expect(renderObject.textHeightBehavior, equals(customTextHeightBehavior)); }); test('Asserts if composing text is not valid', () async { void expectToAssert(TextEditingValue value, bool shouldAssert) { dynamic initException; dynamic updateException; TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); try { controller = TextEditingController.fromValue(value); } catch (e) { initException = e; } controller = TextEditingController(); addTearDown(controller.dispose); try { controller.value = value; } catch (e) { updateException = e; } expect(initException?.toString(), shouldAssert ? contains('composing range'): isNull); expect(updateException?.toString(), shouldAssert ? contains('composing range'): isNull); } expectToAssert(TextEditingValue.empty, false); expectToAssert(const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 0)), true); expectToAssert(const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 9)), true); expectToAssert(const TextEditingValue(text: 'test', composing: TextRange(start: -1, end: 9)), false); }); testWidgets('Preserves composing range if cursor moves within that range', (WidgetTester tester) async { final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ); await tester.pumpWidget(widget); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', composing: TextRange(start: 4, end: 12), )); controller.selection = const TextSelection.collapsed(offset: 5); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); }); testWidgets('Clears composing range if cursor moves outside that range', (WidgetTester tester) async { final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ); await tester.pumpWidget(widget); // Positioning cursor before the composing range should clear the composing range. final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', selection: TextSelection.collapsed(offset: 4), composing: TextRange(start: 4, end: 12), )); controller.selection = const TextSelection.collapsed(offset: 2); expect(state.currentTextEditingValue.composing, TextRange.empty); // Reset the composing range. state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', selection: TextSelection.collapsed(offset: 4), composing: TextRange(start: 4, end: 12), )); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); // Positioning cursor after the composing range should clear the composing range. state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', selection: TextSelection.collapsed(offset: 4), composing: TextRange(start: 4, end: 12), )); controller.selection = const TextSelection.collapsed(offset: 14); expect(state.currentTextEditingValue.composing, TextRange.empty); }); testWidgets('Clears composing range if cursor moves outside that range - case two', (WidgetTester tester) async { final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ); await tester.pumpWidget(widget); // Setting a selection before the composing range clears the composing range. final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', selection: TextSelection.collapsed(offset: 4), composing: TextRange(start: 4, end: 12), )); controller.selection = const TextSelection(baseOffset: 1, extentOffset: 2); expect(state.currentTextEditingValue.composing, TextRange.empty); // Reset the composing range. state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', selection: TextSelection.collapsed(offset: 4), composing: TextRange(start: 4, end: 12), )); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); // Setting a selection within the composing range doesn't clear the composing range. state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', selection: TextSelection.collapsed(offset: 4), composing: TextRange(start: 4, end: 12), )); controller.selection = const TextSelection(baseOffset: 5, extentOffset: 7); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); expect(state.currentTextEditingValue.selection, const TextSelection(baseOffset: 5, extentOffset: 7)); // Reset the composing range. state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', selection: TextSelection.collapsed(offset: 4), composing: TextRange(start: 4, end: 12), )); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); // Setting a selection after the composing range clears the composing range. state.updateEditingValue(const TextEditingValue( text: 'foo composing bar', selection: TextSelection.collapsed(offset: 4), composing: TextRange(start: 4, end: 12), )); controller.selection = const TextSelection(baseOffset: 13, extentOffset: 15); expect(state.currentTextEditingValue.composing, TextRange.empty); }); group('Length formatter', () { const int maxLength = 5; Future<void> setupWidget( WidgetTester tester, LengthLimitingTextInputFormatter formatter, ) async { final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, inputFormatters: <TextInputFormatter>[formatter], style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ); await tester.pumpWidget(widget); await tester.pumpAndSettle(); } // Regression test for https://github.com/flutter/flutter/issues/65374. testWidgets('will not cause crash while the TextEditingValue is composing', (WidgetTester tester) async { await setupWidget( tester, LengthLimitingTextInputFormatter( maxLength, maxLengthEnforcement: MaxLengthEnforcement.truncateAfterCompositionEnds, ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'abcde')); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 2, end: 4))); expect(state.currentTextEditingValue.composing, const TextRange(start: 2, end: 4)); // Formatter will not update format while the editing value is composing. state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 2, end: 5))); expect(state.currentTextEditingValue.text, 'abcdef'); expect(state.currentTextEditingValue.composing, const TextRange(start: 2, end: 5)); // After composing ends, formatter will update. state.updateEditingValue(const TextEditingValue(text: 'abcdef')); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); testWidgets('handles composing text correctly, continued', (WidgetTester tester) async { await setupWidget( tester, LengthLimitingTextInputFormatter( maxLength, maxLengthEnforcement: MaxLengthEnforcement.truncateAfterCompositionEnds, ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Initially we're at maxLength with no composing text. controller.text = 'abcde' ; assert(state.currentTextEditingValue == const TextEditingValue(text: 'abcde')); // Should be able to change the editing value if the new value is still shorter // than maxLength. state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 2, end: 4))); expect(state.currentTextEditingValue.composing, const TextRange(start: 2, end: 4)); // Reset. controller.text = 'abcde' ; assert(state.currentTextEditingValue == const TextEditingValue(text: 'abcde')); // The text should not change when trying to insert when the text is already // at maxLength. state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 5, end: 6))); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); // Regression test for https://github.com/flutter/flutter/issues/68086. testWidgets('enforced composing truncated', (WidgetTester tester) async { await setupWidget( tester, LengthLimitingTextInputFormatter( maxLength, maxLengthEnforcement: MaxLengthEnforcement.enforced, ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Initially we're at maxLength with no composing text. state.updateEditingValue(const TextEditingValue(text: 'abcde')); expect(state.currentTextEditingValue.composing, TextRange.empty); // When it's not longer than `maxLength`, it can still start composing. state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); // `newValue` will be truncated if `composingMaxLengthEnforced`. state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); // Reset the value. state.updateEditingValue(const TextEditingValue(text: 'abcde')); expect(state.currentTextEditingValue.composing, TextRange.empty); // Change the value in order to take effects on web test. state.updateEditingValue(const TextEditingValue(text: '你好啊朋友')); expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing with a longer value, it should be the same state. state.updateEditingValue(const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.composing, TextRange.empty); }); // Regression test for https://github.com/flutter/flutter/issues/68086. testWidgets('default truncate behaviors with different platforms', (WidgetTester tester) async { await setupWidget(tester, LengthLimitingTextInputFormatter(maxLength)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Initially we're at maxLength with no composing text. state.updateEditingValue(const TextEditingValue(text: '你好啊朋友')); expect(state.currentTextEditingValue.composing, TextRange.empty); // When it's not longer than `maxLength`, it can still start composing. state.updateEditingValue(const TextEditingValue(text: '你好啊朋友', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6))); if (kIsWeb || defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.linux || defaultTargetPlatform == TargetPlatform.fuchsia ) { // `newValue` will not be truncated on couple platforms. expect(state.currentTextEditingValue.text, '你好啊朋友们'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 6)); } else { // `newValue` on other platforms will be truncated. expect(state.currentTextEditingValue.text, '你好啊朋友'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); } // Reset the value. state.updateEditingValue(const TextEditingValue(text: '你好啊朋友')); expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing with a longer value, it should be the same state. state.updateEditingValue(const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.text, '你好啊朋友'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); // Regression test for https://github.com/flutter/flutter/issues/68086. testWidgets("composing range removed if it's overflowed the truncated value's length", (WidgetTester tester) async { await setupWidget( tester, LengthLimitingTextInputFormatter( maxLength, maxLengthEnforcement: MaxLengthEnforcement.enforced, ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Initially we're not at maxLength with no composing text. state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing. state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); // Reset the value. state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing with a range already overflowed the truncated length. state.updateEditingValue(const TextEditingValue(text: 'abcdefgh', composing: TextRange(start: 5, end: 7))); expect(state.currentTextEditingValue.composing, TextRange.empty); }); // Regression test for https://github.com/flutter/flutter/issues/68086. testWidgets('composing range removed with different platforms', (WidgetTester tester) async { await setupWidget(tester, LengthLimitingTextInputFormatter(maxLength)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Initially we're not at maxLength with no composing text. state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing. state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); // Reset the value. state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing with a range already overflowed the truncated length. state.updateEditingValue(const TextEditingValue(text: 'abcdefgh', composing: TextRange(start: 5, end: 7))); if (kIsWeb || defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.linux || defaultTargetPlatform == TargetPlatform.fuchsia ) { expect(state.currentTextEditingValue.composing, const TextRange(start: 5, end: 7)); } else { expect(state.currentTextEditingValue.composing, TextRange.empty); } }); testWidgets("composing range handled correctly when it's overflowed", (WidgetTester tester) async { const String string = '👨‍👩‍👦0123456'; await setupWidget(tester, LengthLimitingTextInputFormatter(maxLength)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Initially we're not at maxLength with no composing text. state.updateEditingValue(const TextEditingValue(text: string)); expect(state.currentTextEditingValue.composing, TextRange.empty); // Clearing composing range if collapsed. state.updateEditingValue(const TextEditingValue(text: string, composing: TextRange(start: 10, end: 10))); expect(state.currentTextEditingValue.composing, TextRange.empty); // Clearing composing range if overflowed. state.updateEditingValue(const TextEditingValue(text: string, composing: TextRange(start: 10, end: 11))); expect(state.currentTextEditingValue.composing, TextRange.empty); }); // Regression test for https://github.com/flutter/flutter/issues/68086. testWidgets('typing in the middle with different platforms.', (WidgetTester tester) async { await setupWidget(tester, LengthLimitingTextInputFormatter(maxLength)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Initially we're not at maxLength with no composing text. state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.composing, TextRange.empty); // Start typing in the middle. state.updateEditingValue(const TextEditingValue(text: 'abDEc', composing: TextRange(start: 3, end: 4))); expect(state.currentTextEditingValue.text, 'abDEc'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 4)); // Keep typing when the value has exceed the limitation. state.updateEditingValue(const TextEditingValue(text: 'abDEFc', composing: TextRange(start: 3, end: 5))); if (kIsWeb || defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.linux || defaultTargetPlatform == TargetPlatform.fuchsia ) { expect(state.currentTextEditingValue.text, 'abDEFc'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); } else { expect(state.currentTextEditingValue.text, 'abDEc'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 4)); } // Reset the value according to the limit. state.updateEditingValue(const TextEditingValue(text: 'abDEc')); expect(state.currentTextEditingValue.text, 'abDEc'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: 'abDEFc', composing: TextRange(start: 4, end: 5))); expect(state.currentTextEditingValue.composing, TextRange.empty); }); }); group('callback errors', () { const String errorText = 'Test EditableText callback error'; testWidgets('onSelectionChanged can throw errors', (WidgetTester tester) async { controller.text = 'flutter is the best!'; await tester.pumpWidget(MaterialApp( home: EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, selectionControls: materialTextSelectionControls, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { throw FlutterError(errorText); }, ), )); // Interact with the field to establish the input connection. await tester.tap(find.byType(EditableText)); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), contains(errorText)); }); testWidgets('onChanged can throw errors', (WidgetTester tester) async { controller.text = 'flutter is the best!'; await tester.pumpWidget(MaterialApp( home: EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, onChanged: (String text) { throw FlutterError(errorText); }, ), )); // Modify the text and expect an error from onChanged. await tester.enterText(find.byType(EditableText), '...'); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), contains(errorText)); }); testWidgets('onEditingComplete can throw errors', (WidgetTester tester) async { controller.text = 'flutter is the best!'; await tester.pumpWidget(MaterialApp( home: EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, onEditingComplete: () { throw FlutterError(errorText); }, ), )); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); // Submit and expect an error from onEditingComplete. await tester.testTextInput.receiveAction(TextInputAction.done); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), contains(errorText)); }); testWidgets('onSubmitted can throw errors', (WidgetTester tester) async { controller.text = 'flutter is the best!'; await tester.pumpWidget(MaterialApp( home: EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, onSubmitted: (String text) { throw FlutterError(errorText); }, ), )); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); // Submit and expect an error from onSubmitted. await tester.testTextInput.receiveAction(TextInputAction.done); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), contains(errorText)); }); testWidgets('input formatters can throw errors', (WidgetTester tester) async { final TextInputFormatter badFormatter = TextInputFormatter.withFunction( (TextEditingValue oldValue, TextEditingValue newValue) => throw FlutterError(errorText), ); controller.text = 'flutter is the best!'; await tester.pumpWidget(MaterialApp( home: EditableText( showSelectionHandles: true, maxLines: 2, controller: controller, inputFormatters: <TextInputFormatter>[badFormatter], focusNode: focusNode, cursorColor: Colors.red, backgroundCursorColor: Colors.blue, style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), keyboardType: TextInputType.text, ), )); // Interact with the field to establish the input connection. await tester.tap(find.byType(EditableText)); await tester.pump(); await tester.enterText(find.byType(EditableText), 'text'); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), contains(errorText)); expect(controller.text, 'text'); }); }); // Regression test for https://github.com/flutter/flutter/issues/72400. testWidgets("delete doesn't cause crash when selection is -1,-1", (WidgetTester tester) async { final UnsettableController unsettableController = UnsettableController(); addTearDown(unsettableController.dispose); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: EditableText( autofocus: true, controller: unsettableController, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ); await tester.pump(); // Wait for the autofocus to take effect. // Delete await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.delete, ], targetPlatform: TargetPlatform.android, ); expect(tester.takeException(), null); }); testWidgets('can change behavior by overriding text editing shortcuts', (WidgetTester tester) async { const Map<SingleActivator, Intent> testShortcuts = <SingleActivator, Intent>{ SingleActivator(LogicalKeyboardKey.arrowLeft): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), SingleActivator(LogicalKeyboardKey.keyX, control: true): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), SingleActivator(LogicalKeyboardKey.keyC, control: true): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), SingleActivator(LogicalKeyboardKey.keyV, control: true): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), SingleActivator(LogicalKeyboardKey.keyA, control: true): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), }; controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: Shortcuts( shortcuts: testShortcuts, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. // The right arrow key moves to the right as usual. await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 1); // And the testShortcuts also moves to the right due to the Shortcuts override. for (final SingleActivator singleActivator in testShortcuts.keys) { controller.selection = const TextSelection.collapsed(offset: 0); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[singleActivator.trigger], shortcutModifier: singleActivator.control, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 1); } // On web, using keyboard for selection is handled by the browser. }, skip: kIsWeb); // [intended] testWidgets('navigating by word', (WidgetTester tester) async { controller.text = 'word word word'; // word wo|rd| word controller.selection = const TextSelection( baseOffset: 7, extentOffset: 9, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 9); await sendKeys( tester, <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); // word wo|rd word| expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 14); await sendKeys( tester, <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); // word wo|rd |word expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 10); await sendKeys( tester, <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); if (defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS) { // word wo|rd word expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 7); await sendKeys( tester, <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); } // word |wo|rd word expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 5); await sendKeys( tester, <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); // |word wo|rd word expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 0); await sendKeys( tester, <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); // word| wo|rd word expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 4); await sendKeys( tester, <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); if (defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS) { // word wo|rd word expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 7); await sendKeys( tester, <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, ); } // word wo|rd| word expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 9); // On web, using keyboard for selection is handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('navigating multiline text', (WidgetTester tester) async { controller.text = 'word word word\nword word\nword'; // 15 + 10 + 4; // wo|rd wo|rd controller.selection = const TextSelection( baseOffset: 17, extentOffset: 22, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 17); expect(controller.selection.extentOffset, 22); // Multiple expandRightByLine shortcuts only move to the end of the line and // not to the next line. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 17); expect(controller.selection.extentOffset, 24); // Multiple expandLeftByLine shortcuts only move to the start of the line // and not to the previous line. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, false); switch (defaultTargetPlatform) { // These platforms extend by line. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, 17); expect(controller.selection.extentOffset, 15); // Mac and iOS expand by line. case TargetPlatform.iOS: case TargetPlatform.macOS: expect(controller.selection.baseOffset, 15); expect(controller.selection.extentOffset, 24); } // Set the caret to the end of a line. controller.selection = const TextSelection( baseOffset: 24, extentOffset: 24, affinity: TextAffinity.upstream, ); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 24); expect(controller.selection.extentOffset, 24); // Can't expand right by line any further. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 24); expect(controller.selection.extentOffset, 24); // Can select the entire line from the end. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 24); expect(controller.selection.extentOffset, 15); // Set the caret to the start of a line. controller.selection = const TextSelection( baseOffset: 15, extentOffset: 15, ); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 15); expect(controller.selection.extentOffset, 15); // Can't expand let any further. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 15); expect(controller.selection.extentOffset, 15); // Can select the entire line from the start. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 15); expect(controller.selection.extentOffset, 24); // On web, using keyboard for selection is handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets("Mac's expand by line behavior on multiple lines", (WidgetTester tester) async { controller.text = 'word word word\nword word\nword'; // 15 + 10 + 4; // word word word // wo|rd word // w|ord controller.selection = const TextSelection( baseOffset: 17, extentOffset: 26, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 17); expect(controller.selection.extentOffset, 26); // Expanding right to the end of the line moves the extent on the second // selected line. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 17); expect(controller.selection.extentOffset, 29); // Expanding right again does nothing. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 17); expect(controller.selection.extentOffset, 29); // Expanding left by line moves the base on the first selected line to the // beginning of that line. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 15); expect(controller.selection.extentOffset, 29); // Expanding left again does nothing. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, ], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 15); expect(controller.selection.extentOffset, 29); }, // On web, using keyboard for selection is handled by the browser. skip: kIsWeb, // [intended] variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) ); testWidgets("Mac's expand extent position", (WidgetTester tester) async { controller.text = 'Now is the time for all good people to come to the aid of their country'; // Start the selection in the middle somewhere. controller.selection = const TextSelection.collapsed(offset: 10); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 10); // With cursor in the middle of the line, cmd + left. Left end is the extent. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( controller.selection, equals( const TextSelection( baseOffset: 10, extentOffset: 0, affinity: TextAffinity.upstream, ), ), ); // With cursor in the middle of the line, cmd + right. Right end is the extent. controller.selection = const TextSelection.collapsed(offset: 10); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( controller.selection, equals( const TextSelection( baseOffset: 10, extentOffset: 29, affinity: TextAffinity.upstream, ), ), ); // With cursor in the middle of the line, cmd + left then cmd + right. Left end is the extent. controller.selection = const TextSelection.collapsed(offset: 10); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( controller.selection, equals( const TextSelection( baseOffset: 29, extentOffset: 0, ), ), ); // With cursor in the middle of the line, cmd + right then cmd + left. Right end is the extent. controller.selection = const TextSelection.collapsed(offset: 10); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( controller.selection, equals( const TextSelection( baseOffset: 0, extentOffset: 29, affinity: TextAffinity.upstream, ), ), ); // With an RTL selection in the middle of the line, cmd + left. Left end is the extent. controller.selection = const TextSelection(baseOffset: 12, extentOffset: 8); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( controller.selection, equals( const TextSelection( baseOffset: 12, extentOffset: 0, affinity: TextAffinity.upstream, ), ), ); // With an RTL selection in the middle of the line, cmd + right. Left end is the extent. controller.selection = const TextSelection(baseOffset: 12, extentOffset: 8); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( controller.selection, equals( const TextSelection( baseOffset: 29, extentOffset: 8, affinity: TextAffinity.upstream, ), ), ); // With an LTR selection in the middle of the line, cmd + right. Right end is the extent. controller.selection = const TextSelection(baseOffset: 8, extentOffset: 12); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( controller.selection, equals( const TextSelection( baseOffset: 8, extentOffset: 29, affinity: TextAffinity.upstream, ), ), ); // With an LTR selection in the middle of the line, cmd + left. Right end is the extent. controller.selection = const TextSelection(baseOffset: 8, extentOffset: 12); await tester.pump(); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, ); expect( controller.selection, equals( const TextSelection( baseOffset: 0, extentOffset: 12, affinity: TextAffinity.upstream, ), ), ); }, // On web, using keyboard for selection is handled by the browser. skip: kIsWeb, // [intended] variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) ); testWidgets('expanding selection to start/end single line', (WidgetTester tester) async { controller.text = 'word word word'; // word wo|rd| word controller.selection = const TextSelection( baseOffset: 7, extentOffset: 9, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); expect(controller.selection.extentOffset, 9); final String targetPlatform = defaultTargetPlatform.toString(); final String platform = targetPlatform.substring(targetPlatform.indexOf('.') + 1).toLowerCase(); // Select to the start. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, ], shift: true, targetPlatform: defaultTargetPlatform, ); // |word word| word expect( controller.selection, equals( const TextSelection( baseOffset: 9, extentOffset: 0, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); // Select to the end. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, ], shift: true, targetPlatform: defaultTargetPlatform, ); // |word word word| expect( controller.selection, equals( const TextSelection( baseOffset: 0, extentOffset: 14, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); }, // On web, using keyboard for selection is handled by the browser. skip: kIsWeb, // [intended] variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) ); testWidgets('can change text editing behavior by overriding actions', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); bool myIntentWasCalled = false; final CallbackAction<ExtendSelectionByCharacterIntent> overrideAction = CallbackAction<ExtendSelectionByCharacterIntent>( onInvoke: (ExtendSelectionByCharacterIntent intent) { myIntentWasCalled = true; return null; }, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: Actions( actions: <Type, Action<Intent>>{ ExtendSelectionByCharacterIntent: overrideAction, }, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); expect(myIntentWasCalled, isTrue); // On web, using keyboard for selection is handled by the browser. }, skip: kIsWeb); // [intended] testWidgets('ignore key event from web platform', (WidgetTester tester) async { controller.text = 'test\ntest'; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); bool myIntentWasCalled = false; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: Actions( actions: <Type, Action<Intent>>{ ExtendSelectionByCharacterIntent: CallbackAction<ExtendSelectionByCharacterIntent>( onInvoke: (ExtendSelectionByCharacterIntent intent) { myIntentWasCalled = true; return null; }, ), }, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. if (kIsWeb) { await simulateKeyDownEvent(LogicalKeyboardKey.arrowRight, platform: 'web'); await tester.pump(); expect(myIntentWasCalled, isFalse); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); } else { await simulateKeyDownEvent(LogicalKeyboardKey.arrowRight, platform: 'android'); await tester.pump(); expect(myIntentWasCalled, isTrue); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); } }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('the toolbar is disposed when selection changes and there is no selectionControls', (WidgetTester tester) async { late StateSetter setState; bool enableInteractiveSelection = true; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return EditableText( focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: enableInteractiveSelection ? materialTextSelectionControls : null, controller: controller, enableInteractiveSelection: enableInteractiveSelection, ); }, ), ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Can't show the toolbar when there's no focus. expect(state.showToolbar(), false); await tester.pumpAndSettle(); expect(find.text('Paste'), findsNothing); // Can show the toolbar when focused even though there's no text. state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pump(); expect(state.showToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); // Find the FadeTransition in the toolbar and expect that it has not been // disposed. final FadeTransition fadeTransition = find.byType(FadeTransition).evaluate() .map((Element element) => element.widget as FadeTransition) .firstWhere((FadeTransition fadeTransition) { return fadeTransition.child is CompositedTransformFollower; }); expect(fadeTransition.toString(), isNot(contains('DISPOSED'))); // Turn off interactive selection and change the text, which triggers the // toolbar to be disposed. setState(() { enableInteractiveSelection = false; }); await tester.pump(); await tester.enterText(find.byType(EditableText), 'abc'); await tester.pump(); expect(fadeTransition.toString(), contains('DISPOSED')); // On web, using keyboard for selection is handled by the browser. }, skip: kIsWeb); // [intended] testWidgets('EditableText does not leak animation controllers', (WidgetTester tester) async { controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( autofocus: true, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, ), ), ); expect(focusNode.hasPrimaryFocus, isTrue); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); // Start the cursor blink opacity animation controller. // _kCursorBlinkWaitForStart await tester.pump(const Duration(milliseconds: 150)); // _kCursorBlinkHalfPeriod await tester.pump(const Duration(milliseconds: 500)); // Start the floating cursor reset animation controller. state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); expect(tester.binding.transientCallbackCount, 2); await tester.pumpWidget(const SizedBox()); expect(tester.hasRunningAnimations, isFalse); }); testWidgets('Floating cursor affinity', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; final GlobalKey key = GlobalKey(); // Set it up so that there will be word-wrap. controller.text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz'; await tester.pumpWidget( MaterialApp( home: Center( child: ConstrainedBox( constraints: const BoxConstraints( maxWidth: 500, ), child: EditableText( key: key, autofocus: true, maxLines: 2, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, ), ), ), ), ); await tester.pump(); final EditableTextState state = tester.state(find.byType(EditableText)); // Select after the first word, with default affinity (downstream). controller.selection = const TextSelection.collapsed(offset: 27); await tester.pump(); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); await tester.pump(); // The floating cursor should be drawn at the end of the first line. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(0.5, 15, 3, 12), const Radius.circular(1) ) )); // Select after the first word, with upstream affinity. controller.selection = const TextSelection.collapsed(offset: 27, affinity: TextAffinity.upstream); await tester.pump(); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); await tester.pump(); // The floating cursor should be drawn at the beginning of the second line. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(378.5, 1, 3, 12), const Radius.circular(1) ) )); EditableText.debugDeterministicCursor = false; }); testWidgets('Floating cursor ending with selection', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; final GlobalKey key = GlobalKey(); SelectionChangedCause? lastSelectionChangedCause; controller.text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ\n1234567890'; controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget( MaterialApp( home: EditableText( key: key, autofocus: true, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { lastSelectionChangedCause = cause; }, maxLines: 2, ), ), ); await tester.pump(); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); await tester.pump(); // The cursor should be drawn at the start of the line. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(0.5, 1, 3, 12), const Radius.circular(1) ) )); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(50, 0))); await tester.pump(); // The cursor should be drawn somewhere in the middle of the line expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(50.5, 1, 3, 12), const Radius.circular(1) ) )); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); await tester.pumpAndSettle(const Duration(milliseconds: 125)); // Floating cursor has an end animation. // Selection should be updated based on the floating cursor location. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 4); expect(lastSelectionChangedCause, SelectionChangedCause.forcePress); lastSelectionChangedCause = null; state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); await tester.pump(); // The cursor should be drawn near to the previous position. // It's different because it's snapped to exactly between characters. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(56.5, 1, 3, 12), const Radius.circular(1) ) )); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(-56, 0))); await tester.pump(); // The cursor should be drawn at the start of the line. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(0.5, 1, 3, 12), const Radius.circular(1) ) )); // Simulate UIKit setting the selection using keyboard selection. state.updateEditingValue(state.currentTextEditingValue.copyWith(selection: const TextSelection(baseOffset: 0, extentOffset: 4))); await tester.pump(); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); await tester.pump(); // Selection should not be changed since it wasn't previously collapsed. expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 4); expect(lastSelectionChangedCause, SelectionChangedCause.forcePress); lastSelectionChangedCause = null; // Now test using keyboard selection in a forwards direction. state.updateEditingValue(state.currentTextEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 0))); await tester.pump(); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); await tester.pump(); // The cursor should be drawn in the same (start) position. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(0.5, 1, 3, 12), const Radius.circular(1) ) )); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(56, 0))); await tester.pump(); // The cursor should be drawn somewhere in the middle of the line. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(56.5, 1, 3, 12), const Radius.circular(1) ) )); // Simulate UIKit setting the selection using keyboard selection. state.updateEditingValue(state.currentTextEditingValue.copyWith(selection: const TextSelection(baseOffset: 0, extentOffset: 4))); await tester.pump(); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); await tester.pump(); // Selection should not be changed since it wasn't previously collapsed. expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 4); expect(lastSelectionChangedCause, SelectionChangedCause.forcePress); lastSelectionChangedCause = null; // Test that the affinity is updated in case the floating cursor ends at the same offset. // Put the selection at the beginning of the second line. state.updateEditingValue(state.currentTextEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 27))); await tester.pump(); // Now test using keyboard selection in a forwards direction. state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); await tester.pump(); // The cursor should be drawn at the start of the second line. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(0.5, 15, 3, 12), const Radius.circular(1) ) )); // Move the cursor to the end of the first line. state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(9999, -14))); await tester.pump(); // The cursor should be drawn at the end of the first line. expect(key.currentContext!.findRenderObject(), paints..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(800.5, 1, 3, 12), const Radius.circular(1) ) )); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); await tester.pump(); // Selection should be changed as it was previously collapsed. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 27); expect(controller.selection.extentOffset, 27); expect(lastSelectionChangedCause, SelectionChangedCause.forcePress); lastSelectionChangedCause = null; EditableText.debugDeterministicCursor = false; }); group('Selection changed scroll into view', () { final String text = List<int>.generate(64, (int index) => index).join('\n'); final TextEditingController controller = TextEditingController(text: text); final ScrollController scrollController = ScrollController(); late double maxScrollExtent; tearDownAll(() { controller.dispose(); scrollController.dispose(); }); Future<void> resetSelectionAndScrollOffset(WidgetTester tester, {required bool setMaxScrollExtent}) async { controller.value = controller.value.copyWith( text: text, selection: controller.selection.copyWith(baseOffset: 0, extentOffset: 1), ); await tester.pump(); final double targetOffset = setMaxScrollExtent ? scrollController.position.maxScrollExtent : 0.0; scrollController.jumpTo(targetOffset); await tester.pumpAndSettle(); maxScrollExtent = scrollController.position.maxScrollExtent; expect(scrollController.offset, targetOffset); } Future<TextSelectionDelegate> pumpLongScrollableText(WidgetTester tester) async { final GlobalKey<EditableTextState> key = GlobalKey<EditableTextState>(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: SizedBox( height: 32, child: EditableText( key: key, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, controller: controller, scrollController: scrollController, maxLines: 2, ), ), ), ), ), ); // Populate [maxScrollExtent]. await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); return key.currentState!; } testWidgets('SelectAll toolbar action will not set max scroll on designated platforms', (WidgetTester tester) async { final TextSelectionDelegate textSelectionDelegate = await pumpLongScrollableText(tester); await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); textSelectionDelegate.selectAll(SelectionChangedCause.toolbar); await tester.pump(); expect(scrollController.offset, 0.0); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Selection will be scrolled into view with SelectionChangedCause', (WidgetTester tester) async { final TextSelectionDelegate textSelectionDelegate = await pumpLongScrollableText(tester); // Cut await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); textSelectionDelegate.cutSelection(SelectionChangedCause.keyboard); await tester.pump(); expect(scrollController.offset, maxScrollExtent); await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); textSelectionDelegate.cutSelection(SelectionChangedCause.toolbar); await tester.pump(); expect(scrollController.offset.roundToDouble(), 0.0); // Paste await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); await textSelectionDelegate.pasteText(SelectionChangedCause.keyboard); await tester.pump(); expect(scrollController.offset, maxScrollExtent); await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); await textSelectionDelegate.pasteText(SelectionChangedCause.toolbar); await tester.pump(); expect(scrollController.offset.roundToDouble(), 0.0); // Select all await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); textSelectionDelegate.selectAll(SelectionChangedCause.keyboard); await tester.pump(); expect(scrollController.offset, 0.0); await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); textSelectionDelegate.selectAll(SelectionChangedCause.toolbar); await tester.pump(); expect(scrollController.offset.roundToDouble(), maxScrollExtent); // Copy await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); textSelectionDelegate.copySelection(SelectionChangedCause.keyboard); await tester.pump(); expect(scrollController.offset, maxScrollExtent); await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); textSelectionDelegate.copySelection(SelectionChangedCause.toolbar); await tester.pump(); expect(scrollController.offset.roundToDouble(), 0.0); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); }); testWidgets('Should not scroll on paste if caret already visible', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/96658. final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); controller.text = 'Lorem ipsum please paste here: \n${".\n" * 50}'; await tester.pumpWidget( MaterialApp( home: Center( child: SizedBox( height: 600.0, width: 600.0, child: EditableText( controller: controller, scrollController: scrollController, focusNode: focusNode, maxLines: null, style: const TextStyle(fontSize: 36.0), backgroundCursorColor: Colors.grey, cursorColor: cursorColor, ), ), ), ) ); await Clipboard.setData(const ClipboardData(text: 'Fairly long text to be pasted')); focusNode.requestFocus(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(scrollController.offset, 0.0); controller.selection = const TextSelection.collapsed(offset: 31); await state.pasteText(SelectionChangedCause.toolbar); await tester.pumpAndSettle(); // No scroll should happen as the caret is in the viewport all the time. expect(scrollController.offset, 0.0); }); testWidgets('Autofill enabled by default', (WidgetTester tester) async { controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( autofocus: true, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, ), ), ); assert(focusNode.hasFocus); expect( tester.testTextInput.log, contains(matchesMethodCall('TextInput.requestAutofill')), ); }); testWidgets('Autofill can be disabled', (WidgetTester tester) async { controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( autofocus: true, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, ), ), ); assert(focusNode.hasFocus); expect( tester.testTextInput.log, isNot(contains(matchesMethodCall('TextInput.requestAutofill'))), ); }); group('TextEditingHistory', () { Future<void> sendUndoRedo(WidgetTester tester, [bool redo = false]) { return sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyZ, ], shortcutModifier: true, shift: redo, targetPlatform: defaultTargetPlatform, ); } Future<void> sendUndo(WidgetTester tester) => sendUndoRedo(tester); Future<void> sendRedo(WidgetTester tester) => sendUndoRedo(tester, true); TextEditingValue emptyComposingOnAndroid(TextEditingValue value) { if (defaultTargetPlatform == TargetPlatform.android) { return value.copyWith(composing: TextRange.empty); } return value; } Widget boilerplate() { return MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, ), ); } // Wait for the throttling. This is used to ensure a new history entry is created. Future<void> waitForThrottling(WidgetTester tester) async { await tester.pump(const Duration(milliseconds: 500)); } // Empty text editing value with a collapsed selection. const TextEditingValue emptyTextCollapsed = TextEditingValue( selection: TextSelection.collapsed(offset: 0), ); // Texts and text editing values used repeatedly in undo/redo tests. const String textA = 'A'; const String textAB = 'AB'; const String textAC = 'AC'; const TextEditingValue textACollapsedAtEnd = TextEditingValue( text: textA, selection: TextSelection.collapsed(offset: textA.length), ); const TextEditingValue textABCollapsedAtEnd = TextEditingValue( text: textAB, selection: TextSelection.collapsed(offset: textAB.length), ); const TextEditingValue textACCollapsedAtEnd = TextEditingValue( text: textAC, selection: TextSelection.collapsed(offset: textAC.length), ); testWidgets('Should have no effect on an empty and non-focused field', (WidgetTester tester) async { await tester.pumpWidget(boilerplate()); expect(controller.value, TextEditingValue.empty); // Undo/redo have no effect on an empty field that has never been edited. await sendUndo(tester); expect(controller.value, TextEditingValue.empty); await sendRedo(tester); expect(controller.value, TextEditingValue.empty); await tester.pump(); expect(controller.value, TextEditingValue.empty); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('Should have no effect on an empty and focused field', (WidgetTester tester) async { await tester.pumpWidget(boilerplate()); await waitForThrottling(tester); expect(controller.value, TextEditingValue.empty); // Focus the field and wait for throttling delay to get the initial // state saved in text editing history. focusNode.requestFocus(); await tester.pump(); expect(controller.value, emptyTextCollapsed); await waitForThrottling(tester); // Undo/redo should have no effect. The field is focused and the value has // changed, but the text remains empty. await sendUndo(tester); expect(controller.value, emptyTextCollapsed); await sendRedo(tester); expect(controller.value, emptyTextCollapsed); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('Can undo/redo a single insertion', (WidgetTester tester) async { await tester.pumpWidget(boilerplate()); // Focus the field and wait for throttling delay to get the initial // state saved in text editing history. focusNode.requestFocus(); await tester.pump(); await waitForThrottling(tester); expect(controller.value, emptyTextCollapsed); // First insertion. await tester.enterText(find.byType(EditableText), textA); await waitForThrottling(tester); expect(controller.value, textACollapsedAtEnd); // A redo before any undo has no effect. await sendRedo(tester); expect(controller.value, textACollapsedAtEnd); // Can undo a single insertion. await sendUndo(tester); expect(controller.value, emptyTextCollapsed); // A second undo has no effect. await sendUndo(tester); expect(controller.value, emptyTextCollapsed); // Can redo a single insertion. await sendRedo(tester); expect(controller.value, textACollapsedAtEnd); // A second redo has no effect. await sendRedo(tester); expect(controller.value, textACollapsedAtEnd); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('Can undo/redo multiple insertions', (WidgetTester tester) async { await tester.pumpWidget(boilerplate()); // Focus the field and wait for throttling delay to get the initial // state saved in text editing history. focusNode.requestFocus(); await tester.pump(); await waitForThrottling(tester); expect(controller.value, emptyTextCollapsed); // First insertion. await tester.enterText(find.byType(EditableText), textA); await waitForThrottling(tester); expect(controller.value, textACollapsedAtEnd); // Second insertion. await tester.enterText(find.byType(EditableText), textAB); await waitForThrottling(tester); expect(controller.value, textABCollapsedAtEnd); // Undo the first insertion. await sendUndo(tester); expect(controller.value, textACollapsedAtEnd); // Undo the second insertion. await sendUndo(tester); expect(controller.value, emptyTextCollapsed); // Redo the second insertion. await sendRedo(tester); expect(controller.value, textACollapsedAtEnd); // Redo the first insertion. await sendRedo(tester); expect(controller.value, textABCollapsedAtEnd); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] // Regression test for https://github.com/flutter/flutter/issues/120794. // This is only reproducible on Android platform because it is the only // platform where composing changes are saved in the editing history. testWidgets('Can undo as intented when adding a delay between undos', (WidgetTester tester) async { await tester.pumpWidget(boilerplate()); // Focus the field and wait for throttling delay to get the initial // state saved in text editing history. focusNode.requestFocus(); await tester.pump(); await waitForThrottling(tester); expect(controller.value, emptyTextCollapsed); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); const TextEditingValue composingStep1 = TextEditingValue( text: '1 ni', composing: TextRange(start: 2, end: 4), selection: TextSelection.collapsed(offset: 4), ); const TextEditingValue composingStep2 = TextEditingValue( text: '1 nihao', composing: TextRange(start: 2, end: 7), selection: TextSelection.collapsed(offset: 7), ); const TextEditingValue composingStep3 = TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ); // Enter some composing text. state.userUpdateTextEditingValue(composingStep1, SelectionChangedCause.keyboard); await waitForThrottling(tester); state.userUpdateTextEditingValue(composingStep2, SelectionChangedCause.keyboard); await waitForThrottling(tester); state.userUpdateTextEditingValue(composingStep3, SelectionChangedCause.keyboard); await waitForThrottling(tester); // Undo first insertion. await sendUndo(tester); expect(controller.value, emptyComposingOnAndroid(composingStep2)); // Waiting for the throttling between undos should have no effect. await tester.pump(const Duration(milliseconds: 500)); // Undo second insertion. await sendUndo(tester); expect(controller.value, emptyComposingOnAndroid(composingStep1)); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] // Regression test for https://github.com/flutter/flutter/issues/120194. testWidgets('Cursor does not jump after undo', (WidgetTester tester) async { // Initialize the controller with a non empty text. controller.text = textA; await tester.pumpWidget(boilerplate()); // Focus the field and wait for throttling delay to get the initial // state saved in text editing history. focusNode.requestFocus(); await tester.pump(); await waitForThrottling(tester); expect(controller.value, textACollapsedAtEnd); // Insert some text. await tester.enterText(find.byType(EditableText), textAB); expect(controller.value, textABCollapsedAtEnd); // Undo the insertion without waiting for the throttling delay. await sendUndo(tester); expect(controller.value.selection.isValid, true); expect(controller.value, textACollapsedAtEnd); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('Initial value is recorded when an undo is received just after getting the focus', (WidgetTester tester) async { // Initialize the controller with a non empty text. controller.text = textA; await tester.pumpWidget(boilerplate()); // Focus the field and do not wait for throttling delay before calling undo. focusNode.requestFocus(); await tester.pump(); await sendUndo(tester); await waitForThrottling(tester); expect(controller.value, textACollapsedAtEnd); // Insert some text. await tester.enterText(find.byType(EditableText), textAB); expect(controller.value, textABCollapsedAtEnd); // Undo the insertion. await sendUndo(tester); // Initial text should have been recorded and restored. expect(controller.value, textACollapsedAtEnd); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('Can make changes in the middle of the history', (WidgetTester tester) async { await tester.pumpWidget(boilerplate()); // Focus the field and wait for throttling delay to get the initial // state saved in text editing history. focusNode.requestFocus(); await tester.pump(); await waitForThrottling(tester); expect(controller.value, emptyTextCollapsed); // First insertion. await tester.enterText(find.byType(EditableText), textA); await waitForThrottling(tester); expect(controller.value, textACollapsedAtEnd); // Second insertion. await tester.enterText(find.byType(EditableText), textAC); await waitForThrottling(tester); expect(controller.value, textACCollapsedAtEnd); // Undo and make a change. await sendUndo(tester); expect(controller.value, textACollapsedAtEnd); await tester.enterText(find.byType(EditableText), textAB); await waitForThrottling(tester); expect(controller.value, textABCollapsedAtEnd); // Try a redo, state should not change because of the previous undo. await sendRedo(tester); expect(controller.value, textABCollapsedAtEnd); // Trying again will have no effect. await sendRedo(tester); expect(controller.value, textABCollapsedAtEnd); // Undo should restore state as it was before second insertion. await sendUndo(tester); expect(controller.value, textACollapsedAtEnd); // Another undo will restore state as before first insertion. await sendUndo(tester); expect(controller.value, emptyTextCollapsed); // Redo all changes. await sendRedo(tester); expect(controller.value, textACollapsedAtEnd); await sendRedo(tester); expect(controller.value, textABCollapsedAtEnd); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('inside EditableText, duplicate changes', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, ), ), ); expect( controller.value, TextEditingValue.empty, ); focusNode.requestFocus(); expect( controller.value, TextEditingValue.empty, ); await tester.pump(); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); // Wait for the throttling. await tester.pump(const Duration(milliseconds: 500)); await tester.enterText(find.byType(EditableText), '1'); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); await tester.pump(const Duration(milliseconds: 500)); // Can undo/redo a single insertion. await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); // Changes that result in the same state won't be saved on the undo stack. await tester.enterText(find.byType(EditableText), '12'); expect( controller.value, const TextEditingValue( text: '12', selection: TextSelection.collapsed(offset: 2), ), ); await tester.enterText(find.byType(EditableText), '1'); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); await tester.pump(const Duration(milliseconds: 500)); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('inside EditableText, autofocus', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( autofocus: true, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, ), ), ); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await tester.pump(); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); // Wait for the throttling. await tester.pump(const Duration(milliseconds: 500)); await tester.enterText(find.byType(EditableText), '1'); await tester.pump(const Duration(milliseconds: 500)); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1', selection: TextSelection.collapsed(offset: 1), ), ); }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] testWidgets('does not save composing changes (except Android)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, ), ), ); expect( controller.value, TextEditingValue.empty, ); focusNode.requestFocus(); expect( controller.value, TextEditingValue.empty, ); await tester.pump(); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); // Wait for the throttling. await tester.pump(const Duration(milliseconds: 500)); // Enter some regular non-composing text that is undoable. await tester.enterText(find.byType(EditableText), '1 '); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await tester.pump(const Duration(milliseconds: 500)); // Enter some composing text. final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.userUpdateTextEditingValue( const TextEditingValue( text: '1 ni', composing: TextRange(start: 2, end: 4), selection: TextSelection.collapsed(offset: 4), ), SelectionChangedCause.keyboard, ); await tester.pump(const Duration(milliseconds: 500)); // Enter some more composing text. state.userUpdateTextEditingValue( const TextEditingValue( text: '1 nihao', composing: TextRange(start: 2, end: 7), selection: TextSelection.collapsed(offset: 7), ), SelectionChangedCause.keyboard, ); await tester.pump(const Duration(milliseconds: 500)); // Commit the composing text. state.userUpdateTextEditingValue( const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), SelectionChangedCause.keyboard, ); await tester.pump(const Duration(milliseconds: 500)); expect( controller.value, const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), ); // Undo/redo ignores the composing changes. await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), ); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.android }), skip: kIsWeb); // [intended] testWidgets('does save composing changes on Android', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, ), ), ); expect( controller.value, TextEditingValue.empty, ); focusNode.requestFocus(); expect( controller.value, TextEditingValue.empty, ); await tester.pump(); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); // Wait for the throttling. await tester.pump(const Duration(milliseconds: 500)); // Enter some regular non-composing text that is undoable. await tester.enterText(find.byType(EditableText), '1 '); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await tester.pump(const Duration(milliseconds: 500)); // Enter some composing text. final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.userUpdateTextEditingValue( const TextEditingValue( text: '1 ni', composing: TextRange(start: 2, end: 4), selection: TextSelection.collapsed(offset: 4), ), SelectionChangedCause.keyboard, ); await tester.pump(const Duration(milliseconds: 500)); // Enter some more composing text. state.userUpdateTextEditingValue( const TextEditingValue( text: '1 nihao', composing: TextRange(start: 2, end: 7), selection: TextSelection.collapsed(offset: 7), ), SelectionChangedCause.keyboard, ); await tester.pump(const Duration(milliseconds: 500)); // Commit the composing text. state.userUpdateTextEditingValue( const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), SelectionChangedCause.keyboard, ); await tester.pump(const Duration(milliseconds: 500)); expect( controller.value, const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), ); // Undo/redo includes the composing changes. await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 nihao', selection: TextSelection.collapsed(offset: 7), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 ni', selection: TextSelection.collapsed(offset: 4), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 ni', selection: TextSelection.collapsed(offset: 4), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 nihao', selection: TextSelection.collapsed(offset: 7), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 nihao', selection: TextSelection.collapsed(offset: 7), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 ni', selection: TextSelection.collapsed(offset: 4), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 ni', selection: TextSelection.collapsed(offset: 4), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 nihao', selection: TextSelection.collapsed(offset: 7), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 你好', selection: TextSelection.collapsed(offset: 4), ), ); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] testWidgets('saves right up to composing change even when throttled', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: textStyle, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, ), ), ); expect( controller.value, TextEditingValue.empty, ); focusNode.requestFocus(); expect( controller.value, TextEditingValue.empty, ); await tester.pump(); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); // Wait for the throttling. await tester.pump(const Duration(milliseconds: 500)); // Enter some regular non-composing text that is undoable. await tester.enterText(find.byType(EditableText), '1 '); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await tester.pump(const Duration(milliseconds: 500)); // Enter some regular non-composing text and then immediately enter some // composing text. await tester.enterText(find.byType(EditableText), '1 2 '); expect( controller.value, const TextEditingValue( text: '1 2 ', selection: TextSelection.collapsed(offset: 4), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.userUpdateTextEditingValue( const TextEditingValue( text: '1 2 ni', composing: TextRange(start: 4, end: 6), selection: TextSelection.collapsed(offset: 6), ), SelectionChangedCause.keyboard, ); expect( controller.value, const TextEditingValue( text: '1 2 ni', composing: TextRange(start: 4, end: 6), selection: TextSelection.collapsed(offset: 6), ), ); await tester.pump(const Duration(milliseconds: 500)); // Commit the composing text. state.userUpdateTextEditingValue( const TextEditingValue( text: '1 2 你', selection: TextSelection.collapsed(offset: 5), ), SelectionChangedCause.keyboard, ); await tester.pump(const Duration(milliseconds: 500)); expect( controller.value, const TextEditingValue( text: '1 2 你', selection: TextSelection.collapsed(offset: 5), ), ); // Undo/redo still gets the second non-composing change. await sendUndo(tester); switch (defaultTargetPlatform) { // Android includes composing changes. case TargetPlatform.android: expect( controller.value, emptyComposingOnAndroid( const TextEditingValue( text: '1 2 ni', composing: TextRange(start: 4, end: 6), selection: TextSelection.collapsed(offset: 6), ), ), ); // Composing changes are ignored on all other platforms. case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: case TargetPlatform.iOS: case TargetPlatform.macOS: expect( controller.value, const TextEditingValue( text: '1 2 ', selection: TextSelection.collapsed(offset: 4), ), ); } await sendUndo(tester); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendUndo(tester); expect( controller.value, const TextEditingValue( selection: TextSelection.collapsed(offset: 0), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 ', selection: TextSelection.collapsed(offset: 2), ), ); await sendRedo(tester); switch (defaultTargetPlatform) { // Android includes composing changes. case TargetPlatform.android: expect( controller.value, emptyComposingOnAndroid( const TextEditingValue( text: '1 2 ni', composing: TextRange(start: 4, end: 6), selection: TextSelection.collapsed(offset: 6), ), ), ); // Composing changes are ignored on all other platforms. case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: case TargetPlatform.iOS: case TargetPlatform.macOS: expect( controller.value, const TextEditingValue( text: '1 2 ', selection: TextSelection.collapsed(offset: 4), ), ); } await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 2 你', selection: TextSelection.collapsed(offset: 5), ), ); await sendRedo(tester); expect( controller.value, const TextEditingValue( text: '1 2 你', selection: TextSelection.collapsed(offset: 5), ), ); // On web, these keyboard shortcuts are handled by the browser. }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] }); testWidgets('pasting with the keyboard collapses the selection and places it after the pasted content', (WidgetTester tester) async { Future<void> testPasteSelection(WidgetTester tester, _VoidFutureCallback paste) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); await tester.pump(); expect(controller.text, ''); await tester.enterText(find.byType(EditableText), '12345'); expect(controller.value, const TextEditingValue( text: '12345', selection: TextSelection.collapsed(offset: 5), )); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect(controller.value, const TextEditingValue( text: '12345', selection: TextSelection(baseOffset: 5, extentOffset: 0), )); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyC, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.value, const TextEditingValue( text: '12345', selection: TextSelection(baseOffset: 5, extentOffset: 0), )); // Pasting content of equal length, reversed selection. await paste(); expect(controller.value, const TextEditingValue( text: '12345', selection: TextSelection.collapsed(offset: 5), )); // Pasting content of longer length, forward selection. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, ], targetPlatform: defaultTargetPlatform, ); await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, ], shift: true, targetPlatform: defaultTargetPlatform, ); expect(controller.value, const TextEditingValue( text: '12345', selection: TextSelection(baseOffset: 4, extentOffset: 5), )); await paste(); expect(controller.value, const TextEditingValue( text: '123412345', selection: TextSelection.collapsed(offset: 9), )); // Pasting content of shorter length, forward selection. await sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyA, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect(controller.value, const TextEditingValue( text: '123412345', selection: TextSelection(baseOffset: 0, extentOffset: 9), )); await paste(); // Pump to allow postFrameCallbacks to finish before dispose. await tester.pump(); expect(controller.value, const TextEditingValue( text: '12345', selection: TextSelection.collapsed(offset: 5), )); } // Test pasting with the keyboard. await testPasteSelection(tester, () { return sendKeys( tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.keyV, ], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); }); // Test pasting with the toolbar. await testPasteSelection(tester, () async { final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.showToolbar(), true); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); return tester.tap(find.text('Paste')); }); }, skip: kIsWeb); // [intended] // Regression test for https://github.com/flutter/flutter/issues/98322. testWidgets('EditableText consumes ActivateIntent and ButtonActivateIntent', (WidgetTester tester) async { bool receivedIntent = false; await tester.pumpWidget( MaterialApp( home: Actions( actions: <Type, Action<Intent>>{ ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: (_) { receivedIntent = true; return; }), ButtonActivateIntent: CallbackAction<ActivateIntent>(onInvoke: (_) { receivedIntent = true; return; }), }, child: EditableText( autofocus: true, backgroundCursorColor: Colors.blue, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ); await tester.pump(); expect(focusNode.hasFocus, isTrue); // ActivateIntent, which is triggered by space and enter in WidgetsApp, is // consumed by EditableText so that the space/enter reach the IME. await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pump(); expect(receivedIntent, isFalse); await tester.sendKeyEvent(LogicalKeyboardKey.enter); await tester.pump(); expect(receivedIntent, isFalse); }); // Regression test for https://github.com/flutter/flutter/issues/100585. testWidgets('can paste and remove field', (WidgetTester tester) async { controller.text = 'text'; late StateSetter setState; bool showField = true; final _CustomTextSelectionControls controls = _CustomTextSelectionControls( onPaste: () { setState(() { showField = false; }); }, ); await tester.pumpWidget(MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter stateSetter) { setState = stateSetter; if (!showField) { return const Placeholder(); } return EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: controls, ); }, ), )); await tester.tap(find.byType(EditableText)); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); await tester.longPress(find.byType(EditableText)); await tester.pump(); expect(state.showToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('Paste'), findsOneWidget); await tester.tap(find.text('Paste')); await tester.pumpAndSettle(); expect(tester.takeException(), null); // On web, the text selection toolbar paste button is handled by the browser. }, skip: kIsWeb); // [intended] // Regression test for https://github.com/flutter/flutter/issues/100585. testWidgets('can cut and remove field', (WidgetTester tester) async { controller.text = 'text'; late StateSetter setState; bool showField = true; final _CustomTextSelectionControls controls = _CustomTextSelectionControls( onCut: () { setState(() { showField = false; }); }, ); await tester.pumpWidget(MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter stateSetter) { setState = stateSetter; if (!showField) { return const Placeholder(); } return EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: controls, ); }, ), )); await tester.tap(find.byType(EditableText)); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); await tester.tapAt(textOffsetToPosition(tester, 2)); state.renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pump(); expect(state.showToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('Cut'), findsOneWidget); await tester.tap(find.text('Cut')); await tester.pumpAndSettle(); expect(tester.takeException(), null); // On web, the text selection toolbar cut button is handled by the browser. }, skip: kIsWeb); // [intended] group('Mac document shortcuts', () { testWidgets('ctrl-A/E', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); await tester.sendKeyDownEvent( LogicalKeyboardKey.controlLeft, platform: platform, ); await tester.pump(); await tester.sendKeyEvent(LogicalKeyboardKey.keyE, platform: platform); await tester.pump(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); await tester.pump(); expect( controller.selection, equals( const TextSelection.collapsed( offset: 19, affinity: TextAffinity.upstream, ), ), reason: 'on $platform', ); await tester.sendKeyDownEvent( LogicalKeyboardKey.controlLeft, platform: platform, ); await tester.pump(); await tester.sendKeyEvent(LogicalKeyboardKey.keyA, platform: platform); await tester.pump(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); await tester.pump(); expect( controller.selection, equals( const TextSelection.collapsed( offset: 0, ), ), reason: 'on $platform', ); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('ctrl-F/B', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); await tester.sendKeyDownEvent( LogicalKeyboardKey.controlLeft, platform: platform, ); await tester.pump(); await tester.sendKeyEvent(LogicalKeyboardKey.keyF, platform: platform); await tester.pump(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 1); await tester.sendKeyDownEvent( LogicalKeyboardKey.controlLeft, platform: platform, ); await tester.pump(); await tester.sendKeyEvent(LogicalKeyboardKey.keyB, platform: platform); await tester.pump(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('ctrl-N/P', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); await tester.sendKeyDownEvent( LogicalKeyboardKey.controlLeft, platform: platform, ); await tester.pump(); await tester.sendKeyEvent(LogicalKeyboardKey.keyN, platform: platform); await tester.pump(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 20); await tester.sendKeyDownEvent( LogicalKeyboardKey.controlLeft, platform: platform, ); await tester.pump(); await tester.sendKeyEvent(LogicalKeyboardKey.keyP, platform: platform); await tester.pump(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); group('ctrl-T to transpose', () { Future<void> ctrlT(WidgetTester tester, String platform) async { await tester.sendKeyDownEvent( LogicalKeyboardKey.controlLeft, platform: platform, ); await tester.pump(); await tester.sendKeyEvent(LogicalKeyboardKey.keyT, platform: platform); await tester.pump(); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); await tester.pump(); } testWidgets('with normal characters', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); // ctrl-T does nothing at the start of the field. await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); controller.selection = const TextSelection( baseOffset: 1, extentOffset: 4, ); await tester.pump(); expect(controller.selection.isCollapsed, isFalse); expect(controller.selection.baseOffset, 1); expect(controller.selection.extentOffset, 4); // ctrl-T does nothing when the selection isn't collapsed. await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isFalse); expect(controller.selection.baseOffset, 1); expect(controller.selection.extentOffset, 4); controller.selection = const TextSelection.collapsed(offset: 5); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 5); // ctrl-T swaps the previous and next characters when they exist. await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 6); expect(controller.text.substring(0, 19), 'Now si the time for'); await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 7); expect(controller.text.substring(0, 19), 'Now s ithe time for'); await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 8); expect(controller.text.substring(0, 19), 'Now s tihe time for'); controller.selection = TextSelection.collapsed( offset: controller.text.length, ); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, controller.text.length); expect(controller.text.substring(55, 72), 'of their country.'); await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, controller.text.length); expect(controller.text.substring(55, 72), 'of their countr.y'); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('with extended grapheme clusters', (WidgetTester tester) async { final String targetPlatformString = defaultTargetPlatform.toString(); final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); // One extended grapheme cluster of length 8 and one surrogate pair of // length 2. controller.text = '👨‍👩‍👦😆'; controller.selection = const TextSelection( baseOffset: 0, extentOffset: 0, affinity: TextAffinity.upstream, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); // ctrl-T does nothing at the start of the field. await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 0); expect(controller.text, '👨‍👩‍👦😆'); controller.selection = const TextSelection( baseOffset: 8, extentOffset: 10, ); await tester.pump(); expect(controller.selection.isCollapsed, isFalse); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 10); // ctrl-T does nothing when the selection isn't collapsed. await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isFalse); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 10); expect(controller.text, '👨‍👩‍👦😆'); controller.selection = const TextSelection.collapsed(offset: 8); await tester.pump(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 8); // ctrl-T swaps the previous and next characters when they exist. await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 10); expect(controller.text, '😆👨‍👩‍👦'); await ctrlT(tester, platform); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 10); expect(controller.text, '👨‍👩‍👦😆'); }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); }); testWidgets('macOS selectors work', (WidgetTester tester) async { controller.text = 'test\nline2'; controller.selection = TextSelection.collapsed(offset: controller.text.length); final GlobalKey<EditableTextState> key = GlobalKey<EditableTextState>(); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( key: key, maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ), ), ), )); key.currentState!.performSelector('moveLeft:'); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 9), ); key.currentState!.performSelector('moveToBeginningOfParagraph:'); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 5), ); // These both need to be handled, first moves cursor to the end of previous // paragraph, second moves to the beginning of paragraph. key.currentState!.performSelector('moveBackward:'); key.currentState!.performSelector('moveToBeginningOfParagraph:'); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 0), ); }); }); testWidgets('contextMenuBuilder is used in place of the default text selection toolbar', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, textAlign: TextAlign.right, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, EditableTextState editableTextState, ) { return SizedBox( key: key, width: 10.0, height: 10.0, ); }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(find.byKey(key), findsNothing); // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(find.byKey(key), findsOneWidget); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); testWidgets('contextMenuBuilder can be updated to display a new menu', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/142077. late StateSetter setState; final GlobalKey keyOne = GlobalKey(); final GlobalKey keyTwo = GlobalKey(); GlobalKey key = keyOne; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: StatefulBuilder( builder: (BuildContext context, StateSetter localSetState) { setState = localSetState; return EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, textAlign: TextAlign.right, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, EditableTextState editableTextState, ) { return SizedBox( key: key, width: 10.0, height: 10.0, ); }, ); }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. expect(find.byKey(keyOne), findsNothing); expect(find.byKey(keyTwo), findsNothing); // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(find.byKey(keyOne), findsOneWidget); expect(find.byKey(keyTwo), findsNothing); setState(() { key = keyTwo; }); await tester.pumpAndSettle(); expect(find.byKey(keyOne), findsNothing); expect(find.byKey(keyTwo), findsOneWidget); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); testWidgets('selectionControls can be updated', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/142077. controller.text = 'test'; late StateSetter setState; TextSelectionControls selectionControls = materialTextSelectionControls; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: StatefulBuilder( builder: (BuildContext context, StateSetter localSetState) { setState = localSetState; return EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, textAlign: TextAlign.right, selectionControls: selectionControls, ); }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. final Finder materialHandleFinder = find.byWidgetPredicate((Widget widget) { if (widget.runtimeType != CustomPaint) { return false; } final CustomPaint customPaint = widget as CustomPaint; return '${customPaint.painter.runtimeType}' == '_TextSelectionHandlePainter'; }); final Finder cupertinoHandleFinder = find.byWidgetPredicate((Widget widget) { if (widget.runtimeType != CustomPaint) { return false; } final CustomPaint customPaint = widget as CustomPaint; return '${customPaint.painter.runtimeType}' == '_CupertinoTextSelectionHandlePainter'; }); expect(materialHandleFinder, findsOneWidget); expect(cupertinoHandleFinder, findsNothing); // Long-press to select the text because Cupertino doesn't show a selection // handle when the selection is collapsed. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(materialHandleFinder, findsNWidgets(2)); expect(cupertinoHandleFinder, findsNothing); setState(() { selectionControls = cupertinoTextSelectionControls; }); await tester.pumpAndSettle(); expect(materialHandleFinder, findsNothing); expect(cupertinoHandleFinder, findsNWidgets(2)); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); testWidgets('onSelectionHandleTapped can be updated', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/142077. late StateSetter setState; int tapCount = 0; VoidCallback? onSelectionHandleTapped; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: StatefulBuilder( builder: (BuildContext context, StateSetter localSetState) { setState = localSetState; return EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, textAlign: TextAlign.right, selectionControls: materialTextSelectionControls, onSelectionHandleTapped: onSelectionHandleTapped, ); }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. final Finder materialHandleFinder = find.byWidgetPredicate((Widget widget) { if (widget.runtimeType != CustomPaint) { return false; } final CustomPaint customPaint = widget as CustomPaint; return '${customPaint.painter.runtimeType}' == '_TextSelectionHandlePainter'; }); expect(materialHandleFinder, findsOneWidget); expect(tapCount, equals(0)); await tester.tap(materialHandleFinder); await tester.pump(); expect(tapCount, equals(0)); setState(() { onSelectionHandleTapped = () => tapCount += 1; }); await tester.pumpAndSettle(); await tester.tap(materialHandleFinder); await tester.pump(); expect(tapCount, equals(1)); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); testWidgets('dragStartBehavior can be updated', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/142077. late StateSetter setState; DragStartBehavior dragStartBehavior = DragStartBehavior.down; await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: StatefulBuilder( builder: (BuildContext context, StateSetter localSetState) { setState = localSetState; return EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, textAlign: TextAlign.right, selectionControls: materialTextSelectionControls, dragStartBehavior: dragStartBehavior, ); }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. final Finder handleOverlayFinder = find.descendant( of: find.byType(Overlay), matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), ); expect(handleOverlayFinder, findsOneWidget); // Expects that the selection handle has the given DragStartBehavior. void checkDragStartBehavior(DragStartBehavior dragStartBehavior) { final RawGestureDetector rawGestureDetector = tester.widget(find.descendant( of: handleOverlayFinder, matching: find.byType(RawGestureDetector) ).first); final GestureRecognizerFactory<GestureRecognizer>? recognizerFactory = rawGestureDetector.gestures[PanGestureRecognizer]; final PanGestureRecognizer recognizer = PanGestureRecognizer(); recognizerFactory?.initializer(recognizer); expect(recognizer.dragStartBehavior, dragStartBehavior); recognizer.dispose(); } checkDragStartBehavior(DragStartBehavior.down); setState(() { dragStartBehavior = DragStartBehavior.start; }); await tester.pumpAndSettle(); expect(handleOverlayFinder, findsOneWidget); checkDragStartBehavior(DragStartBehavior.start); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); testWidgets('magnifierConfiguration can be updated to display a new magnifier', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/142077. late StateSetter setState; final GlobalKey keyOne = GlobalKey(); final GlobalKey keyTwo = GlobalKey(); GlobalKey key = keyOne; final TextMagnifierConfiguration magnifierConfiguration = TextMagnifierConfiguration( magnifierBuilder: (BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo>? info) { return Placeholder( key: key, ); }, ); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: StatefulBuilder( builder: (BuildContext context, StateSetter localSetState) { setState = localSetState; return EditableText( maxLines: 10, controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.subtitle1!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, textAlign: TextAlign.right, selectionControls: materialTextSelectionHandleControls, magnifierConfiguration: magnifierConfiguration, ); }, ), ), ), )); await tester.pump(); // Wait for autofocus to take effect. void checkMagnifierKey(Key testKey) { final EditableText editableText = tester.widget(find.byType(EditableText)); final BuildContext context = tester.firstElement(find.byType(EditableText)); final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); expect( editableText.magnifierConfiguration.magnifierBuilder( context, MagnifierController(), magnifierInfo, ), isA<Widget>().having( (Widget widget) => widget.key, 'built magnifier key equal to passed in magnifier key', equals(testKey), ), ); } checkMagnifierKey(keyOne); setState(() { key = keyTwo; }); await tester.pumpAndSettle(); checkMagnifierKey(keyTwo); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); group('Spell check', () { testWidgets( 'Spell check configured properly when spell check disabled by default', (WidgetTester tester) async { controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.spellCheckEnabled, isFalse); }); testWidgets( 'Spell check configured properly when spell check disabled manually', (WidgetTester tester) async { controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: const SpellCheckConfiguration.disabled(), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.spellCheckEnabled, isFalse); }); testWidgets( 'Error thrown when spell check configuration defined without specifying misspelled text style', (WidgetTester tester) async { controller.text = 'A'; expect( () { EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: const SpellCheckConfiguration(), ); }, throwsAssertionError, ); }); testWidgets( 'Spell check configured properly when spell check enabled without specified spell check service and native spell check service defined', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.spellCheckEnabled, isTrue); expect( state.spellCheckConfiguration.spellCheckService.runtimeType, equals(DefaultSpellCheckService), ); tester.binding.platformDispatcher.clearNativeSpellCheckServiceDefined(); }); testWidgets( 'Spell check configured properly with specified spell check service', (WidgetTester tester) async { final FakeSpellCheckService fakeSpellCheckService = FakeSpellCheckService(); controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: SpellCheckConfiguration( spellCheckService: fakeSpellCheckService, misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect( state.spellCheckConfiguration.spellCheckService.runtimeType, equals(FakeSpellCheckService), ); }); testWidgets( 'Spell check disabled when spell check configuration specified but no default spell check service available', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = false; controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ) ); expect(tester.takeException(), isA<AssertionError>()); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.spellCheckConfiguration, equals(const SpellCheckConfiguration.disabled())); tester.binding.platformDispatcher.clearNativeSpellCheckServiceDefined(); }); testWidgets( 'findSuggestionSpanAtCursorIndex finds correct span with cursor in middle of a word', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); const int cursorIndex = 21; const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']); const List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[ SuggestionSpan( TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), expectedSpan, SuggestionSpan( TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), ]; // Omitting actual text in results for brevity. Same for following tests that test the findSuggestionSpanAtCursorIndex method. state.spellCheckResults = const SpellCheckResults('', suggestionSpans); final SuggestionSpan? suggestionSpan = state.findSuggestionSpanAtCursorIndex(cursorIndex); expect(suggestionSpan, equals(expectedSpan)); }); testWidgets( 'findSuggestionSpanAtCursorIndex finds correct span with cursor on edge of a word', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); const int cursorIndex = 23; const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']); const List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[ SuggestionSpan( TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), expectedSpan, SuggestionSpan( TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), ]; state.spellCheckResults = const SpellCheckResults('', suggestionSpans); final SuggestionSpan? suggestionSpan = state.findSuggestionSpanAtCursorIndex(cursorIndex); expect(suggestionSpan, equals(expectedSpan)); }); testWidgets( 'findSuggestionSpanAtCursorIndex finds no span when cursor out of range of spans', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); const int cursorIndex = 33; const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']); const List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[ SuggestionSpan( TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), expectedSpan, SuggestionSpan( TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), ]; state.spellCheckResults = const SpellCheckResults('', suggestionSpans); final SuggestionSpan? suggestionSpan = state.findSuggestionSpanAtCursorIndex(cursorIndex); expect(suggestionSpan, isNull); }); testWidgets( 'findSuggestionSpanAtCursorIndex finds no span when word correctly spelled', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.text = 'A'; await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); const int cursorIndex = 5; const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']); const List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[ SuggestionSpan( TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), expectedSpan, SuggestionSpan( TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), ]; state.spellCheckResults = const SpellCheckResults('', suggestionSpans); final SuggestionSpan? suggestionSpan = state.findSuggestionSpanAtCursorIndex(cursorIndex); expect(suggestionSpan, isNull); }); testWidgets('can show spell check suggestions toolbar when there are spell check results', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; const TextEditingValue value = TextEditingValue( text: 'tset test test', selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), ); controller.value = value; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, spellCheckSuggestionsToolbarBuilder: TextField.defaultSpellCheckSuggestionsToolbarBuilder, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Can't show the toolbar when there's no focus. expect(state.showSpellCheckSuggestionsToolbar(), false); await tester.pumpAndSettle(); expect(find.text('DELETE'), findsNothing); // Can't show the toolbar when there are no spell check results. expect(state.showSpellCheckSuggestionsToolbar(), false); await tester.pumpAndSettle(); expect(find.text('test'), findsNothing); expect(find.text('sets'), findsNothing); expect(find.text('set'), findsNothing); expect(find.text('DELETE'), findsNothing); // Can show the toolbar when there are spell check results. state.spellCheckResults = const SpellCheckResults('test tset test', <SuggestionSpan>[SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set'])]); state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pumpAndSettle(); // Toolbar will only show on non-web platforms. expect(state.showSpellCheckSuggestionsToolbar(), !kIsWeb); await tester.pumpAndSettle(); const Matcher matcher = kIsWeb ? findsNothing : findsOneWidget; expect(find.text('test'), matcher); expect(find.text('sets'), matcher); expect(find.text('set'), matcher); expect(find.text('DELETE'), matcher); }); testWidgets('can show spell check suggestions toolbar when there are no spell check results on iOS', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; const TextEditingValue value = TextEditingValue( text: 'tset test test', selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), ); controller.value = value; await tester.pumpWidget( CupertinoApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: CupertinoTextField.cupertinoMisspelledTextStyle, spellCheckSuggestionsToolbarBuilder: CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Can't show the toolbar when there's no focus. expect(state.showSpellCheckSuggestionsToolbar(), false); await tester.pumpAndSettle(); expect(find.byType(CupertinoTextSelectionToolbarButton), findsNothing); // Can't show the toolbar when there are no spell check results. expect(state.showSpellCheckSuggestionsToolbar(), false); await tester.pumpAndSettle(); expect(find.byType(CupertinoTextSelectionToolbarButton), findsNothing); // Shows 'No Replacements Found' when there are spell check results but no // suggestions. state.spellCheckResults = const SpellCheckResults('test tset test', <SuggestionSpan>[SuggestionSpan(TextRange(start: 0, end: 4), <String>[])]); state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pumpAndSettle(); // Toolbar will only show on non-web platforms. expect(state.showSpellCheckSuggestionsToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.byType(CupertinoTextSelectionToolbarButton), findsOneWidget); expect(find.byType(CupertinoButton), findsOneWidget); expect(find.text('No Replacements Found'), findsOneWidget); final CupertinoButton button = tester.widget(find.byType(CupertinoButton)); expect(button.enabled, isFalse); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), skip: kIsWeb, // [intended] ); testWidgets('cupertino spell check suggestions toolbar buttons correctly change the composing region', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; const TextEditingValue value = TextEditingValue( text: 'tset test test', selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), ); controller.value = value; await tester.pumpWidget( CupertinoApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: cupertinoTextSelectionControls, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: CupertinoTextField.cupertinoMisspelledTextStyle, spellCheckSuggestionsToolbarBuilder: CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.spellCheckResults = const SpellCheckResults('tset test test', <SuggestionSpan>[SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set'])]); state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pumpAndSettle(); // Set last tap down position so that selecting the word edge will be // a valid operation. final Offset pos1 = textOffsetToPosition(tester, 1); final TestGesture gesture = await tester.startGesture(pos1); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(state.currentTextEditingValue.selection.baseOffset, equals(1)); // Test that tapping misspelled word replacement buttons will replace // the correct word and select the word edge. state.showSpellCheckSuggestionsToolbar(); await tester.pumpAndSettle(); if (kIsWeb) { expect(find.text('sets'), findsNothing); } else { expect(find.text('sets'), findsOneWidget); await tester.tap(find.text('sets')); await tester.pumpAndSettle(); expect(state.currentTextEditingValue.text, equals('sets test test')); expect(state.currentTextEditingValue.selection.baseOffset, equals(4)); } }); testWidgets('material spell check suggestions toolbar buttons correctly change the composing region', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; const TextEditingValue value = TextEditingValue( text: 'tset test test', composing: TextRange(start: 0, end: 4), selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), ); controller.value = value; await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, spellCheckSuggestionsToolbarBuilder: TextField.defaultSpellCheckSuggestionsToolbarBuilder, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.spellCheckResults = const SpellCheckResults('tset test test', <SuggestionSpan>[SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set'])]); state.renderEditable.selectWordsInRange( from: Offset.zero, cause: SelectionChangedCause.tap, ); await tester.pumpAndSettle(); expect(state.currentTextEditingValue.selection.baseOffset, equals(0)); // Test misspelled word replacement buttons. state.showSpellCheckSuggestionsToolbar(); await tester.pumpAndSettle(); if (kIsWeb) { expect(find.text('sets'), findsNothing); } else { expect(find.text('sets'), findsOneWidget); await tester.tap(find.text('sets')); await tester.pumpAndSettle(); expect(state.currentTextEditingValue.text, equals('sets test test')); expect(state.currentTextEditingValue.selection.baseOffset, equals(0)); } // Test delete button. state.showSpellCheckSuggestionsToolbar(); await tester.pumpAndSettle(); if (kIsWeb) { expect(find.text('DELETE'), findsNothing); } else { expect(find.text('DELETE'), findsOneWidget); await tester.tap(find.text('DELETE')); await tester.pumpAndSettle(); expect(state.currentTextEditingValue.text, equals(' test test')); expect(state.currentTextEditingValue.selection.baseOffset, equals(0)); } }); testWidgets('replacing puts cursor at the end of the word', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.value = const TextEditingValue( // All misspellings of "test". One the same length, one shorter, and one // longer. text: 'tset tst testt', selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), ); await tester.pumpWidget( CupertinoApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: CupertinoTextField.cupertinoMisspelledTextStyle, spellCheckSuggestionsToolbarBuilder: CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.spellCheckResults = SpellCheckResults( controller.value.text, const <SuggestionSpan>[ SuggestionSpan(TextRange(start: 0, end: 4), <String>['test']), SuggestionSpan(TextRange(start: 5, end: 8), <String>['test']), SuggestionSpan(TextRange(start: 9, end: 13), <String>['test']), ]); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(state.showSpellCheckSuggestionsToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('test'), findsOneWidget); // Replacing a word of the same length as the replacement puts the cursor // at the end of the new word. await tester.tap(find.text('test')); await tester.pumpAndSettle(); expect( controller.value, equals(const TextEditingValue( text: 'test tst testt', selection: TextSelection.collapsed( offset: 4, ), )), ); state.spellCheckResults = SpellCheckResults( controller.value.text, const <SuggestionSpan>[ SuggestionSpan(TextRange(start: 5, end: 8), <String>['test']), SuggestionSpan(TextRange(start: 9, end: 13), <String>['test']), ]); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(state.showSpellCheckSuggestionsToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('test'), findsOneWidget); // Replacing a word of less length as the replacement puts the cursor at // the end of the new word. await tester.tap(find.text('test')); await tester.pumpAndSettle(); expect( controller.value, equals(const TextEditingValue( text: 'test test testt', selection: TextSelection.collapsed( offset: 9, ), )), ); state.spellCheckResults = SpellCheckResults( controller.value.text, const <SuggestionSpan>[ SuggestionSpan(TextRange(start: 10, end: 15), <String>['test']), ]); await tester.tapAt(textOffsetToPosition(tester, 10)); await tester.pumpAndSettle(); expect(state.showSpellCheckSuggestionsToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('test'), findsOneWidget); // Replacing a word of greater length as the replacement puts the cursor // at the end of the new word. await tester.tap(find.text('test')); await tester.pumpAndSettle(); expect( controller.value, equals(const TextEditingValue( text: 'test test test', selection: TextSelection.collapsed( offset: 14, ), )), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: kIsWeb, // [intended] ); testWidgets('tapping on a misspelled word hides the handles', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.value = const TextEditingValue( // All misspellings of "test". One the same length, one shorter, and one // longer. text: 'test test testt', selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), ); await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, showSelectionHandles: true, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, spellCheckSuggestionsToolbarBuilder: TextField.defaultSpellCheckSuggestionsToolbarBuilder, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.spellCheckResults = SpellCheckResults( controller.value.text, const <SuggestionSpan>[ SuggestionSpan(TextRange(start: 10, end: 15), <String>['test']), ]); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(state.showSpellCheckSuggestionsToolbar(), isFalse); await tester.pumpAndSettle(); expect(find.text('test'), findsNothing); expect(state.selectionOverlay!.handlesAreVisible, isTrue); await tester.tapAt(textOffsetToPosition(tester, 12)); await tester.pumpAndSettle(); expect(state.showSpellCheckSuggestionsToolbar(), isTrue); await tester.pumpAndSettle(); expect(find.text('test'), findsOneWidget); expect(state.selectionOverlay!.handlesAreVisible, isFalse); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(state.showSpellCheckSuggestionsToolbar(), isFalse); await tester.pumpAndSettle(); expect(find.text('test'), findsNothing); expect(state.selectionOverlay!.handlesAreVisible, isTrue); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), skip: kIsWeb, // [intended] ); }); group('magnifier', () { testWidgets('should build nothing by default', (WidgetTester tester) async { final EditableText editableText = EditableText( controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, ); await tester.pumpWidget( MaterialApp( home: editableText, ), ); final BuildContext context = tester.firstElement(find.byType(EditableText)); final ValueNotifier<MagnifierInfo> notifier = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); addTearDown(notifier.dispose); expect( editableText.magnifierConfiguration.magnifierBuilder( context, MagnifierController(), notifier, ), isNull, ); }); }); // Regression test for: https://github.com/flutter/flutter/issues/117418. testWidgets('can handle the partial selection of a multi-code-unit glyph', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, showSelectionHandles: true, autofocus: true, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, minLines: 2, maxLines: 2, ), ), ); await tester.enterText(find.byType(EditableText), '12345'); await tester.pumpAndSettle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.userUpdateTextEditingValue( const TextEditingValue( // This is an extended grapheme cluster made up of several code units, // which has length 8. A selection from 0-1 does not fully select it. text: '👨‍👩‍👦', selection: TextSelection( baseOffset: 0, extentOffset: 1, ), ), SelectionChangedCause.keyboard, ); await tester.pumpAndSettle(); expect(tester.takeException(), null); }); testWidgets('does not crash when didChangeMetrics is called after unmounting', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Disposes the EditableText. await tester.pumpWidget(const Placeholder()); // Shouldn't crash. state.didChangeMetrics(); }); testWidgets('_CompositionCallback widget does not skip frames', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; controller.value = const TextEditingValue(selection: TextSelection.collapsed(offset: 0)); Offset offset = Offset.zero; late StateSetter setState; await tester.pumpWidget( MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter stateSetter) { setState = stateSetter; return Transform.translate( offset: offset, // The EditableText is configured in a way that the it doesn't // explicitly request repaint on focus change. child: TickerMode( enabled: false, child: RepaintBoundary( child: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(), showCursor: false, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ), ); }, ), ), ); focusNode.requestFocus(); await tester.pump(); tester.testTextInput.log.clear(); // The composition callback should be registered. To verify, change the // parent layer's transform. setState(() { offset = const Offset(42, 0); }); await tester.pump(); expect( tester.testTextInput.log, contains( matchesMethodCall( 'TextInput.setEditableSizeAndTransform', args: containsPair('transform', Matrix4.translationValues(offset.dx, offset.dy, 0).storage), ), ), ); EditableText.debugDeterministicCursor = false; }); group('selection behavior when receiving focus', () { testWidgets('tabbing between fields', (WidgetTester tester) async { final TextEditingController controller1 = TextEditingController(); addTearDown(controller1.dispose); final TextEditingController controller2 = TextEditingController(); addTearDown(controller2.dispose); controller1.text = 'Text1'; controller2.text = 'Text2\nLine2'; final FocusNode focusNode1 = FocusNode(); addTearDown(focusNode1.dispose); final FocusNode focusNode2 = FocusNode(); addTearDown(focusNode2.dispose); await tester.pumpWidget( MaterialApp( home: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ EditableText( key: ValueKey<String>(controller1.text), controller: controller1, focusNode: focusNode1, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), const SizedBox(height: 200.0), EditableText( key: ValueKey<String>(controller2.text), controller: controller2, focusNode: focusNode2, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, minLines: 10, maxLines: 20, ), const SizedBox(height: 100.0), ], ), ), ); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isFalse); expect( controller1.selection, const TextSelection.collapsed(offset: -1), ); expect( controller2.selection, const TextSelection.collapsed(offset: -1), ); // Tab to the first field (single line). await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect( controller1.selection, kIsWeb ? TextSelection( baseOffset: 0, extentOffset: controller1.text.length, ) : TextSelection.collapsed( offset: controller1.text.length, ), ); // Move the cursor to another position in the first field. await tester.tapAt(textOffsetToPosition(tester, controller1.text.length - 1)); await tester.pumpAndSettle(); expect( controller1.selection, TextSelection.collapsed( offset: controller1.text.length - 1, ), ); // Tab to the second field (multiline). await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); expect( controller2.selection, TextSelection.collapsed( offset: controller2.text.length, ), ); // Move the cursor to another position in the second field. await tester.tapAt(textOffsetToPosition(tester, controller2.text.length - 1, index: 1)); await tester.pumpAndSettle(); expect( controller2.selection, TextSelection.collapsed( offset: controller2.text.length - 1, ), ); // On web, the document root is also focusable. if (kIsWeb) { await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isFalse); } // Tabbing again goes back to the first field and reselects the field. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect( controller1.selection, kIsWeb ? TextSelection( baseOffset: 0, extentOffset: controller1.text.length, ) : TextSelection.collapsed( offset: controller1.text.length - 1, ), ); // Tabbing to the second field again retains the moved selection. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); expect( controller2.selection, TextSelection.collapsed( offset: controller2.text.length - 1, ), ); }); testWidgets('Selection is updated when the field has focus and the new selection is invalid', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/120631. controller.text = 'Text'; await tester.pumpWidget( MaterialApp( home: EditableText( key: ValueKey<String>(controller.text), controller: controller, focusNode: focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ); expect(focusNode.hasFocus, isFalse); expect( controller.selection, const TextSelection.collapsed(offset: -1), ); // Tab to focus the field. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); expect( controller.selection, kIsWeb ? TextSelection( baseOffset: 0, extentOffset: controller.text.length, ) : TextSelection.collapsed( offset: controller.text.length, ), ); // Update text without specifying the selection. controller.text = 'Updated'; // As the TextField is focused the selection should be automatically adjusted. expect(focusNode.hasFocus, isTrue); expect( controller.selection, kIsWeb ? TextSelection( baseOffset: 0, extentOffset: controller.text.length, ) : TextSelection.collapsed( offset: controller.text.length, ), ); }); testWidgets('when having focus stolen between frames on web', (WidgetTester tester) async { controller.text = 'Text1'; final FocusNode focusNode1 = FocusNode(); addTearDown(focusNode1.dispose); final FocusNode focusNode2 = FocusNode(); addTearDown(focusNode2.dispose); await tester.pumpWidget( MaterialApp( home: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ EditableText( key: ValueKey<String>(controller.text), controller: controller, focusNode: focusNode1, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), const SizedBox(height: 200.0), Focus( focusNode: focusNode2, child: const SizedBox.shrink(), ), const SizedBox(height: 100.0), ], ), ), ); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isFalse); expect( controller.selection, const TextSelection.collapsed(offset: -1), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText).first); // Set the text editing value in order to trigger an internal call to // requestFocus. state.userUpdateTextEditingValue( controller.value, SelectionChangedCause.keyboard, ); // Focus takes a frame to update, so it hasn't changed yet. expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isFalse); // Before EditableText's listener on widget.focusNode can be called, change // the focus again focusNode2.requestFocus(); await tester.pump(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); // Focus the EditableText again, which should cause the field to be selected // on web. focusNode1.requestFocus(); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect( controller.selection, TextSelection( baseOffset: 0, extentOffset: controller.text.length, ), ); }, skip: !kIsWeb, // [intended] ); }); testWidgets('EditableText respects MediaQuery.boldText', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(boldText: true), child: EditableText( controller: controller, focusNode: focusNode, style: const TextStyle(fontWeight: FontWeight.normal), cursorColor: Colors.red, backgroundCursorColor: Colors.green, ), ), )); controller.text = 'foo'; final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.buildTextSpan().style!.fontWeight, FontWeight.bold); }); testWidgets('code points are treated as single characters in obscure mode', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, toolbarOptions: const ToolbarOptions( copy: true, cut: true, paste: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); await tester.tap(find.byType(EditableText)); await tester.enterText(find.byType(EditableText), '👨‍👩‍👦'); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.textEditingValue.text, '👨‍👩‍👦'); // 👨‍👩‍👦| expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 8), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); // 👨‍👩‍|👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); // 👨‍👩|‍👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 5), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); // 👨‍|👩‍👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 3), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); // 👨|‍👩‍👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 2), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); // |👨‍👩‍👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 0), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); // 👨|‍👩‍👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 2), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); // 👨‍|👩‍👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 3), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); // 👨‍👩|‍👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 5), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); // 👨‍👩‍|👦 expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); // 👨‍👩‍👦| expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 8), ); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, '👨‍👩‍'); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, '👨‍👩'); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, '👨‍'); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, '👨'); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, ''); }, skip: kIsWeb, // [intended] ); testWidgets('when manually placing the cursor in the middle of a code point', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, toolbarOptions: const ToolbarOptions( copy: true, cut: true, paste: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); await tester.tap(find.byType(EditableText)); await tester.enterText(find.byType(EditableText), '👨‍👩‍👦'); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.textEditingValue.text, '👨‍👩‍👦'); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 8), ); // Place the cursor in the middle of the last code point, which consists of // two code units. await tester.tapAt(textOffsetToPosition(tester, 7)); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 7), ); // Using the arrow keys moves out of the code unit. await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); await tester.tapAt(textOffsetToPosition(tester, 7)); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 7), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 8), ); // Pressing delete doesn't delete only the left code unit, it deletes the // entire code point (both code units, one to the left and one to the right // of the cursor). await tester.tapAt(textOffsetToPosition(tester, 7)); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 7), ); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, '👨‍👩‍'); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); }, skip: kIsWeb, // [intended] ); testWidgets('when inserting a malformed string', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, toolbarOptions: const ToolbarOptions( copy: true, cut: true, paste: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); await tester.tap(find.byType(EditableText)); // This malformed string is the result of removing the final code unit from // the extended grapheme cluster "👨‍👩‍👦", so that the final // surrogate pair (the "👦" emoji or "\uD83D\uDC66"), only has its high // surrogate. await tester.enterText(find.byType(EditableText), '👨‍👩‍\uD83D'); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.textEditingValue.text, '👨‍👩‍\uD83D'); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 7), ); // The dangling high surrogate is treated as a single rune. await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 7), ); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, '👨‍👩‍'); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); }, skip: kIsWeb, // [intended] ); testWidgets('when inserting a malformed string that is a sequence of dangling high surrogates', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, toolbarOptions: const ToolbarOptions( copy: true, cut: true, paste: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); await tester.tap(find.byType(EditableText)); // This string is the high surrogate from the emoji "👦" ("\uD83D\uDC66"), // repeated. await tester.enterText(find.byType(EditableText), '\uD83D\uD83D\uD83D\uD83D\uD83D\uD83D'); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.textEditingValue.text, '\uD83D\uD83D\uD83D\uD83D\uD83D\uD83D'); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); // Each dangling high surrogate is treated as a single character. await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 5), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, '\uD83D\uD83D\uD83D\uD83D\uD83D'); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 5), ); }, skip: kIsWeb, // [intended] ); testWidgets('when inserting a malformed string that is a sequence of dangling low surrogates', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, toolbarOptions: const ToolbarOptions( copy: true, cut: true, paste: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); await tester.tap(find.byType(EditableText)); // This string is the low surrogate from the emoji "👦" ("\uD83D\uDC66"), // repeated. await tester.enterText(find.byType(EditableText), '\uDC66\uDC66\uDC66\uDC66\uDC66\uDC66'); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.textEditingValue.text, '\uDC66\uDC66\uDC66\uDC66\uDC66\uDC66'); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); // Each dangling high surrogate is treated as a single character. await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 5), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 6), ); await tester.sendKeyEvent(LogicalKeyboardKey.backspace); await tester.pump(); expect(state.textEditingValue.text, '\uDC66\uDC66\uDC66\uDC66\uDC66'); expect( state.textEditingValue.selection, const TextSelection.collapsed(offset: 5), ); }, skip: kIsWeb, // [intended] ); group('hasStrings', () { late int calls; setUp(() { calls = 0; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) { if (methodCall.method == 'Clipboard.hasStrings') { calls += 1; } return Future<void>.value(); }); }); tearDown(() { TestWidgetsFlutterBinding.ensureInitialized() .defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); }); testWidgets('web avoids the paste permissions prompt by not calling hasStrings', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, obscureText: true, toolbarOptions: const ToolbarOptions( copy: true, cut: true, paste: true, selectAll: true, ), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, ), ), ); expect(calls, equals(kIsWeb ? 0 : 1)); // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(calls, equals(kIsWeb ? 0 : 2)); }); }); testWidgets('Cursor color with an opacity is respected', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); const double opacity = 0.55; controller.text = 'blah blah'; await tester.pumpWidget( MaterialApp( home: EditableText( key: key, cursorColor: cursorColor.withOpacity(opacity), backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, ), ), ); // Tap to show the cursor. await tester.tap(find.byKey(key)); await tester.pumpAndSettle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.renderEditable.cursorColor, cursorColor.withOpacity(opacity)); }); testWidgets('should notify on size change', (WidgetTester tester) async { int notifyCount = 0; await tester.pumpWidget(MaterialApp( home: Scaffold( body: NotificationListener<SizeChangedLayoutNotification>( onNotification: (SizeChangedLayoutNotification notification) { notifyCount += 1; return false; }, child: EditableText( backgroundCursorColor: Colors.grey, cursorColor: Colors.grey, controller: controller, focusNode: focusNode, maxLines: 3, minLines: 1, style: textStyle, ), ), ), )); expect(notifyCount, equals(0)); await tester.enterText(find.byType(EditableText), '\n'); await tester.pumpAndSettle(); expect(notifyCount, equals(1)); }); testWidgets('ShowCaretOnScreen is correctly scheduled within a SliverMainAxisGroup', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final Widget widget = MaterialApp( home: Scaffold( body: CustomScrollView( controller: scrollController, slivers: const <Widget>[ SliverMainAxisGroup( slivers: <Widget>[ SliverToBoxAdapter( child: SizedBox( height: 600, ), ), SliverToBoxAdapter( child: SizedBox( height: 44, child: TextField(), ), ), SliverToBoxAdapter( child: SizedBox( height: 500, ), ), ], ) ], ), ), ); await tester.pumpWidget(widget); await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); expect(scrollController.offset, 75.0); }); } class UnsettableController extends TextEditingController { @override set value(TextEditingValue v) { // Do nothing for set, which causes selection to remain as -1, -1. } } class MockTextFormatter extends TextInputFormatter { MockTextFormatter() : formatCallCount = 0, log = <String>[]; int formatCallCount; List<String> log; late TextEditingValue lastOldValue; late TextEditingValue lastNewValue; @override TextEditingValue formatEditUpdate( TextEditingValue oldValue, TextEditingValue newValue, ) { lastOldValue = oldValue; lastNewValue = newValue; formatCallCount++; log.add('[$formatCallCount]: ${oldValue.text}, ${newValue.text}'); TextEditingValue finalValue; if (newValue.text.length < oldValue.text.length) { finalValue = _handleTextDeletion(oldValue, newValue); } else { finalValue = _formatText(newValue); } return finalValue; } TextEditingValue _handleTextDeletion(TextEditingValue oldValue, TextEditingValue newValue) { final String result = 'a' * (formatCallCount - 2); log.add('[$formatCallCount]: deleting $result'); return TextEditingValue(text: newValue.text, selection: newValue.selection, composing: newValue.composing); } TextEditingValue _formatText(TextEditingValue value) { final String result = 'a' * formatCallCount * 2; log.add('[$formatCallCount]: normal $result'); return TextEditingValue(text: value.text, selection: value.selection, composing: value.composing); } } class MockTextSelectionControls extends Fake implements TextSelectionControls { @override Widget buildToolbar( BuildContext context, Rect globalEditableRegion, double textLineHeight, Offset position, List<TextSelectionPoint> endpoints, TextSelectionDelegate delegate, ValueListenable<ClipboardStatus>? clipboardStatus, Offset? lastSecondaryTapDownPosition, ) { return const SizedBox(); } @override Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { return const SizedBox(); } @override Size getHandleSize(double textLineHeight) { return Size.zero; } @override Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) { return Offset.zero; } bool testCanCut = false; bool testCanCopy = false; bool testCanPaste = false; int cutCount = 0; int pasteCount = 0; int copyCount = 0; @override void handleCopy(TextSelectionDelegate delegate) { copyCount += 1; } @override Future<void> handlePaste(TextSelectionDelegate delegate) async { pasteCount += 1; } @override void handleCut(TextSelectionDelegate delegate) { cutCount += 1; } @override bool canCut(TextSelectionDelegate delegate) { return testCanCut; } @override bool canCopy(TextSelectionDelegate delegate) { return testCanCopy; } @override bool canPaste(TextSelectionDelegate delegate) { return testCanPaste; } } // Fake text selection controls that call a callback when paste happens. class _CustomTextSelectionControls extends TextSelectionControls { _CustomTextSelectionControls({ this.onPaste, this.onCut, }); static const double _kToolbarContentDistance = 8.0; final VoidCallback? onPaste; final VoidCallback? onCut; @override Widget buildToolbar( BuildContext context, Rect globalEditableRegion, double textLineHeight, Offset position, List<TextSelectionPoint> endpoints, TextSelectionDelegate delegate, ValueListenable<ClipboardStatus>? clipboardStatus, Offset? lastSecondaryTapDownPosition, ) { final Offset selectionMidpoint = position; final TextSelectionPoint startTextSelectionPoint = endpoints[0]; final TextSelectionPoint endTextSelectionPoint = endpoints.length > 1 ? endpoints[1] : endpoints[0]; final Offset anchorAbove = Offset( globalEditableRegion.left + selectionMidpoint.dx, globalEditableRegion.top + startTextSelectionPoint.point.dy - textLineHeight - _kToolbarContentDistance ); final Offset anchorBelow = Offset( globalEditableRegion.left + selectionMidpoint.dx, globalEditableRegion.top + endTextSelectionPoint.point.dy + TextSelectionToolbar.kToolbarContentDistanceBelow, ); return _CustomTextSelectionToolbar( anchorAbove: anchorAbove, anchorBelow: anchorBelow, handlePaste: () => handlePaste(delegate), handleCut: () => handleCut(delegate), ); } @override Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { return Container(); } @override Size getHandleSize(double textLineHeight) { return Size.zero; } @override Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) { return Offset.zero; } @override bool canCut(TextSelectionDelegate delegate) { return true; } @override bool canPaste(TextSelectionDelegate delegate) { return true; } @override Future<void> handlePaste(TextSelectionDelegate delegate) { onPaste?.call(); return super.handlePaste(delegate); } @override void handleCut(TextSelectionDelegate delegate, [ClipboardStatusNotifier? clipboardStatus]) { onCut?.call(); return super.handleCut(delegate); } } // A fake text selection toolbar with only a paste button. class _CustomTextSelectionToolbar extends StatelessWidget { const _CustomTextSelectionToolbar({ required this.anchorAbove, required this.anchorBelow, this.handlePaste, this.handleCut, }); final Offset anchorAbove; final Offset anchorBelow; final VoidCallback? handlePaste; final VoidCallback? handleCut; @override Widget build(BuildContext context) { return TextSelectionToolbar( anchorAbove: anchorAbove, anchorBelow: anchorBelow, toolbarBuilder: (BuildContext context, Widget child) { return ColoredBox( color: Colors.pink, child: child, ); }, children: <Widget>[ TextSelectionToolbarTextButton( padding: TextSelectionToolbarTextButton.getPadding(0, 2), onPressed: handleCut, child: const Text('Cut'), ), TextSelectionToolbarTextButton( padding: TextSelectionToolbarTextButton.getPadding(1, 2), onPressed: handlePaste, child: const Text('Paste'), ), ], ); } } class CustomStyleEditableText extends EditableText { CustomStyleEditableText({ super.key, required super.controller, required super.cursorColor, required super.focusNode, required super.style, }) : super( backgroundCursorColor: Colors.grey, ); @override CustomStyleEditableTextState createState() => CustomStyleEditableTextState(); } class CustomStyleEditableTextState extends EditableTextState { @override TextSpan buildTextSpan() { return TextSpan( style: const TextStyle(fontStyle: FontStyle.italic), text: widget.controller.value.text, ); } } class TransformedEditableText extends StatefulWidget { const TransformedEditableText({ super.key, required this.offset, required this.transformButtonKey, }); final Offset offset; final Key transformButtonKey; @override State<TransformedEditableText> createState() => _TransformedEditableTextState(); } class _TransformedEditableTextState extends State<TransformedEditableText> { bool _isTransformed = false; final TextEditingController _controller = TextEditingController(); final FocusNode _focusNode = FocusNode(); @override void dispose() { _controller.dispose(); _focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Transform.translate( offset: _isTransformed ? widget.offset : Offset.zero, child: EditableText( controller: _controller, focusNode: _focusNode, style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), ), ElevatedButton( key: widget.transformButtonKey, onPressed: () { setState(() { _isTransformed = !_isTransformed; }); }, child: const Text('Toggle Transform'), ), ], ), ), ); } } class NoImplicitScrollPhysics extends AlwaysScrollableScrollPhysics { const NoImplicitScrollPhysics({ super.parent }); @override bool get allowImplicitScrolling => false; @override NoImplicitScrollPhysics applyTo(ScrollPhysics? ancestor) { return NoImplicitScrollPhysics(parent: buildParent(ancestor)); } } class SkipPainting extends SingleChildRenderObjectWidget { const SkipPainting({ super.key, required Widget super.child }); @override SkipPaintingRenderObject createRenderObject(BuildContext context) => SkipPaintingRenderObject(); } class SkipPaintingRenderObject extends RenderProxyBox { @override void paint(PaintingContext context, Offset offset) { } } class _AccentColorTextEditingController extends TextEditingController { _AccentColorTextEditingController(String text) : super(text: text); @override TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing, SpellCheckConfiguration? spellCheckConfiguration}) { final Color color = Theme.of(context).colorScheme.secondary; return super.buildTextSpan(context: context, style: TextStyle(color: color), withComposing: withComposing); } } class _TestScrollController extends ScrollController { bool get attached => hasListeners; } class FakeSpellCheckService extends DefaultSpellCheckService {}
flutter/packages/flutter/test/widgets/editable_text_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/editable_text_test.dart", "repo_id": "flutter", "token_count": 243294 }
686
// 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/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { testWidgets('Vertical gesture detector has up/down actions', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); int callCount = 0; final GlobalKey detectorKey = GlobalKey(); await tester.pumpWidget( Center( child: GestureDetector( key: detectorKey, onVerticalDragStart: (DragStartDetails _) { callCount += 1; }, child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], )); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollRight); expect(callCount, 0); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollUp); expect(callCount, 1); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollDown); expect(callCount, 2); semantics.dispose(); }); testWidgets('Horizontal gesture detector has up/down actions', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); int callCount = 0; final GlobalKey detectorKey = GlobalKey(); await tester.pumpWidget( Center( child: GestureDetector( key: detectorKey, onHorizontalDragStart: (DragStartDetails _) { callCount += 1; }, child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], )); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollUp); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollDown); expect(callCount, 0); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); expect(callCount, 1); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollRight); expect(callCount, 2); semantics.dispose(); }); testWidgets('All registered handlers for the gesture kind are called', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Set<String> logs = <String>{}; final GlobalKey detectorKey = GlobalKey(); await tester.pumpWidget( Center( child: GestureDetector( key: detectorKey, onHorizontalDragStart: (_) { logs.add('horizontal'); }, onPanStart: (_) { logs.add('pan'); }, child: Container(), ), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); expect(logs, <String>{'horizontal', 'pan'}); semantics.dispose(); }); testWidgets('Replacing recognizers should update semantic handlers', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); // How the test is set up: // // * In the base state, RawGestureDetector's recognizer is a HorizontalGR // * Calling `introduceLayoutPerformer()` adds a `_TestLayoutPerformer` as // child of RawGestureDetector, which invokes a given callback during // layout phase. // * The aforementioned callback replaces the detector's recognizer with a // TapGR. // * This test makes sure the replacement correctly updates semantics. final Set<String> logs = <String>{}; final GlobalKey<RawGestureDetectorState> detectorKey = GlobalKey(); void performLayout() { detectorKey.currentState!.replaceGestureRecognizers(<Type, GestureRecognizerFactory>{ TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( () => TapGestureRecognizer(), (TapGestureRecognizer instance) { instance.onTap = () { logs.add('tap'); }; }, ), }); } bool hasLayoutPerformer = false; late VoidCallback introduceLayoutPerformer; await tester.pumpWidget( StatefulBuilder( builder: (BuildContext context, StateSetter setter) { introduceLayoutPerformer = () { setter(() { hasLayoutPerformer = true; }); }; return Center( child: RawGestureDetector( key: detectorKey, gestures: <Type, GestureRecognizerFactory>{ HorizontalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>( () => HorizontalDragGestureRecognizer(), (HorizontalDragGestureRecognizer instance) { instance.onStart = (_) { logs.add('horizontal'); }; }, ), }, child: hasLayoutPerformer ? _TestLayoutPerformer(performLayout: performLayout) : null, ), ); }, ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); expect(logs, <String>{'horizontal'}); logs.clear(); introduceLayoutPerformer(); await tester.pumpAndSettle(); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.tap); expect(logs, <String>{'tap'}); logs.clear(); semantics.dispose(); }); group("RawGestureDetector's custom semantics delegate", () { testWidgets('should update semantics notations when switching from the default delegate', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Map<Type, GestureRecognizerFactory> gestures = _buildGestureMap(() => LongPressGestureRecognizer(), null) ..addAll( _buildGestureMap(() => TapGestureRecognizer(), null)); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: gestures, child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.longPress, SemanticsAction.tap], )); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: gestures, semantics: _TestSemanticsGestureDelegate(onTap: () {}), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], )); semantics.dispose(); }); testWidgets('should update semantics notations when switching to the default delegate', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Map<Type, GestureRecognizerFactory> gestures = _buildGestureMap(() => LongPressGestureRecognizer(), null) ..addAll( _buildGestureMap(() => TapGestureRecognizer(), null)); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: gestures, semantics: _TestSemanticsGestureDelegate(onTap: () {}), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], )); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: gestures, child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.longPress, SemanticsAction.tap], )); semantics.dispose(); }); testWidgets('should update semantics notations when switching from a different custom delegate', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Map<Type, GestureRecognizerFactory> gestures = _buildGestureMap(() => LongPressGestureRecognizer(), null) ..addAll( _buildGestureMap(() => TapGestureRecognizer(), null)); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: gestures, semantics: _TestSemanticsGestureDelegate(onTap: () {}), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], )); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: gestures, semantics: _TestSemanticsGestureDelegate(onLongPress: () {}), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.longPress], )); semantics.dispose(); }); testWidgets('should correctly call callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> logs = <String>[]; final GlobalKey<RawGestureDetectorState> detectorKey = GlobalKey(); await tester.pumpWidget( Center( child: RawGestureDetector( key: detectorKey, semantics: _TestSemanticsGestureDelegate( onTap: () { logs.add('tap'); }, onLongPress: () { logs.add('longPress'); }, onHorizontalDragUpdate: (_) { logs.add('horizontal'); }, onVerticalDragUpdate: (_) { logs.add('vertical'); }, ), child: Container(), ), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.tap); expect(logs, <String>['tap']); logs.clear(); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.longPress); expect(logs, <String>['longPress']); logs.clear(); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); expect(logs, <String>['horizontal']); logs.clear(); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollUp); expect(logs, <String>['vertical']); logs.clear(); semantics.dispose(); }); }); group("RawGestureDetector's default semantics delegate", () { group('should map onTap to', () { testWidgets('null when there is no TapGR', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap(null, null), child: Container(), ), ), ); expect(semantics, isNot(includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], ))); semantics.dispose(); }); testWidgets('non-null when there is TapGR with no callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap( () => TapGestureRecognizer(), null, ), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], )); semantics.dispose(); }); testWidgets('a callback that correctly calls callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey detectorKey = GlobalKey(); final List<String> logs = <String>[]; await tester.pumpWidget( Center( child: RawGestureDetector( key: detectorKey, gestures: _buildGestureMap( () => TapGestureRecognizer(), (TapGestureRecognizer tap) { tap ..onTap = () {logs.add('tap');} ..onTapUp = (_) {logs.add('tapUp');} ..onTapDown = (_) {logs.add('tapDown');} ..onTapCancel = () {logs.add('WRONG');} ..onSecondaryTapDown = (_) {logs.add('WRONG');} ..onTertiaryTapDown = (_) {logs.add('WRONG');}; }, ), child: Container(), ), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.tap); expect(logs, <String>['tapDown', 'tapUp', 'tap']); semantics.dispose(); }); }); group('should map onLongPress to', () { testWidgets('null when there is no LongPressGR ', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap(null, null), child: Container(), ), ), ); expect(semantics, isNot(includesNodeWith( actions: <SemanticsAction>[SemanticsAction.longPress], ))); semantics.dispose(); }); testWidgets('non-null when there is LongPressGR with no callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap( () => LongPressGestureRecognizer(), null, ), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.longPress], )); semantics.dispose(); }); testWidgets('a callback that correctly calls callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey detectorKey = GlobalKey(); final List<String> logs = <String>[]; await tester.pumpWidget( Center( child: RawGestureDetector( key: detectorKey, gestures: _buildGestureMap( () => LongPressGestureRecognizer(), (LongPressGestureRecognizer longPress) { longPress ..onLongPress = () {logs.add('LP');} ..onLongPressStart = (_) {logs.add('LPStart');} ..onLongPressUp = () {logs.add('LPUp');} ..onLongPressEnd = (_) {logs.add('LPEnd');} ..onLongPressMoveUpdate = (_) {logs.add('WRONG');}; }, ), child: Container(), ), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.longPress); expect(logs, <String>['LPStart', 'LP', 'LPEnd', 'LPUp']); semantics.dispose(); }); }); group('should map onHorizontalDragUpdate to', () { testWidgets('null when there is no matching recognizers ', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap(null, null), child: Container(), ), ), ); expect(semantics, isNot(includesNodeWith( actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], ))); semantics.dispose(); }); testWidgets('non-null when there is either matching recognizer with no callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap( () => HorizontalDragGestureRecognizer(), null, ), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], )); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap( () => PanGestureRecognizer(), null, ), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[ SemanticsAction.scrollLeft, SemanticsAction.scrollRight, SemanticsAction.scrollDown, SemanticsAction.scrollUp, ], )); semantics.dispose(); }); testWidgets('a callback that correctly calls callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey detectorKey = GlobalKey(); final List<String> logs = <String>[]; final Map<Type, GestureRecognizerFactory> gestures = _buildGestureMap( () => HorizontalDragGestureRecognizer(), (HorizontalDragGestureRecognizer horizontal) { horizontal ..onStart = (_) {logs.add('HStart');} ..onDown = (_) {logs.add('HDown');} ..onEnd = (_) {logs.add('HEnd');} ..onUpdate = (_) {logs.add('HUpdate');} ..onCancel = () {logs.add('WRONG');}; }, )..addAll(_buildGestureMap( () => PanGestureRecognizer(), (PanGestureRecognizer pan) { pan ..onStart = (_) {logs.add('PStart');} ..onDown = (_) {logs.add('PDown');} ..onEnd = (_) {logs.add('PEnd');} ..onUpdate = (_) {logs.add('PUpdate');} ..onCancel = () {logs.add('WRONG');}; }, )); await tester.pumpWidget( Center( child: RawGestureDetector( key: detectorKey, gestures: gestures, child: Container(), ), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); expect(logs, <String>['HDown', 'HStart', 'HUpdate', 'HEnd', 'PDown', 'PStart', 'PUpdate', 'PEnd',]); logs.clear(); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); expect(logs, <String>['HDown', 'HStart', 'HUpdate', 'HEnd', 'PDown', 'PStart', 'PUpdate', 'PEnd',]); semantics.dispose(); }); }); group('should map onVerticalDragUpdate to', () { testWidgets('null when there is no matching recognizers ', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap(null, null), child: Container(), ), ), ); expect(semantics, isNot(includesNodeWith( actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], ))); semantics.dispose(); }); testWidgets('non-null when there is either matching recognizer with no callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap( () => VerticalDragGestureRecognizer(), null, ), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], )); // Pan has bene tested in Horizontal semantics.dispose(); }); testWidgets('a callback that correctly calls callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey detectorKey = GlobalKey(); final List<String> logs = <String>[]; final Map<Type, GestureRecognizerFactory> gestures = _buildGestureMap( () => VerticalDragGestureRecognizer(), (VerticalDragGestureRecognizer horizontal) { horizontal ..onStart = (_) {logs.add('VStart');} ..onDown = (_) {logs.add('VDown');} ..onEnd = (_) {logs.add('VEnd');} ..onUpdate = (_) {logs.add('VUpdate');} ..onCancel = () {logs.add('WRONG');}; }, )..addAll(_buildGestureMap( () => PanGestureRecognizer(), (PanGestureRecognizer pan) { pan ..onStart = (_) {logs.add('PStart');} ..onDown = (_) {logs.add('PDown');} ..onEnd = (_) {logs.add('PEnd');} ..onUpdate = (_) {logs.add('PUpdate');} ..onCancel = () {logs.add('WRONG');}; }, )); await tester.pumpWidget( Center( child: RawGestureDetector( key: detectorKey, gestures: gestures, child: Container(), ), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollUp); expect(logs, <String>['VDown', 'VStart', 'VUpdate', 'VEnd', 'PDown', 'PStart', 'PUpdate', 'PEnd',]); logs.clear(); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollDown); expect(logs, <String>['VDown', 'VStart', 'VUpdate', 'VEnd', 'PDown', 'PStart', 'PUpdate', 'PEnd',]); semantics.dispose(); }); }); testWidgets('should update semantics notations when receiving new gestures', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap(() => LongPressGestureRecognizer(), null), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.longPress], )); await tester.pumpWidget( Center( child: RawGestureDetector( gestures: _buildGestureMap(() => TapGestureRecognizer(), null), child: Container(), ), ), ); expect(semantics, includesNodeWith( actions: <SemanticsAction>[SemanticsAction.tap], )); semantics.dispose(); }); }); } class _TestLayoutPerformer extends SingleChildRenderObjectWidget { const _TestLayoutPerformer({ required this.performLayout, }); final VoidCallback performLayout; @override _RenderTestLayoutPerformer createRenderObject(BuildContext context) { return _RenderTestLayoutPerformer(performLayout: performLayout); } } class _RenderTestLayoutPerformer extends RenderBox { _RenderTestLayoutPerformer({required VoidCallback performLayout}) : _performLayout = performLayout; final VoidCallback _performLayout; @override Size computeDryLayout(BoxConstraints constraints) { return const Size(1, 1); } @override void performLayout() { size = const Size(1, 1); _performLayout(); } } Map<Type, GestureRecognizerFactory> _buildGestureMap<T extends GestureRecognizer>( GestureRecognizerFactoryConstructor<T>? constructor, GestureRecognizerFactoryInitializer<T>? initializer, ) { if (constructor == null) { return <Type, GestureRecognizerFactory>{}; } return <Type, GestureRecognizerFactory>{ T: GestureRecognizerFactoryWithHandlers<T>( constructor, initializer ?? (T o) {}, ), }; } class _TestSemanticsGestureDelegate extends SemanticsGestureDelegate { const _TestSemanticsGestureDelegate({ this.onTap, this.onLongPress, this.onHorizontalDragUpdate, this.onVerticalDragUpdate, }); final GestureTapCallback? onTap; final GestureLongPressCallback? onLongPress; final GestureDragUpdateCallback? onHorizontalDragUpdate; final GestureDragUpdateCallback? onVerticalDragUpdate; @override void assignSemantics(RenderSemanticsGestureHandler renderObject) { renderObject ..onTap = onTap ..onLongPress = onLongPress ..onHorizontalDragUpdate = onHorizontalDragUpdate ..onVerticalDragUpdate = onVerticalDragUpdate; } }
flutter/packages/flutter/test/widgets/gesture_detector_semantics_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/gesture_detector_semantics_test.dart", "repo_id": "flutter", "token_count": 11526 }
687
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'dart:async'; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Image at default filterQuality', (WidgetTester tester) async { await testImageQuality(tester, null); }); testWidgets('Image at high filterQuality', (WidgetTester tester) async { await testImageQuality(tester, ui.FilterQuality.high); }); testWidgets('Image at none filterQuality', (WidgetTester tester) async { await testImageQuality(tester, ui.FilterQuality.none); }); } Future<void> testImageQuality(WidgetTester tester, ui.FilterQuality? quality) async { await tester.binding.setSurfaceSize(const ui.Size(3, 3)); // A 3x3 image encoded as PNG with white background and black pixels on the diagonal: // ┌──────┐ // │▓▓ │ // │ ▓▓ │ // │ ▓▓│ // └──────┘ // At different levels of quality these pixels are blurred differently. final Uint8List test3x3Image = Uint8List.fromList(<int>[ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x08, 0x02, 0x00, 0x00, 0x00, 0xd9, 0x4a, 0x22, 0xe8, 0x00, 0x00, 0x00, 0x1b, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0x64, 0x60, 0x60, 0xf8, 0xff, 0xff, 0x3f, 0x03, 0x9c, 0xfa, 0xff, 0xff, 0x3f, 0xc3, 0xff, 0xff, 0xff, 0x21, 0x1c, 0x00, 0xcb, 0x70, 0x0e, 0xf3, 0x5d, 0x11, 0xc2, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, ]); final ui.Image image = (await tester.runAsync(() async { final ui.Codec codec = await ui.instantiateImageCodec(test3x3Image); return (await codec.getNextFrame()).image; }))!; addTearDown(image.dispose); expect(image.width, 3); expect(image.height, 3); final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); streamCompleter.setData(imageInfo: ImageInfo(image: image)); final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); await tester.pumpWidget( quality == null ? Image(image: imageProvider) : Image( image: imageProvider, filterQuality: quality, ), ); await expectLater( find.byType(Image), matchesGoldenFile('image_quality_${quality ?? 'default'}.png'), ); } class _TestImageStreamCompleter extends ImageStreamCompleter { ImageInfo? _currentImage; final Set<ImageStreamListener> listeners = <ImageStreamListener>{}; @override void addListener(ImageStreamListener listener) { listeners.add(listener); if (_currentImage != null) { listener.onImage(_currentImage!.clone(), true); } } @override void removeListener(ImageStreamListener listener) { listeners.remove(listener); } void setData({ ImageInfo? imageInfo, ImageChunkEvent? chunkEvent, }) { if (imageInfo != null) { _currentImage?.dispose(); _currentImage = imageInfo; } final List<ImageStreamListener> localListeners = listeners.toList(); for (final ImageStreamListener listener in localListeners) { if (imageInfo != null) { listener.onImage(imageInfo.clone(), false); } if (chunkEvent != null && listener.onChunk != null) { listener.onChunk!(chunkEvent); } } } void setError({ required Object exception, StackTrace? stackTrace, }) { final List<ImageStreamListener> localListeners = listeners.toList(); for (final ImageStreamListener listener in localListeners) { listener.onError?.call(exception, stackTrace); } } } class _TestImageProvider extends ImageProvider<Object> { _TestImageProvider({ImageStreamCompleter? streamCompleter}) { _streamCompleter = streamCompleter ?? OneFrameImageStreamCompleter(_completer.future); } final Completer<ImageInfo> _completer = Completer<ImageInfo>(); late ImageStreamCompleter _streamCompleter; bool get loadCalled => _loadCallCount > 0; int get loadCallCount => _loadCallCount; int _loadCallCount = 0; @override Future<Object> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<_TestImageProvider>(this); } @override ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) { _loadCallCount += 1; return _streamCompleter; } void complete(ui.Image image) { _completer.complete(ImageInfo(image: image)); } void fail(Object exception, StackTrace? stackTrace) { _completer.completeError(exception, stackTrace); } @override String toString() => '${describeIdentity(this)}()'; }
flutter/packages/flutter/test/widgets/image_filter_quality_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/image_filter_quality_test.dart", "repo_id": "flutter", "token_count": 1902 }
688
// 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 'dart:math' as math; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:vector_math/vector_math_64.dart' show Matrix4, Quad, Vector3; import 'gesture_utils.dart'; void main() { group('InteractiveViewer', () { late TransformationController transformationController; setUp(() { transformationController = TransformationController(); }); tearDown(() { transformationController.dispose(); }); testWidgets('child fits in viewport', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Attempting to drag to pan doesn't work because the child fits inside // the viewport and has a tight boundary. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); // Pinch to zoom works. final Offset scaleStart1 = childInterior; final Offset scaleStart2 = Offset(childInterior.dx + 10.0, childInterior.dy); final Offset scaleEnd1 = Offset(childInterior.dx - 10.0, childInterior.dy); final Offset scaleEnd2 = Offset(childInterior.dx + 20.0, childInterior.dy); gesture = await tester.createGesture(); final TestGesture gesture2 = await tester.createGesture(); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value, isNot(equals(Matrix4.identity()))); }); testWidgets('boundary slightly bigger than child', (WidgetTester tester) async { const double boundaryMargin = 10.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Dragging to pan works only until it hits the boundary. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, -boundaryMargin); expect(translation.y, -boundaryMargin); // Pinch to zoom also only works until expanding to the boundary. final Offset scaleStart1 = childInterior; final Offset scaleStart2 = Offset(childInterior.dx + 20.0, childInterior.dy); final Offset scaleEnd1 = Offset(scaleStart1.dx + 5.0, scaleStart1.dy); final Offset scaleEnd2 = Offset(scaleStart2.dx - 5.0, scaleStart2.dy); gesture = await tester.createGesture(); final TestGesture gesture2 = await tester.createGesture(); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); // The new scale is the scale that makes the original size (200.0) as big // as the boundary (220.0). expect(transformationController.value.getMaxScaleOnAxis(), 200.0 / 220.0); }); testWidgets('child bigger than viewport', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( constrained: false, scaleEnabled: false, transformationController: transformationController, child: const SizedBox(width: 2000.0, height: 2000.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Attempting to move against the boundary doesn't work. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); TestGesture gesture = await tester.startGesture(childOffset); await tester.pump(); await gesture.moveTo(childInterior); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); // Attempting to pinch to zoom doesn't work because it's disabled. final Offset scaleStart1 = childInterior; final Offset scaleStart2 = Offset(childInterior.dx + 10.0, childInterior.dy); final Offset scaleEnd1 = Offset(childInterior.dx - 10.0, childInterior.dy); final Offset scaleEnd2 = Offset(childInterior.dx + 20.0, childInterior.dy); gesture = await tester.startGesture(scaleStart1); TestGesture gesture2 = await tester.startGesture(scaleStart2); addTearDown(gesture2.removePointer); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); // Attempting to pinch to rotate doesn't work because it's disabled. final Offset rotateStart1 = childInterior; final Offset rotateStart2 = Offset(childInterior.dx + 10.0, childInterior.dy); final Offset rotateEnd1 = Offset(childInterior.dx + 5.0, childInterior.dy + 5.0); final Offset rotateEnd2 = Offset(childInterior.dx - 5.0, childInterior.dy - 5.0); gesture = await tester.startGesture(rotateStart1); gesture2 = await tester.startGesture(rotateStart2); await tester.pump(); await gesture.moveTo(rotateEnd1); await gesture2.moveTo(rotateEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); // Drag to pan away from the boundary. gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, isNot(equals(Matrix4.identity()))); }); testWidgets('child has no dimensions', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( constrained: false, scaleEnabled: false, transformationController: transformationController, child: const SizedBox.shrink(), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Interacting throws an error because the child has no size. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); final TestGesture gesture = await tester.startGesture(childOffset); await tester.pump(); await gesture.moveTo(childInterior); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); expect(tester.takeException(), isAssertionError); }); testWidgets('no boundary', (WidgetTester tester) async { const double minScale = 0.8; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Drag to pan works because even though the viewport fits perfectly // around the child, there is no boundary. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, childOffset.dx - childInterior.dx); expect(translation.y, childOffset.dy - childInterior.dy); // It's also possible to zoom out and view beyond the child because there // is no boundary. final Offset scaleStart1 = childInterior; final Offset scaleStart2 = Offset(childInterior.dx + 20.0, childInterior.dy); final Offset scaleEnd1 = Offset(childInterior.dx + 5.0, childInterior.dy); final Offset scaleEnd2 = Offset(childInterior.dx - 5.0, childInterior.dy); gesture = await tester.createGesture(); final TestGesture gesture2 = await tester.createGesture(); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), minScale); }); testWidgets('PanAxis.free allows panning in all directions for diagonal gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation has only happened along the y axis (the default axis when // a gesture is perfectly at 45 degrees to the axes). final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, childOffset.dx - childInterior.dx); expect(translation.y, childOffset.dy - childInterior.dy); }); testWidgets('PanAxis.aligned allows panning in one direction only for diagonal gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.aligned, boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation has only happened along the y axis (the default axis when // a gesture is perfectly at 45 degrees to the axes). final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, 0.0); expect(translation.y, childOffset.dy - childInterior.dy); }); testWidgets('PanAxis.aligned allows panning in one direction only for horizontal leaning gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.aligned, boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a horizontally leaning diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 10.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation happened only along the x axis because that's the axis that // had the greatest movement. final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, childOffset.dx - childInterior.dx); expect(translation.y, 0.0); }); testWidgets('PanAxis.horizontal allows panning in the horizontal direction only for diagonal gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.horizontal, boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation has only happened along the x axis (the default axis when // a gesture is perfectly at 45 degrees to the axes). final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, childOffset.dx - childInterior.dx); expect(translation.y, 0.0); }); testWidgets('PanAxis.horizontal allows panning in the horizontal direction only for horizontal leaning gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.horizontal, boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a horizontally leaning diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 10.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation happened only along the x axis because that's the axis that // had been set to the panningDirection parameter. final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, childOffset.dx - childInterior.dx); expect(translation.y, 0.0); }); testWidgets('PanAxis.horizontal does not allow panning in vertical direction on vertical gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.horizontal, boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a horizontally leaning diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 0.0, childOffset.dy + 10.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation didn't happen because the only axis allowed to do panning // is the horizontal. final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, 0.0); expect(translation.y, 0.0); }); testWidgets('PanAxis.vertical allows panning in the vertical direction only for diagonal gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.vertical, boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation has only happened along the x axis (the default axis when // a gesture is perfectly at 45 degrees to the axes). final Vector3 translation = transformationController.value.getTranslation(); expect(translation.y, childOffset.dy - childInterior.dy); expect(translation.x, 0.0); }); testWidgets('PanAxis.vertical allows panning in the vertical direction only for vertical leaning gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.vertical, boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a horizontally leaning diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 10.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation happened only along the x axis because that's the axis that // had been set to the panningDirection parameter. final Vector3 translation = transformationController.value.getTranslation(); expect(translation.y, childOffset.dy - childInterior.dy); expect(translation.x, 0.0); }); testWidgets('PanAxis.vertical does not allow panning in horizontal direction on vertical gesture', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.vertical, boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Perform a horizontally leaning diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 10.0, childOffset.dy + 0.0, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Translation didn't happen because the only axis allowed to do panning // is the horizontal. final Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, 0.0); expect(translation.y, 0.0); }); testWidgets('inertia fling and boundary sliding', (WidgetTester tester) async { const double boundaryMargin = 50.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); // Fling the child. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); const Offset flingEnd = Offset(20.0, 15.0); await tester.flingFrom(childOffset, flingEnd, 1000.0); await tester.pump(); // Immediately after the gesture, the child has moved to exactly follow // the gesture. Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, flingEnd.dx); expect(translation.y, flingEnd.dy); // A short time after the gesture was released, it continues to move with // inertia. await tester.pump(const Duration(milliseconds: 10)); translation = transformationController.value.getTranslation(); expect(translation.x, greaterThan(20.0)); expect(translation.y, greaterThan(10.0)); expect(translation.x, lessThan(boundaryMargin)); expect(translation.y, lessThan(boundaryMargin)); // It hits the boundary in the x direction first. await tester.pump(const Duration(milliseconds: 60)); translation = transformationController.value.getTranslation(); expect(translation.x, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); expect(translation.y, lessThan(boundaryMargin)); final double yWhenXHits = translation.y; // x is held to the boundary while y slides along. await tester.pump(const Duration(milliseconds: 50)); translation = transformationController.value.getTranslation(); expect(translation.x, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); expect(translation.y, greaterThan(yWhenXHits)); expect(translation.y, lessThan(boundaryMargin)); // Eventually it ends up in the corner. await tester.pumpAndSettle(); translation = transformationController.value.getTranslation(); expect(translation.x, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); expect(translation.y, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); }); testWidgets('Scaling automatically causes a centering translation', (WidgetTester tester) async { const double boundaryMargin = 50.0; const double minScale = 0.1; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), minScale: minScale, transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, 0.0); expect(translation.y, 0.0); // Pan into the corner of the boundaries. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); const Offset flingEnd = Offset(20.0, 15.0); await tester.flingFrom(childOffset, flingEnd, 1000.0); await tester.pumpAndSettle(); translation = transformationController.value.getTranslation(); expect(translation.x, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); expect(translation.y, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); // Zoom out so the entire child is visible. The child will also be // translated in order to keep it inside the boundaries. final Offset childCenter = tester.getCenter(find.byType(SizedBox)); Offset scaleStart1 = Offset(childCenter.dx - 40.0, childCenter.dy); Offset scaleStart2 = Offset(childCenter.dx + 40.0, childCenter.dy); Offset scaleEnd1 = Offset(childCenter.dx - 10.0, childCenter.dy); Offset scaleEnd2 = Offset(childCenter.dx + 10.0, childCenter.dy); TestGesture gesture = await tester.createGesture(); TestGesture gesture2 = await tester.createGesture(); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), lessThan(1.0)); translation = transformationController.value.getTranslation(); expect(translation.x, lessThan(boundaryMargin)); expect(translation.y, lessThan(boundaryMargin)); expect(translation.x, greaterThan(0.0)); expect(translation.y, greaterThan(0.0)); expect(translation.x, moreOrLessEquals(translation.y, epsilon: 1e-9)); // Zoom in on a point that's not the center, and see that it remains at // roughly the same location in the viewport after the zoom. scaleStart1 = Offset(childCenter.dx - 50.0, childCenter.dy); scaleStart2 = Offset(childCenter.dx - 30.0, childCenter.dy); scaleEnd1 = Offset(childCenter.dx - 51.0, childCenter.dy); scaleEnd2 = Offset(childCenter.dx - 29.0, childCenter.dy); final Offset viewportFocalPoint = Offset( childCenter.dx - 40.0 - childOffset.dx, childCenter.dy - childOffset.dy, ); final Offset sceneFocalPoint = transformationController.toScene(viewportFocalPoint); gesture = await tester.createGesture(); gesture2 = await tester.createGesture(); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); final Offset newSceneFocalPoint = transformationController.toScene(viewportFocalPoint); expect(newSceneFocalPoint.dx, moreOrLessEquals(sceneFocalPoint.dx, epsilon: 1.0)); expect(newSceneFocalPoint.dy, moreOrLessEquals(sceneFocalPoint.dy, epsilon: 1.0)); }); testWidgets('Scaling automatically causes a centering translation even when alignPanAxis is set', (WidgetTester tester) async { const double boundaryMargin = 50.0; const double minScale = 0.1; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( panAxis: PanAxis.aligned, boundaryMargin: const EdgeInsets.all(boundaryMargin), minScale: minScale, transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, 0.0); expect(translation.y, 0.0); // Pan into the corner of the boundaries in two gestures, since // alignPanAxis prevents diagonal panning. final Offset childOffset1 = tester.getTopLeft(find.byType(SizedBox)); const Offset flingEnd1 = Offset(20.0, 0.0); await tester.flingFrom(childOffset1, flingEnd1, 1000.0); await tester.pumpAndSettle(); await tester.pump(const Duration(seconds: 5)); final Offset childOffset2 = tester.getTopLeft(find.byType(SizedBox)); const Offset flingEnd2 = Offset(0.0, 15.0); await tester.flingFrom(childOffset2, flingEnd2, 1000.0); await tester.pumpAndSettle(); translation = transformationController.value.getTranslation(); expect(translation.x, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); expect(translation.y, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); // Zoom out so the entire child is visible. The child will also be // translated in order to keep it inside the boundaries. final Offset childCenter = tester.getCenter(find.byType(SizedBox)); Offset scaleStart1 = Offset(childCenter.dx - 40.0, childCenter.dy); Offset scaleStart2 = Offset(childCenter.dx + 40.0, childCenter.dy); Offset scaleEnd1 = Offset(childCenter.dx - 10.0, childCenter.dy); Offset scaleEnd2 = Offset(childCenter.dx + 10.0, childCenter.dy); TestGesture gesture = await tester.createGesture(); TestGesture gesture2 = await tester.createGesture(); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), lessThan(1.0)); translation = transformationController.value.getTranslation(); expect(translation.x, lessThan(boundaryMargin)); expect(translation.y, lessThan(boundaryMargin)); expect(translation.x, greaterThan(0.0)); expect(translation.y, greaterThan(0.0)); expect(translation.x, moreOrLessEquals(translation.y, epsilon: 1e-9)); // Zoom in on a point that's not the center, and see that it remains at // roughly the same location in the viewport after the zoom. scaleStart1 = Offset(childCenter.dx - 50.0, childCenter.dy); scaleStart2 = Offset(childCenter.dx - 30.0, childCenter.dy); scaleEnd1 = Offset(childCenter.dx - 51.0, childCenter.dy); scaleEnd2 = Offset(childCenter.dx - 29.0, childCenter.dy); final Offset viewportFocalPoint = Offset( childCenter.dx - 40.0 - childOffset1.dx, childCenter.dy - childOffset1.dy, ); final Offset sceneFocalPoint = transformationController.toScene(viewportFocalPoint); gesture = await tester.createGesture(); gesture2 = await tester.createGesture(); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); final Offset newSceneFocalPoint = transformationController.toScene(viewportFocalPoint); expect(newSceneFocalPoint.dx, moreOrLessEquals(sceneFocalPoint.dx, epsilon: 1.0)); expect(newSceneFocalPoint.dy, moreOrLessEquals(sceneFocalPoint.dy, epsilon: 1.0)); }); testWidgets('Can scale with mouse', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); final Offset center = tester.getCenter(find.byType(InteractiveViewer)); await scrollAt(center, tester, const Offset(0.0, -20.0)); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), greaterThan(1.0)); }); testWidgets('Cannot scale with mouse when scale is disabled', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( transformationController: transformationController, scaleEnabled: false, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); final Offset center = tester.getCenter(find.byType(InteractiveViewer)); await scrollAt(center, tester, const Offset(0.0, -20.0)); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), equals(1.0)); }); testWidgets('Scale with mouse returns onInteraction properties', (WidgetTester tester) async{ late Offset focalPoint; late Offset localFocalPoint; late double scaleChange; late Velocity currentVelocity; late bool calledStart; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( transformationController: transformationController, onInteractionStart: (ScaleStartDetails details) { calledStart = true; }, onInteractionUpdate: (ScaleUpdateDetails details) { scaleChange = details.scale; focalPoint = details.focalPoint; localFocalPoint = details.localFocalPoint; }, onInteractionEnd: (ScaleEndDetails details) { currentVelocity = details.velocity; }, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); final Offset center = tester.getCenter(find.byType(InteractiveViewer)); await scrollAt(center, tester, const Offset(0.0, -20.0)); await tester.pumpAndSettle(); const Velocity noMovement = Velocity.zero; final double afterScaling = transformationController.value.getMaxScaleOnAxis(); expect(scaleChange, greaterThan(1.0)); expect(afterScaling, scaleChange); expect(currentVelocity, equals(noMovement)); expect(calledStart, equals(true)); // Focal points are given in coordinates outside of InteractiveViewer, // with local being in relation to the viewport. expect(focalPoint, center); expect(localFocalPoint, const Offset(100, 100)); // The scene point is the same as localFocalPoint because the center of // the scene is at the center of the viewport. final Offset scenePoint = transformationController.toScene(localFocalPoint); expect(scenePoint, const Offset(100, 100)); }); testWidgets('Scaling amount is equal forth and back with a mouse scroll', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( constrained: false, maxScale: 100000, minScale: 0.01, transformationController: transformationController, child: const SizedBox(width: 1000.0, height: 1000.0), ), ), ), ), ); final Offset center = tester.getCenter(find.byType(InteractiveViewer)); await scrollAt(center, tester, const Offset(0.0, -200.0)); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), math.exp(200 / 200)); await scrollAt(center, tester, const Offset(0.0, -200.0)); await tester.pumpAndSettle(); // math.exp round the number too short compared to the one in transformationController. expect(transformationController.value.getMaxScaleOnAxis(), closeTo(math.exp(400 / 200), 0.000000000000001)); await scrollAt(center, tester, const Offset(0.0, 200.0)); await scrollAt(center, tester, const Offset(0.0, 200.0)); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); }); testWidgets('onInteraction can be used to get scene point', (WidgetTester tester) async{ late Offset focalPoint; late Offset localFocalPoint; late double scaleChange; late Velocity currentVelocity; late bool calledStart; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( transformationController: transformationController, onInteractionStart: (ScaleStartDetails details) { calledStart = true; }, onInteractionUpdate: (ScaleUpdateDetails details) { scaleChange = details.scale; focalPoint = details.focalPoint; localFocalPoint = details.localFocalPoint; }, onInteractionEnd: (ScaleEndDetails details) { currentVelocity = details.velocity; }, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); final Offset center = tester.getCenter(find.byType(InteractiveViewer)); final Offset offCenter = Offset(center.dx - 20.0, center.dy - 20.0); await scrollAt(offCenter, tester, const Offset(0.0, -20.0)); await tester.pumpAndSettle(); const Velocity noMovement = Velocity.zero; final double afterScaling = transformationController.value.getMaxScaleOnAxis(); expect(scaleChange, greaterThan(1.0)); expect(afterScaling, scaleChange); expect(currentVelocity, equals(noMovement)); expect(calledStart, equals(true)); // Focal points are given in coordinates outside of InteractiveViewer, // with local being in relation to the viewport. expect(focalPoint, offCenter); expect(localFocalPoint, const Offset(80, 80)); // The top left corner of the viewport is not at the top left corner of // the scene. final Offset scenePoint = transformationController.toScene(Offset.zero); expect(scenePoint.dx, greaterThan(0.0)); expect(scenePoint.dy, greaterThan(0.0)); }); testWidgets('onInteraction is called even when disabled (touch)', (WidgetTester tester) async { bool calledStart = false; bool calledUpdate = false; bool calledEnd = false; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( transformationController: transformationController, scaleEnabled: false, onInteractionStart: (ScaleStartDetails details) { calledStart = true; }, onInteractionUpdate: (ScaleUpdateDetails details) { calledUpdate = true; }, onInteractionEnd: (ScaleEndDetails details) { calledEnd = true; }, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); TestGesture gesture = await tester.startGesture(childOffset); // Attempting to pan doesn't work because it's disabled, but the // interaction methods are still called. await tester.pump(); await gesture.moveTo(childInterior); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); expect(calledStart, isTrue); expect(calledUpdate, isTrue); expect(calledEnd, isTrue); // Attempting to pinch to zoom doesn't work because it's disabled, but the // interaction methods are still called. calledStart = false; calledUpdate = false; calledEnd = false; final Offset scaleStart1 = childInterior; final Offset scaleStart2 = Offset(childInterior.dx + 10.0, childInterior.dy); final Offset scaleEnd1 = Offset(childInterior.dx - 10.0, childInterior.dy); final Offset scaleEnd2 = Offset(childInterior.dx + 20.0, childInterior.dy); gesture = await tester.startGesture(scaleStart1); final TestGesture gesture2 = await tester.startGesture(scaleStart2); addTearDown(gesture2.removePointer); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); expect(calledStart, isTrue); expect(calledUpdate, isTrue); expect(calledEnd, isTrue); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); testWidgets('onInteraction is called even when disabled (mouse)', (WidgetTester tester) async { bool calledStart = false; bool calledUpdate = false; bool calledEnd = false; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( transformationController: transformationController, scaleEnabled: false, onInteractionStart: (ScaleStartDetails details) { calledStart = true; }, onInteractionUpdate: (ScaleUpdateDetails details) { calledUpdate = true; }, onInteractionEnd: (ScaleEndDetails details) { calledEnd = true; }, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); final TestGesture gesture = await tester.startGesture(childOffset, kind: PointerDeviceKind.mouse); // Attempting to pan doesn't work because it's disabled, but the // interaction methods are still called. await tester.pump(); await gesture.moveTo(childInterior); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); expect(calledStart, isTrue); expect(calledUpdate, isTrue); expect(calledEnd, isTrue); // Attempting to scroll with a mouse to zoom doesn't work because it's // disabled, but the interaction methods are still called. calledStart = false; calledUpdate = false; calledEnd = false; await scrollAt(childInterior, tester, const Offset(0.0, -20.0)); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); expect(calledStart, isTrue); expect(calledUpdate, isTrue); expect(calledEnd, isTrue); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.linux, TargetPlatform.windows })); testWidgets('viewport changes size', (WidgetTester tester) async { addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( transformationController: transformationController, child: Container(), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Attempting to drag to pan doesn't work because the child fits inside // the viewport and has a tight boundary. final Offset childOffset = tester.getTopLeft(find.byType(Container)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); // Shrink the size of the screen. tester.view.physicalSize = const Size(100.0, 100.0); await tester.pump(); // Attempting to drag to pan still doesn't work, because the image has // resized itself to fit the new screen size, and InteractiveViewer has // updated its measurements to take that into consideration. gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); }); testWidgets('gesture can start as pan and become scale', (WidgetTester tester) async { const double boundaryMargin = 50.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, 0.0); expect(translation.y, 0.0); // Start a pan gesture. final Offset childCenter = tester.getCenter(find.byType(SizedBox)); final TestGesture gesture = await tester.createGesture(); await gesture.down(childCenter); await tester.pump(); await gesture.moveTo(Offset( childCenter.dx + 5.0, childCenter.dy + 5.0, )); await tester.pump(); translation = transformationController.value.getTranslation(); expect(translation.x, greaterThan(0.0)); expect(translation.y, greaterThan(0.0)); // Put another finger down and turn it into a scale gesture. final TestGesture gesture2 = await tester.createGesture(); await gesture2.down(Offset( childCenter.dx - 5.0, childCenter.dy - 5.0, )); await tester.pump(); await gesture.moveTo(Offset( childCenter.dx + 25.0, childCenter.dy + 25.0, )); await gesture2.moveTo(Offset( childCenter.dx - 25.0, childCenter.dy - 25.0, )); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), greaterThan(1.0)); }); // Regression test for https://github.com/flutter/flutter/issues/65304 testWidgets('can view beyond boundary when necessary for a small child', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( constrained: false, minScale: 1.0, maxScale: 1.0, transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // Pinch to zoom does nothing because minScale and maxScale are 1.0. final Offset center = tester.getCenter(find.byType(SizedBox)); final Offset scaleStart1 = Offset(center.dx - 10.0, center.dy - 10.0); final Offset scaleStart2 = Offset(center.dx + 10.0, center.dy + 10.0); final Offset scaleEnd1 = Offset(center.dx - 20.0, center.dy - 20.0); final Offset scaleEnd2 = Offset(center.dx + 20.0, center.dy + 20.0); final TestGesture gesture = await tester.createGesture(); final TestGesture gesture2 = await tester.createGesture(); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); }); testWidgets('scale does not jump when wrapped in GestureDetector', (WidgetTester tester) async { double? initialScale; double? scale; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: GestureDetector( onTapUp: (TapUpDetails details) {}, child: InteractiveViewer( onInteractionUpdate: (ScaleUpdateDetails details) { initialScale ??= details.scale; scale = details.scale; }, transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); expect(initialScale, null); expect(scale, null); // Pinch to zoom isn't immediately detected for a small amount of // movement due to the GestureDetector. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); final Offset childInterior = Offset( childOffset.dx + 20.0, childOffset.dy + 20.0, ); final Offset scaleStart1 = childInterior; final Offset scaleStart2 = Offset(childInterior.dx + 10.0, childInterior.dy); Offset scaleEnd1 = Offset(childInterior.dx - 10.0, childInterior.dy); Offset scaleEnd2 = Offset(childInterior.dx + 20.0, childInterior.dy); TestGesture gesture = await tester.createGesture(); TestGesture gesture2 = await tester.createGesture(); addTearDown(gesture2.removePointer); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(transformationController.value, equals(Matrix4.identity())); expect(initialScale, null); expect(scale, null); // Pinch to zoom for a larger amount is detected. It starts smoothly at // 1.0 despite the fact that the gesture has already moved a bit. scaleEnd1 = Offset(childInterior.dx - 38.0, childInterior.dy); scaleEnd2 = Offset(childInterior.dx + 48.0, childInterior.dy); gesture = await tester.createGesture(); gesture2 = await tester.createGesture(); addTearDown(gesture2.removePointer); await gesture.down(scaleStart1); await gesture2.down(scaleStart2); await tester.pump(); await gesture.moveTo(scaleEnd1); await gesture2.moveTo(scaleEnd2); await tester.pump(); await gesture.up(); await gesture2.up(); await tester.pumpAndSettle(); expect(initialScale, 1.0); expect(scale, greaterThan(1.0)); expect(transformationController.value.getMaxScaleOnAxis(), greaterThan(1.0)); }); testWidgets('Check if ClipRect is present in the tree', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( constrained: false, clipBehavior: Clip.none, minScale: 1.0, maxScale: 1.0, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); final RenderClipRect renderClip = tester.allRenderObjects.whereType<RenderClipRect>().first; expect(renderClip.clipBehavior, equals(Clip.none)); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( constrained: false, minScale: 1.0, maxScale: 1.0, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect( find.byType(ClipRect), findsOneWidget, ); }); testWidgets('builder can change widgets that are off-screen', (WidgetTester tester) async { const double childHeight = 10.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: SizedBox( height: 50.0, child: InteractiveViewer.builder( transformationController: transformationController, scaleEnabled: false, boundaryMargin: const EdgeInsets.all(double.infinity), // Build visible children green, off-screen children red. builder: (BuildContext context, Quad viewportQuad) { final Rect viewport = _axisAlignedBoundingBox(viewportQuad); final List<Container> children = <Container>[]; for (int i = 0; i < 10; i++) { final double childTop = i * childHeight; final double childBottom = childTop + childHeight; final bool visible = (childBottom >= viewport.top && childBottom <= viewport.bottom) || (childTop >= viewport.top && childTop <= viewport.bottom); children.add(Container( height: childHeight, color: visible ? Colors.green : Colors.red, )); } return Column( children: children, ); }, ), ), ), ), ), ); expect(transformationController.value, equals(Matrix4.identity())); // The first six are partially visible and therefore green. int i = 0; for (final Element element in find.byType(Container, skipOffstage: false).evaluate()) { final Container container = element.widget as Container; if (i < 6) { expect(container.color, Colors.green); } else { expect(container.color, Colors.red); } i++; } // Drag to pan down past the first child. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); const double translationY = 15.0; final Offset childInterior = Offset( childOffset.dx, childOffset.dy + translationY, ); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(transformationController.value, isNot(Matrix4.identity())); expect(transformationController.value.getTranslation().y, -translationY); // After scrolling down a bit, the first child is not visible, the next // six are, and the final three are not. i = 0; for (final Element element in find.byType(Container, skipOffstage: false).evaluate()) { final Container container = element.widget as Container; if (i > 0 && i < 7) { expect(container.color, Colors.green); } else { expect(container.color, Colors.red); } i++; } }); // Accessing the intrinsic size of a LayoutBuilder throws an error, so // InteractiveViewer only uses a LayoutBuilder when it's needed by // InteractiveViewer.builder. testWidgets('LayoutBuilder is only used for InteractiveViewer.builder', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(find.byType(LayoutBuilder), findsNothing); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer.builder( builder: (BuildContext context, Quad viewport) { return const SizedBox(width: 200.0, height: 200.0); }, ), ), ), ), ); expect(find.byType(LayoutBuilder), findsOneWidget); }); testWidgets('scaleFactor', (WidgetTester tester) async { const double scrollAmount = 30.0; Future<void> pumpScaleFactor(double scaleFactor) { return tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(double.infinity), transformationController: transformationController, scaleFactor: scaleFactor, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); } // Start with the default scaleFactor. await pumpScaleFactor(200.0); expect(transformationController.value, equals(Matrix4.identity())); // Zoom out. The scale decreases. final Offset center = tester.getCenter(find.byType(InteractiveViewer)); await scrollAt(center, tester, const Offset(0.0, scrollAmount)); await tester.pumpAndSettle(); final double scaleZoomedOut = transformationController.value.getMaxScaleOnAxis(); expect(scaleZoomedOut, lessThan(1.0)); // Zoom in. The scale increases. await scrollAt(center, tester, const Offset(0.0, -scrollAmount)); await tester.pumpAndSettle(); final double scaleZoomedIn = transformationController.value.getMaxScaleOnAxis(); expect(scaleZoomedIn, greaterThan(scaleZoomedOut)); // Reset and decrease the scaleFactor below the default, so that scaling // will happen more quickly. transformationController.value = Matrix4.identity(); await pumpScaleFactor(100.0); // Zoom out. The scale decreases more quickly than with the default // (higher) scaleFactor. await scrollAt(center, tester, const Offset(0.0, scrollAmount)); await tester.pumpAndSettle(); final double scaleLowZoomedOut = transformationController.value.getMaxScaleOnAxis(); expect(scaleLowZoomedOut, lessThan(1.0)); expect(scaleLowZoomedOut, lessThan(scaleZoomedOut)); // Zoom in. The scale increases more quickly than with the default // (higher) scaleFactor. await scrollAt(center, tester, const Offset(0.0, -scrollAmount)); await tester.pumpAndSettle(); final double scaleLowZoomedIn = transformationController.value.getMaxScaleOnAxis(); expect(scaleLowZoomedIn, greaterThan(scaleLowZoomedOut)); expect(scaleLowZoomedIn - scaleLowZoomedOut, greaterThan(scaleZoomedIn - scaleZoomedOut)); // Reset and increase the scaleFactor above the default. transformationController.value = Matrix4.identity(); await pumpScaleFactor(400.0); // Zoom out. The scale decreases, but not by as much as with the default // (higher) scaleFactor. await scrollAt(center, tester, const Offset(0.0, scrollAmount)); await tester.pumpAndSettle(); final double scaleHighZoomedOut = transformationController.value.getMaxScaleOnAxis(); expect(scaleHighZoomedOut, lessThan(1.0)); expect(scaleHighZoomedOut, greaterThan(scaleZoomedOut)); // Zoom in. The scale increases, but not by as much as with the default // (higher) scaleFactor. await scrollAt(center, tester, const Offset(0.0, -scrollAmount)); await tester.pumpAndSettle(); final double scaleHighZoomedIn = transformationController.value.getMaxScaleOnAxis(); expect(scaleHighZoomedIn, greaterThan(scaleHighZoomedOut)); expect(scaleHighZoomedIn - scaleHighZoomedOut, lessThan(scaleZoomedIn - scaleZoomedOut)); }); testWidgets('alignment argument is used properly', (WidgetTester tester) async { const Alignment alignment = Alignment.center; await tester.pumpWidget(MaterialApp( home: Scaffold( body: InteractiveViewer( alignment: alignment, child: Container(), ), ), )); final Transform transform = tester.firstWidget(find.byType(Transform)); expect(transform.alignment, alignment); }); testWidgets('interactionEndFrictionCoefficient', (WidgetTester tester) async { // Use the default interactionEndFrictionCoefficient. final TransformationController transformationController1 = TransformationController(); addTearDown(transformationController1.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( width: 200, height: 200, child: InteractiveViewer( constrained: false, transformationController: transformationController1, child: const SizedBox(width: 2000.0, height: 2000.0), ), ), ), ), ); expect(transformationController1.value, equals(Matrix4.identity())); await tester.flingFrom(const Offset(100, 100), const Offset(0, -50), 100.0); await tester.pumpAndSettle(); final Vector3 translation1 = transformationController1.value.getTranslation(); expect(translation1.y, lessThan(-58.0)); // Next try a custom interactionEndFrictionCoefficient. final TransformationController transformationController2 = TransformationController(); addTearDown(transformationController2.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( width: 200, height: 200, child: InteractiveViewer( constrained: false, interactionEndFrictionCoefficient: 0.01, transformationController: transformationController2, child: const SizedBox(width: 2000.0, height: 2000.0), ), ), ), ), ); expect(transformationController2.value, equals(Matrix4.identity())); await tester.flingFrom(const Offset(100, 100), const Offset(0, -50), 100.0); await tester.pumpAndSettle(); final Vector3 translation2 = transformationController2.value.getTranslation(); // The coefficient 0.01 is greater than the default of 0.0000135, // so the translation comes to a stop more quickly. expect(translation2.y, lessThan(translation1.y)); }); testWidgets('discrete scroll pointer events', (WidgetTester tester) async { const double boundaryMargin = 50.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, 0); expect(translation.y, 0); // Send a mouse scroll event, it should cause a scale. final TestPointer mouse = TestPointer(1, PointerDeviceKind.mouse); await tester.sendEventToBinding(mouse.hover(tester.getCenter(find.byType(SizedBox)))); await tester.sendEventToBinding(mouse.scroll(const Offset(300, -200))); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), 2.5); translation = transformationController.value.getTranslation(); // Will be translated to maintain centering. expect(translation.x, -150); expect(translation.y, -150); // Send a trackpad scroll event, it should cause a pan and no scale. final TestPointer trackpad = TestPointer(1, PointerDeviceKind.trackpad); await tester.sendEventToBinding(trackpad.hover(tester.getCenter(find.byType(SizedBox)))); await tester.sendEventToBinding(trackpad.scroll(const Offset(100, -25))); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), 2.5); translation = transformationController.value.getTranslation(); expect(translation.x, -250); expect(translation.y, -125); }); testWidgets('discrete scale pointer event', (WidgetTester tester) async { const double boundaryMargin = 50.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), transformationController: transformationController, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); // Send a scale event. final TestPointer pointer = TestPointer(1, PointerDeviceKind.trackpad); await tester.sendEventToBinding(pointer.hover(tester.getCenter(find.byType(SizedBox)))); await tester.sendEventToBinding(pointer.scale(1.5)); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), 1.5); // Send another scale event. await tester.sendEventToBinding(pointer.scale(1.5)); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), 2.25); // Send another scale event. await tester.sendEventToBinding(pointer.scale(1.5)); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), 2.5); // capped at maxScale (2.5) }); testWidgets('trackpadScrollCausesScale', (WidgetTester tester) async { const double boundaryMargin = 50.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), transformationController: transformationController, trackpadScrollCausesScale: true, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); // Send a vertical scroll. final TestPointer pointer = TestPointer(1, PointerDeviceKind.trackpad); final Offset center = tester.getCenter(find.byType(SizedBox)); await tester.sendEventToBinding(pointer.panZoomStart(center)); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); await tester.sendEventToBinding(pointer.panZoomUpdate(center, pan: const Offset(0, -81))); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.499302500056767)); // Send a horizontal scroll (should have no effect). await tester.sendEventToBinding(pointer.panZoomUpdate(center, pan: const Offset(81, -81))); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.499302500056767)); }); testWidgets('trackpad pointer scroll events cause scale', (WidgetTester tester) async { const double boundaryMargin = 50.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), transformationController: transformationController, trackpadScrollCausesScale: true, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); // Send a vertical scroll. final TestPointer pointer = TestPointer(1, PointerDeviceKind.trackpad); final Offset center = tester.getCenter(find.byType(SizedBox)); Offset scrollAmnt = const Offset(0, -138.0); await tester.sendEventToBinding(pointer.hover(center)); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); await tester.sendEventToBinding(pointer.scroll(scrollAmnt)); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.9937155332430823)); // Scroll should not have translated the box, so the box should still be at the // center of the InteractiveViewer. Vector3 translation = transformationController.value.getTranslation(); expect(translation.x, moreOrLessEquals(-99.37155332430822)); expect(translation.y, moreOrLessEquals(-99.37155332430822)); // Send a horizontal scroll. scrollAmnt = const Offset(-138, 0); await tester.sendEventToBinding(pointer.scroll(scrollAmnt)); await tester.pump(); // Horizontal scroll should not cause a scale change. expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.9937155332430823)); // Horizontal scroll should not have changed the translation of the box. translation = transformationController.value.getTranslation(); expect(translation.x, moreOrLessEquals(-99.37155332430822)); expect(translation.y, moreOrLessEquals(-99.37155332430822)); }); testWidgets('Scaling inertia', (WidgetTester tester) async { const double boundaryMargin = 50.0; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: InteractiveViewer( boundaryMargin: const EdgeInsets.all(boundaryMargin), transformationController: transformationController, trackpadScrollCausesScale: true, child: const SizedBox(width: 200.0, height: 200.0), ), ), ), ), ); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); // Send a vertical scroll fling, which will cause inertia. await tester.trackpadFling( find.byType(InteractiveViewer), const Offset(0, -100), 3000 ); await tester.pump(); expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.6487212707001282)); await tester.pump(const Duration(milliseconds: 80)); expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.7966838346780103)); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.9984509673751225)); await tester.pump(const Duration(seconds: 10)); expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.9984509673751225)); }); }); group('getNearestPointOnLine', () { test('does not modify parameters', () { final Vector3 point = Vector3(5.0, 5.0, 0.0); final Vector3 a = Vector3(0.0, 0.0, 0.0); final Vector3 b = Vector3(10.0, 0.0, 0.0); final Vector3 closestPoint = InteractiveViewer.getNearestPointOnLine(point, a , b); expect(closestPoint, Vector3(5.0, 0.0, 0.0)); expect(point, Vector3(5.0, 5.0, 0.0)); expect(a, Vector3(0.0, 0.0, 0.0)); expect(b, Vector3(10.0, 0.0, 0.0)); }); test('simple example', () { final Vector3 point = Vector3(0.0, 5.0, 0.0); final Vector3 a = Vector3(0.0, 0.0, 0.0); final Vector3 b = Vector3(5.0, 5.0, 0.0); expect(InteractiveViewer.getNearestPointOnLine(point, a, b), Vector3(2.5, 2.5, 0.0)); }); test('closest to a', () { final Vector3 point = Vector3(-1.0, -1.0, 0.0); final Vector3 a = Vector3(0.0, 0.0, 0.0); final Vector3 b = Vector3(5.0, 5.0, 0.0); expect(InteractiveViewer.getNearestPointOnLine(point, a, b), a); }); test('closest to b', () { final Vector3 point = Vector3(6.0, 6.0, 0.0); final Vector3 a = Vector3(0.0, 0.0, 0.0); final Vector3 b = Vector3(5.0, 5.0, 0.0); expect(InteractiveViewer.getNearestPointOnLine(point, a, b), b); }); test('point already on the line returns the point', () { final Vector3 point = Vector3(2.0, 2.0, 0.0); final Vector3 a = Vector3(0.0, 0.0, 0.0); final Vector3 b = Vector3(5.0, 5.0, 0.0); expect(InteractiveViewer.getNearestPointOnLine(point, a, b), point); }); test('real example', () { final Vector3 point = Vector3(-436.9, 433.6, 0.0); final Vector3 a = Vector3(-1114.0, -60.3, 0.0); final Vector3 b = Vector3(288.8, 432.7, 0.0); final Vector3 closestPoint = InteractiveViewer.getNearestPointOnLine(point, a , b); expect(closestPoint.x, moreOrLessEquals(-356.8, epsilon: 0.1)); expect(closestPoint.y, moreOrLessEquals(205.8, epsilon: 0.1)); }); }); group('getAxisAlignedBoundingBox', () { test('rectangle already axis aligned returns the rectangle', () { final Quad quad = Quad.points( Vector3(0.0, 0.0, 0.0), Vector3(10.0, 0.0, 0.0), Vector3(10.0, 10.0, 0.0), Vector3(0.0, 10.0, 0.0), ); final Quad aabb = InteractiveViewer.getAxisAlignedBoundingBox(quad); expect(aabb.point0, quad.point0); expect(aabb.point1, quad.point1); expect(aabb.point2, quad.point2); expect(aabb.point3, quad.point3); }); test('rectangle rotated by 45 degrees', () { final Quad quad = Quad.points( Vector3(0.0, 5.0, 0.0), Vector3(5.0, 10.0, 0.0), Vector3(10.0, 5.0, 0.0), Vector3(5.0, 0.0, 0.0), ); final Quad aabb = InteractiveViewer.getAxisAlignedBoundingBox(quad); expect(aabb.point0, Vector3(0.0, 0.0, 0.0)); expect(aabb.point1, Vector3(10.0, 0.0, 0.0)); expect(aabb.point2, Vector3(10.0, 10.0, 0.0)); expect(aabb.point3, Vector3(0.0, 10.0, 0.0)); }); test('rectangle rotated very slightly', () { final Quad quad = Quad.points( Vector3(0.0, 1.0, 0.0), Vector3(1.0, 11.0, 0.0), Vector3(11.0, 9.0, 0.0), Vector3(9.0, -1.0, 0.0), ); final Quad aabb = InteractiveViewer.getAxisAlignedBoundingBox(quad); expect(aabb.point0, Vector3(0.0, -1.0, 0.0)); expect(aabb.point1, Vector3(11.0, -1.0, 0.0)); expect(aabb.point2, Vector3(11.0, 11.0, 0.0)); expect(aabb.point3, Vector3(0.0, 11.0, 0.0)); }); test('example from hexagon board', () { final Quad quad = Quad.points( Vector3(-462.7, 165.9, 0.0), Vector3(690.6, -576.7, 0.0), Vector3(1188.1, 196.0, 0.0), Vector3(34.9, 938.6, 0.0), ); final Quad aabb = InteractiveViewer.getAxisAlignedBoundingBox(quad); expect(aabb.point0, Vector3(-462.7, -576.7, 0.0)); expect(aabb.point1, Vector3(1188.1, -576.7, 0.0)); expect(aabb.point2, Vector3(1188.1, 938.6, 0.0)); expect(aabb.point3, Vector3(-462.7, 938.6, 0.0)); }); }); group('pointIsInside', () { test('inside', () { final Quad quad = Quad.points( Vector3(0.0, 0.0, 0.0), Vector3(0.0, 10.0, 0.0), Vector3(10.0, 10.0, 0.0), Vector3(10.0, 0.0, 0.0), ); final Vector3 point = Vector3(5.0, 5.0, 0.0); expect(InteractiveViewer.pointIsInside(point, quad), true); }); test('outside', () { final Quad quad = Quad.points( Vector3(0.0, 0.0, 0.0), Vector3(0.0, 10.0, 0.0), Vector3(10.0, 10.0, 0.0), Vector3(10.0, 0.0, 0.0), ); final Vector3 point = Vector3(12.0, 0.0, 0.0); expect(InteractiveViewer.pointIsInside(point, quad), false); }); test('on the edge', () { final Quad quad = Quad.points( Vector3(0.0, 0.0, 0.0), Vector3(0.0, 10.0, 0.0), Vector3(10.0, 10.0, 0.0), Vector3(10.0, 0.0, 0.0), ); final Vector3 point = Vector3(0.0, 0.0, 0.0); expect(InteractiveViewer.pointIsInside(point, quad), true); }); }); group('getNearestPointInside', () { test('point already inside quad', () { final Vector3 point = Vector3(5.0, 5.0, 0.0); final Quad quad = Quad.points( Vector3(0.0, 0.0, 0.0), Vector3(0.0, 10.0, 0.0), Vector3(10.0, 10.0, 0.0), Vector3(10.0, 0.0, 0.0), ); final Vector3 nearestPoint = InteractiveViewer.getNearestPointInside(point, quad); expect(nearestPoint, point); }); test('axis aligned quad', () { final Vector3 point = Vector3(5.0, 15.0, 0.0); final Quad quad = Quad.points( Vector3(0.0, 0.0, 0.0), Vector3(0.0, 10.0, 0.0), Vector3(10.0, 10.0, 0.0), Vector3(10.0, 0.0, 0.0), ); final Vector3 nearestPoint = InteractiveViewer.getNearestPointInside(point, quad); expect(nearestPoint, Vector3(5.0, 10.0, 0.0)); }); test('not axis aligned quad', () { final Vector3 point = Vector3(5.0, 15.0, 0.0); final Quad quad = Quad.points( Vector3(0.0, 0.0, 0.0), Vector3(2.0, 10.0, 0.0), Vector3(12.0, 12.0, 0.0), Vector3(10.0, 2.0, 0.0), ); final Vector3 nearestPoint = InteractiveViewer.getNearestPointInside(point, quad); expect(nearestPoint.x, moreOrLessEquals(5.8, epsilon: 0.1)); expect(nearestPoint.y, moreOrLessEquals(10.8, epsilon: 0.1)); }); }); } Rect _axisAlignedBoundingBox(Quad quad) { double? xMin; double? xMax; double? yMin; double? yMax; for (final Vector3 point in <Vector3>[quad.point0, quad.point1, quad.point2, quad.point3]) { if (xMin == null || point.x < xMin) { xMin = point.x; } if (xMax == null || point.x > xMax) { xMax = point.x; } if (yMin == null || point.y < yMin) { yMin = point.y; } if (yMax == null || point.y > yMax) { yMax = point.y; } } return Rect.fromLTRB(xMin!, yMin!, xMax!, yMax!); }
flutter/packages/flutter/test/widgets/interactive_viewer_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/interactive_viewer_test.dart", "repo_id": "flutter", "token_count": 35112 }
689
// 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_test/flutter_test.dart'; const double kHeight = 10.0; const double kFlingOffset = kHeight * 20.0; void main() { testWidgets("Flings don't stutter", (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView.builder( itemBuilder: (BuildContext context, int index) { return Container(height: kHeight); }, ), ), ); double getCurrentOffset() { return tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels; } await tester.fling(find.byType(ListView), const Offset(0.0, -kFlingOffset), 1000.0); expect(getCurrentOffset(), kFlingOffset); await tester.pump(); // process the up event while (tester.binding.transientCallbackCount > 0) { final double lastOffset = getCurrentOffset(); await tester.pump(const Duration(milliseconds: 20)); expect(getCurrentOffset(), greaterThan(lastOffset)); } }); }
flutter/packages/flutter/test/widgets/list_view_fling_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/list_view_fling_test.dart", "repo_id": "flutter", "token_count": 454 }
690
// 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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('setState can be called from build, initState, didChangeDependencies, and didUpdateWidget', (WidgetTester tester) async { // Initial build. await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: TestWidget(value: 1), ), ); final _TestWidgetState state = tester.state(find.byType(TestWidget)); expect(state.calledDuringBuild, 1); expect(state.calledDuringInitState, 1); expect(state.calledDuringDidChangeDependencies, 1); expect(state.calledDuringDidUpdateWidget, 0); // Update Widget. late Widget child; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: child = const TestWidget(value: 2), ), ); expect(state.calledDuringBuild, 2); // Increased. expect(state.calledDuringInitState, 1); expect(state.calledDuringDidChangeDependencies, 1); expect(state.calledDuringDidUpdateWidget, 1); // Increased. // Build after state is dirty. state.markNeedsBuild(); await tester.pump(); expect(state.calledDuringBuild, 3); // Increased. expect(state.calledDuringInitState, 1); expect(state.calledDuringDidChangeDependencies, 1); expect(state.calledDuringDidUpdateWidget, 1); // Change dependency. await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, // Changed. child: child, ), ); expect(state.calledDuringBuild, 4); // Increased. expect(state.calledDuringInitState, 1); expect(state.calledDuringDidChangeDependencies, 2); // Increased. expect(state.calledDuringDidUpdateWidget, 1); }); } class TestWidget extends StatefulWidget { const TestWidget({super.key, required this.value}); final int value; @override State<TestWidget> createState() => _TestWidgetState(); } class _TestWidgetState extends State<TestWidget> { int calledDuringBuild = 0; int calledDuringInitState = 0; int calledDuringDidChangeDependencies = 0; int calledDuringDidUpdateWidget = 0; void markNeedsBuild() { setState(() { // Intentionally left empty. }); } @override void initState() { super.initState(); setState(() { calledDuringInitState++; }); } @override void didChangeDependencies() { super.didChangeDependencies(); setState(() { calledDuringDidChangeDependencies++; }); } @override void didUpdateWidget(TestWidget oldWidget) { super.didUpdateWidget(oldWidget); setState(() { calledDuringDidUpdateWidget++; }); } @override Widget build(BuildContext context) { setState(() { calledDuringBuild++; }); return SizedBox.expand( child: Text('${widget.value}: ${Directionality.of(context)}'), ); } }
flutter/packages/flutter/test/widgets/mark_needs_build_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/mark_needs_build_test.dart", "repo_id": "flutter", "token_count": 1094 }
691
// 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 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../rendering/rendering_tester.dart' show TestClipPaintingContext; class _CustomPhysics extends ClampingScrollPhysics { const _CustomPhysics({ super.parent }); @override _CustomPhysics applyTo(ScrollPhysics? ancestor) { return _CustomPhysics(parent: buildParent(ancestor)); } @override Simulation createBallisticSimulation(ScrollMetrics position, double dragVelocity) { return ScrollSpringSimulation(spring, 1000.0, 1000.0, 1000.0); } } Widget buildTest({ ScrollController? controller, String title = 'TTTTTTTT', Key? key, bool expanded = true, }) { return MaterialApp( home: Scaffold( drawerDragStartBehavior: DragStartBehavior.down, body: DefaultTabController( length: 4, child: NestedScrollView( key: key, dragStartBehavior: DragStartBehavior.down, controller: controller, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( title: Text(title), pinned: true, expandedHeight: expanded ? 200.0 : 0.0, forceElevated: innerBoxIsScrolled, bottom: const TabBar( tabs: <Tab>[ Tab(text: 'AA'), Tab(text: 'BB'), Tab(text: 'CC'), Tab(text: 'DD'), ], ), ), ]; }, body: TabBarView( children: <Widget>[ ListView( children: const <Widget>[ SizedBox( height: 300.0, child: Text('aaa1'), ), SizedBox( height: 200.0, child: Text('aaa2'), ), SizedBox( height: 100.0, child: Text('aaa3'), ), SizedBox( height: 50.0, child: Text('aaa4'), ), ], ), ListView( dragStartBehavior: DragStartBehavior.down, children: const <Widget>[ SizedBox( height: 100.0, child: Text('bbb1'), ), ], ), const Center(child: Text('ccc1')), ListView( dragStartBehavior: DragStartBehavior.down, children: const <Widget>[ SizedBox( height: 10000.0, child: Text('ddd1'), ), ], ), ], ), ), ), ), ); } void main() { testWidgets('ScrollDirection test', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/107101 final List<ScrollDirection> receivedResult = <ScrollDirection>[]; const List<ScrollDirection> expectedReverseResult = <ScrollDirection>[ScrollDirection.reverse, ScrollDirection.idle]; const List<ScrollDirection> expectedForwardResult = <ScrollDirection>[ScrollDirection.forward, ScrollDirection.idle]; await tester.pumpWidget(MaterialApp( home: Scaffold( body: NotificationListener<UserScrollNotification>( onNotification: (UserScrollNotification notification) { if (notification.depth != 1) { return true; } receivedResult.add(notification.direction); return true; }, child: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ const SliverAppBar( expandedHeight: 250.0, pinned: true, ), ], body: ListView.builder( padding: const EdgeInsets.all(8), itemCount: 30, itemBuilder: (BuildContext context, int index) { return SizedBox( height: 50, child: Center(child: Text('Item $index')), ); }, ), ), ), ), )); // Fling down to trigger ballistic activity await tester.fling(find.text('Item 3'), const Offset(0.0, -250.0), 10000.0); await tester.pumpAndSettle(); expect(receivedResult, expectedReverseResult); receivedResult.clear(); // Drag forward, without ballistic activity await tester.drag(find.text('Item 29'), const Offset(0.0, 20.0)); await tester.pump(); expect(receivedResult, expectedForwardResult); }); testWidgets('NestedScrollView respects clipBehavior', (WidgetTester tester) async { Widget build(NestedScrollView nestedScrollView) { return Localizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: nestedScrollView, ), ), ); } await tester.pumpWidget(build( NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[const SliverAppBar()], body: Container(height: 2000.0), ), )); // 1st, check that the render object has received the default clip behavior. final RenderNestedScrollViewViewport renderObject = tester.allRenderObjects.whereType<RenderNestedScrollViewViewport>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // 2nd, check that the painting context has received the default clip behavior. final TestClipPaintingContext context = TestClipPaintingContext(); renderObject.paint(context, Offset.zero); expect(context.clipBehavior, equals(Clip.hardEdge)); // 3rd, pump a new widget to check that the render object can update its clip behavior. await tester.pumpWidget(build( NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[const SliverAppBar()], body: Container(height: 2000.0), clipBehavior: Clip.antiAlias, ), )); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); // 4th, check that a non-default clip behavior can be sent to the painting context. renderObject.paint(context, Offset.zero); expect(context.clipBehavior, equals(Clip.antiAlias)); }); testWidgets('NestedScrollView always scrolls outer scrollable first', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/136199 final Key innerKey = UniqueKey(); final GlobalKey<NestedScrollViewState> outerKey = GlobalKey(); final ScrollController outerController = ScrollController(); addTearDown(outerController.dispose); Widget build() { return Directionality( textDirection: TextDirection.ltr, child: Scaffold( body: NestedScrollView( key: outerKey, controller: outerController, physics: const BouncingScrollPhysics(), headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ SliverToBoxAdapter( child: Container(color: Colors.green, height: 300), ), SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverToBoxAdapter( child: Container( color: Colors.blue, height: 64, ), ), ), ], body: SingleChildScrollView( key: innerKey, physics: const BouncingScrollPhysics(), child: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: <ui.Color>[Colors.black, Colors.blue], stops: <double>[0, 1], ), ), height: 800, ), ), ), ), ); } await tester.pumpWidget(build()); final ScrollController outer = outerKey.currentState!.outerController; final ScrollController inner = outerKey.currentState!.innerController; // Assert the initial positions expect(outer.offset, 0.0); expect(inner.offset, 0.0); outerController.addListener(() { fail('Outer controller should not be scrolling'); // This should never be called }); await tester.drag(find.byKey(innerKey), const Offset(0, 2000)); // Over-scroll the inner Scrollable to the bottom // Using a precise value to make addition/subtraction possible later in the test // Which better conveys the intent of the test // The value is not equal to 2000 due to BouncingScrollPhysics of the inner Scrollable const double endPosition = -1974.0862087158384; const Duration nextFrame = Duration(microseconds: 16666); // Assert positions after over-scrolling expect(outer.offset, 0.0); expect(inner.offset, endPosition); await tester.fling(find.byKey(innerKey), const Offset(0, -600), 2000); // Fling the inner Scrollable to the top // Assert positions after fling expect(outer.offset, 0.0); expect(inner.offset, endPosition + 600); await tester.pump(nextFrame); // Assert positions after pump expect(outer.offset, 0.0); expect(inner.offset, endPosition + 600); double currentOffset = inner.offset; int maxNumberOfSteps = 100; while (inner.offset < 0) { maxNumberOfSteps--; if (maxNumberOfSteps <= 0) { fail('Scrolling did not settle in an expected number of steps.'); } await tester.pump(nextFrame); expect(inner.offset, greaterThanOrEqualTo(currentOffset)); expect(outer.offset, 0.0); currentOffset = inner.offset; } // Assert positions returned to/stayed at 0.0 expect(outer.offset, 0.0); expect(inner.offset, 0.0); await tester.pumpAndSettle(); // Assert values settle at 0.0 expect(outer.offset, 0.0); expect(inner.offset, 0.0); }); testWidgets('NestedScrollView overscroll and release and hold', (WidgetTester tester) async { await tester.pumpWidget(buildTest()); expect(find.text('aaa2'), findsOneWidget); await tester.pump(const Duration(milliseconds: 250)); final Offset point1 = tester.getCenter(find.text('aaa1')); if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { await tester.dragFrom(point1, const Offset(0.0, 400.0)); } else { await tester.dragFrom(point1, const Offset(0.0, 200.0)); } await tester.pump(); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); await tester.flingFrom(point1, const Offset(0.0, -80.0), 50000.0); await tester.pump(const Duration(milliseconds: 20)); final Offset point2 = tester.getCenter(find.text('aaa1')); expect(point2.dy, greaterThan(point1.dy)); expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('NestedScrollView overscroll and release and hold', (WidgetTester tester) async { await tester.pumpWidget(buildTest()); expect(find.text('aaa2'), findsOneWidget); await tester.pump(const Duration(milliseconds: 250)); final Offset point = tester.getCenter(find.text('aaa1')); if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { await tester.flingFrom(point, const Offset(0.0, 200.0), 15000.0); } else { await tester.flingFrom(point, const Offset(0.0, 200.0), 5000.0); } await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 10)); expect(find.text('aaa2'), findsNothing); final TestGesture gesture1 = await tester.startGesture(point); await tester.pump(const Duration(milliseconds: 5000)); expect(find.text('aaa2'), findsNothing); await gesture1.moveBy(const Offset(0.0, 50.0)); await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 10)); expect(find.text('aaa2'), findsNothing); await tester.pump(const Duration(milliseconds: 1000)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('NestedScrollView overscroll and release', (WidgetTester tester) async { await tester.pumpWidget(buildTest()); expect(find.text('aaa2'), findsOneWidget); await tester.pump(const Duration(milliseconds: 500)); final TestGesture gesture1 = await tester.startGesture( tester.getCenter(find.text('aaa1')), ); await gesture1.moveBy(const Offset(0.0, 200.0)); await tester.pumpAndSettle(); expect(find.text('aaa2'), findsNothing); await tester.pump(const Duration(seconds: 1)); await gesture1.up(); await tester.pumpAndSettle(); expect(find.text('aaa2'), findsOneWidget); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('NestedScrollView', (WidgetTester tester) async { await tester.pumpWidget(buildTest()); expect(find.text('aaa2'), findsOneWidget); expect(find.text('aaa3'), findsNothing); expect(find.text('bbb1'), findsNothing); await tester.pump(const Duration(milliseconds: 250)); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); await tester.drag(find.text('AA'), const Offset(0.0, -20.0)); await tester.pump(const Duration(milliseconds: 250)); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 180.0, ); await tester.drag(find.text('AA'), const Offset(0.0, -20.0)); await tester.pump(const Duration(milliseconds: 250)); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 160.0, ); await tester.drag(find.text('AA'), const Offset(0.0, -20.0)); await tester.pump(const Duration(milliseconds: 250)); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 140.0, ); expect(find.text('aaa4'), findsNothing); await tester.pump(const Duration(milliseconds: 250)); await tester.fling(find.text('AA'), const Offset(0.0, -50.0), 10000.0); await tester.pumpAndSettle(const Duration(milliseconds: 250)); expect(find.text('aaa4'), findsOneWidget); final double minHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(minHeight, lessThan(140.0)); await tester.pump(const Duration(milliseconds: 250)); await tester.tap(find.text('BB')); await tester.pumpAndSettle(const Duration(milliseconds: 250)); expect(find.text('aaa4'), findsNothing); expect(find.text('bbb1'), findsOneWidget); await tester.pump(const Duration(milliseconds: 250)); await tester.tap(find.text('CC')); await tester.pumpAndSettle(const Duration(milliseconds: 250)); expect(find.text('bbb1'), findsNothing); expect(find.text('ccc1'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, minHeight, ); await tester.pump(const Duration(milliseconds: 250)); await tester.fling(find.text('AA'), const Offset(0.0, 50.0), 10000.0); await tester.pumpAndSettle(const Duration(milliseconds: 250)); expect(find.text('ccc1'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); }); testWidgets('NestedScrollView with a ScrollController', (WidgetTester tester) async { final ScrollController controller = ScrollController( initialScrollOffset: 50.0, ); addTearDown(controller.dispose); late double scrollOffset; controller.addListener(() { scrollOffset = controller.offset; }); await tester.pumpWidget(buildTest(controller: controller)); expect(controller.position.minScrollExtent, 0.0); expect(controller.position.pixels, 50.0); expect(controller.position.maxScrollExtent, 200.0); // The appbar's expandedHeight - initialScrollOffset = 150. expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 150.0, ); // Fully expand the appbar by scrolling (no animation) to 0.0. controller.jumpTo(0.0); await tester.pumpAndSettle(); expect(scrollOffset, 0.0); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); // Scroll back to 50.0 animating over 100ms. controller.animateTo( 50.0, duration: const Duration(milliseconds: 100), curve: Curves.linear, ); await tester.pump(); await tester.pump(); expect(scrollOffset, 0.0); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); await tester.pump(const Duration(milliseconds: 50)); // 50ms - halfway to scroll offset = 50.0. expect(scrollOffset, 25.0); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 175.0, ); await tester.pump(const Duration(milliseconds: 50)); // 100ms - all the way to scroll offset = 50.0. expect(scrollOffset, 50.0); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 150.0, ); // Scroll to the end, (we're not scrolling to the end of the list that contains aaa1, // just to the end of the outer scrollview). Verify that the first item in each tab // is still visible. controller.jumpTo(controller.position.maxScrollExtent); await tester.pumpAndSettle(); expect(scrollOffset, 200.0); expect(find.text('aaa1'), findsOneWidget); await tester.tap(find.text('BB')); await tester.pumpAndSettle(); expect(find.text('bbb1'), findsOneWidget); await tester.tap(find.text('CC')); await tester.pumpAndSettle(); expect(find.text('ccc1'), findsOneWidget); await tester.tap(find.text('DD')); await tester.pumpAndSettle(); expect(find.text('ddd1'), findsOneWidget); }); testWidgets('Three NestedScrollViews with one ScrollController', (WidgetTester tester) async { final TrackingScrollController controller = TrackingScrollController(); addTearDown(controller.dispose); expect(controller.mostRecentlyUpdatedPosition, isNull); expect(controller.initialScrollOffset, 0.0); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( children: <Widget>[ buildTest(controller: controller, title: 'Page0'), buildTest(controller: controller, title: 'Page1'), buildTest(controller: controller, title: 'Page2'), ], ), )); // Initially Page0 is visible and Page0's appbar is fully expanded (height = 200.0). expect(find.text('Page0'), findsOneWidget); expect(find.text('Page1'), findsNothing); expect(find.text('Page2'), findsNothing); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); // A scroll collapses Page0's appbar to 150.0. controller.jumpTo(50.0); await tester.pumpAndSettle(); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 150.0, ); // Fling to Page1. Page1's appbar height is the same as the appbar for Page0. await tester.fling(find.text('Page0'), const Offset(-100.0, 0.0), 10000.0); await tester.pumpAndSettle(); expect(find.text('Page0'), findsNothing); expect(find.text('Page1'), findsOneWidget); expect(find.text('Page2'), findsNothing); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 150.0, ); // Expand Page1's appbar and then fling to Page2. Page2's appbar appears // fully expanded. controller.jumpTo(0.0); await tester.pumpAndSettle(); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); await tester.fling(find.text('Page1'), const Offset(-100.0, 0.0), 10000.0); await tester.pumpAndSettle(); expect(find.text('Page0'), findsNothing); expect(find.text('Page1'), findsNothing); expect(find.text('Page2'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); }); testWidgets('NestedScrollViews with custom physics', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], child: MediaQuery( data: const MediaQueryData(), child: NestedScrollView( physics: const _CustomPhysics(), headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ const SliverAppBar( floating: true, title: Text('AA'), ), ]; }, body: Container(), ), ), ), )); expect(find.text('AA'), findsOneWidget); await tester.pump(const Duration(milliseconds: 500)); final Offset point1 = tester.getCenter(find.text('AA')); await tester.dragFrom(point1, const Offset(0.0, 200.0)); await tester.pump(const Duration(milliseconds: 20)); final Offset point2 = tester.getCenter(find.text( 'AA', skipOffstage: false, )); expect(point1.dy, greaterThan(point2.dy)); }); testWidgets('NestedScrollViews respect NeverScrollableScrollPhysics', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/113753 await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], child: MediaQuery( data: const MediaQueryData(), child: NestedScrollView( physics: const NeverScrollableScrollPhysics(), headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ const SliverAppBar( floating: true, title: Text('AA'), ), ]; }, body: Container(), ), ), ), )); expect(find.text('AA'), findsOneWidget); final Offset point1 = tester.getCenter(find.text('AA')); await tester.dragFrom(point1, const Offset(0.0, -200.0)); await tester.pump(); final Offset point2 = tester.getCenter(find.text( 'AA', skipOffstage: false, )); expect(point1, point2); }); testWidgets('NestedScrollView and internal scrolling', (WidgetTester tester) async { debugDisableShadows = false; const List<String> tabs = <String>['Hello', 'World']; int buildCount = 0; await tester.pumpWidget( MaterialApp(theme: ThemeData(useMaterial3: false), home: Material(child: // THE FOLLOWING SECTION IS FROM THE NestedScrollView DOCUMENTATION // (EXCEPT FOR THE CHANGES TO THE buildCount COUNTER) DefaultTabController( length: tabs.length, // This is the number of tabs. child: NestedScrollView( dragStartBehavior: DragStartBehavior.down, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { buildCount += 1; // THIS LINE IS NOT IN THE ORIGINAL -- ADDED FOR TEST // These are the slivers that show up in the "outer" scroll view. return <Widget>[ SliverOverlapAbsorber( // This widget takes the overlapping behavior of the // SliverAppBar, and redirects it to the SliverOverlapInjector // below. If it is missing, then it is possible for the nested // "inner" scroll view below to end up under the SliverAppBar // even when the inner scroll view thinks it has not been // scrolled. This is not necessary if the // "headerSliverBuilder" only builds widgets that do not // overlap the next sliver. handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverAppBar( title: const Text('Books'), // This is the title in the app bar. pinned: true, expandedHeight: 150.0, // The "forceElevated" property causes the SliverAppBar to // show a shadow. The "innerBoxIsScrolled" parameter is true // when the inner scroll view is scrolled beyond its "zero" // point, i.e. when it appears to be scrolled below the // SliverAppBar. Without this, there are cases where the // shadow would appear or not appear inappropriately, // because the SliverAppBar is not actually aware of the // precise position of the inner scroll views. forceElevated: innerBoxIsScrolled, bottom: TabBar( // These are the widgets to put in each tab in the tab // bar. tabs: tabs.map<Widget>((String name) => Tab(text: name)).toList(), dragStartBehavior: DragStartBehavior.down, ), ), ), ]; }, body: TabBarView( dragStartBehavior: DragStartBehavior.down, // These are the contents of the tab views, below the tabs. children: tabs.map<Widget>((String name) { return SafeArea( top: false, bottom: false, child: Builder( // This Builder is needed to provide a BuildContext that is // "inside" the NestedScrollView, so that // sliverOverlapAbsorberHandleFor() can find the // NestedScrollView. builder: (BuildContext context) { return CustomScrollView( // The "controller" and "primary" members should be left // unset, so that the NestedScrollView can control this // inner scroll view. // If the "controller" property is set, then this scroll // view will not be associated with the // NestedScrollView. The PageStorageKey should be unique // to this ScrollView; it allows the list to remember // its scroll position when the tab view is not on the // screen. key: PageStorageKey<String>(name), dragStartBehavior: DragStartBehavior.down, slivers: <Widget>[ SliverOverlapInjector( // This is the flip side of the // SliverOverlapAbsorber above. handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), ), SliverPadding( padding: const EdgeInsets.all(8.0), // In this example, the inner scroll view has // fixed-height list items, hence the use of // SliverFixedExtentList. However, one could use any // sliver widget here, e.g. SliverList or // SliverGrid. sliver: SliverFixedExtentList( // The items in this example are fixed to 48 // pixels high. This matches the Material Design // spec for ListTile widgets. itemExtent: 48.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { // This builder is called for each child. // In this example, we just number each list // item. return ListTile( title: Text('Item $index'), ); }, // The childCount of the // SliverChildBuilderDelegate specifies how many // children this inner list has. In this // example, each tab has a list of exactly 30 // items, but this is arbitrary. childCount: 30, ), ), ), ], ); }, ), ); }).toList(), ), ), ), // END )), ); Object? dfsFindPhysicalLayer(RenderObject object) { expect(object, isNotNull); if (object is RenderPhysicalModel || object is RenderPhysicalShape) { return object; } final List<RenderObject> children = <RenderObject>[]; object.visitChildren(children.add); for (final RenderObject child in children) { final Object? result = dfsFindPhysicalLayer(child); if (result != null) { return result; } } return null; } final RenderObject nestedScrollViewLayer = find.byType(NestedScrollView).evaluate().first.renderObject!; void checkPhysicalLayer({required double elevation}) { final dynamic physicalModel = dfsFindPhysicalLayer(nestedScrollViewLayer); expect(physicalModel, isNotNull); // ignore: avoid_dynamic_calls expect(physicalModel.elevation, equals(elevation)); } int expectedBuildCount = 0; expectedBuildCount += 1; expect(buildCount, expectedBuildCount); expect(find.text('Item 2'), findsOneWidget); expect(find.text('Item 18'), findsNothing); checkPhysicalLayer(elevation: 0); // scroll down final TestGesture gesture0 = await tester.startGesture( tester.getCenter(find.text('Item 2')), ); await gesture0.moveBy(const Offset(0.0, -120.0)); // tiny bit more than the pinned app bar height (56px * 2) await tester.pump(); expect(buildCount, expectedBuildCount); expect(find.text('Item 2'), findsOneWidget); expect(find.text('Item 18'), findsNothing); await gesture0.up(); await tester.pump(const Duration(milliseconds: 1)); // start shadow animation expectedBuildCount += 1; expect(buildCount, expectedBuildCount); await tester.pump(const Duration(milliseconds: 1)); // during shadow animation expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 0.00018262863159179688); await tester.pump(const Duration(seconds: 1)); // end shadow animation expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 4); // scroll down final TestGesture gesture1 = await tester.startGesture( tester.getCenter(find.text('Item 2')), ); await gesture1.moveBy(const Offset(0.0, -800.0)); await tester.pump(); expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 4); expect(find.text('Item 2'), findsNothing); expect(find.text('Item 18'), findsOneWidget); await gesture1.up(); await tester.pump(const Duration(seconds: 1)); expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 4); // swipe left to bring in tap on the right final TestGesture gesture2 = await tester.startGesture( tester.getCenter(find.byType(NestedScrollView)), ); await gesture2.moveBy(const Offset(-400.0, 0.0)); await tester.pump(); expect(buildCount, expectedBuildCount); expect(find.text('Item 18'), findsOneWidget); expect(find.text('Item 2'), findsOneWidget); expect(find.text('Item 0'), findsOneWidget); expect( tester.getTopLeft( find.ancestor( of: find.text('Item 0'), matching: find.byType(ListTile), ), ).dy, tester.getBottomLeft(find.byType(AppBar)).dy + 8.0, ); checkPhysicalLayer(elevation: 4); await gesture2.up(); await tester.pump(); // start sideways scroll await tester.pump(const Duration(seconds: 1)); // end sideways scroll, triggers shadow going away expect(buildCount, expectedBuildCount); await tester.pump(const Duration(seconds: 1)); // start shadow going away expectedBuildCount += 1; expect(buildCount, expectedBuildCount); await tester.pump(const Duration(seconds: 1)); // end shadow going away expect(buildCount, expectedBuildCount); expect(find.text('Item 18'), findsNothing); expect(find.text('Item 2'), findsOneWidget); checkPhysicalLayer(elevation: 0); await tester.pump(const Duration(seconds: 1)); // just checking we don't rebuild... expect(buildCount, expectedBuildCount); // peek left to see it's still in the right place final TestGesture gesture3 = await tester.startGesture( tester.getCenter(find.byType(NestedScrollView)), ); await gesture3.moveBy(const Offset(400.0, 0.0)); await tester.pump(); // bring the left page into view expect(buildCount, expectedBuildCount); await tester.pump(); // shadow comes back starting here expectedBuildCount += 1; expect(buildCount, expectedBuildCount); expect(find.text('Item 18'), findsOneWidget); expect(find.text('Item 2'), findsOneWidget); checkPhysicalLayer(elevation: 0); await tester.pump(const Duration(seconds: 1)); // shadow finishes coming back expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 4); await gesture3.moveBy(const Offset(-400.0, 0.0)); await gesture3.up(); await tester.pump(); // left tab view goes away expect(buildCount, expectedBuildCount); await tester.pump(); // shadow goes away starting here expectedBuildCount += 1; expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 4); await tester.pump(const Duration(seconds: 1)); // shadow finishes going away expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 0); // scroll back up final TestGesture gesture4 = await tester.startGesture( tester.getCenter(find.byType(NestedScrollView)), ); await gesture4.moveBy(const Offset(0.0, 200.0)); // expands the appbar again await tester.pump(); expect(buildCount, expectedBuildCount); expect(find.text('Item 2'), findsOneWidget); expect(find.text('Item 18'), findsNothing); checkPhysicalLayer(elevation: 0); await gesture4.up(); await tester.pump(const Duration(seconds: 1)); expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 0); // peek left to see it's now back at zero final TestGesture gesture5 = await tester.startGesture( tester.getCenter(find.byType(NestedScrollView)), ); await gesture5.moveBy(const Offset(400.0, 0.0)); await tester.pump(); // bring the left page into view await tester.pump(); // shadow would come back starting here, but there's no shadow to show expect(buildCount, expectedBuildCount); expect(find.text('Item 18'), findsNothing); expect(find.text('Item 2'), findsNWidgets(2)); checkPhysicalLayer(elevation: 0); await tester.pump(const Duration(seconds: 1)); // shadow would be finished coming back checkPhysicalLayer(elevation: 0); await gesture5.up(); await tester.pump(); // right tab view goes away await tester.pumpAndSettle(); expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 0); debugDisableShadows = true; }); testWidgets('NestedScrollView and bouncing', (WidgetTester tester) async { // This verifies that overscroll bouncing works correctly on iOS. For // example, this checks that if you pull to overscroll, friction is applied; // it also makes sure that if you scroll back the other way, the scroll // positions of the inner and outer list don't have a discontinuity. const Key key1 = ValueKey<int>(1); const Key key2 = ValueKey<int>(2); await tester.pumpWidget( MaterialApp( home: Material( child: DefaultTabController( length: 1, child: NestedScrollView( dragStartBehavior: DragStartBehavior.down, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ const SliverPersistentHeader( delegate: TestHeader( key: key1, minExtent: 100.0, maxExtent: 100.0, ), ), ]; }, body: const SingleChildScrollView( dragStartBehavior: DragStartBehavior.down, child: SizedBox( height: 1000.0, child: Placeholder(key: key2), ), ), ), ), ), ), ); expect( tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), ); expect( tester.getRect(find.byKey(key2)), const Rect.fromLTWH(0.0, 100.0, 800.0, 1000.0), ); final TestGesture gesture = await tester.startGesture( const Offset(10.0, 10.0), ); await gesture.moveBy(const Offset(0.0, -10.0)); // scroll up await tester.pump(); expect( tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, -10.0, 800.0, 100.0), ); expect( tester.getRect(find.byKey(key2)), const Rect.fromLTWH(0.0, 90.0, 800.0, 1000.0), ); await gesture.moveBy(const Offset(0.0, 10.0)); // scroll back to origin await tester.pump(); expect( tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), ); expect( tester.getRect(find.byKey(key2)), const Rect.fromLTWH(0.0, 100.0, 800.0, 1000.0), ); await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll await tester.pump(); expect( tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), ); expect(tester.getRect(find.byKey(key2)).top, greaterThan(100.0)); expect(tester.getRect(find.byKey(key2)).top, lessThan(130.0)); await gesture.moveBy(const Offset(0.0, -1.0)); // scroll back a little await tester.pump(); expect( tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), ); expect(tester.getRect(find.byKey(key2)).top, greaterThan(100.0)); expect(tester.getRect(find.byKey(key2)).top, lessThan(129.0)); await gesture.moveBy(const Offset(0.0, -10.0)); // scroll back a lot await tester.pump(); expect( tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), ); await gesture.moveBy(const Offset(0.0, 20.0)); // overscroll again await tester.pump(); expect( tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), ); await gesture.up(); debugDefaultTargetPlatformOverride = null; }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); group('NestedScrollViewState exposes inner and outer controllers', () { testWidgets('Scrolling by less than the outer extent does not scroll the inner body', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey, expanded: false, )); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 104.0); final double scrollExtent = appBarHeight - 50.0; expect(globalKey.currentState!.outerController.offset, 0.0); expect(globalKey.currentState!.innerController.offset, 0.0); // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. final TestGesture gesture = await tester.startGesture(Offset( 0.0, appBarHeight + 1.0, )); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // This is not an expanded AppBar. expect(appBarHeight, 104.0); // The outer scroll controller should show an offset of the applied // scrollExtent. expect(globalKey.currentState!.outerController.offset, 54.0); // the inner scroll controller should not have scrolled. expect(globalKey.currentState!.innerController.offset, 0.0); }); testWidgets('Scrolling by exactly the outer extent does not scroll the inner body', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey, expanded: false, )); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 104.0); final double scrollExtent = appBarHeight; expect(globalKey.currentState!.outerController.offset, 0.0); expect(globalKey.currentState!.innerController.offset, 0.0); // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. final TestGesture gesture = await tester.startGesture(Offset( 0.0, appBarHeight + 1.0, )); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // This is not an expanded AppBar. expect(appBarHeight, 104.0); // The outer scroll controller should show an offset of the applied // scrollExtent. expect(globalKey.currentState!.outerController.offset, 104.0); // the inner scroll controller should not have scrolled. expect(globalKey.currentState!.innerController.offset, 0.0); }); testWidgets('Scrolling by greater than the outer extent scrolls the inner body', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey, expanded: false, )); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 104.0); final double scrollExtent = appBarHeight + 50.0; expect(globalKey.currentState!.outerController.offset, 0.0); expect(globalKey.currentState!.innerController.offset, 0.0); // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. final TestGesture gesture = await tester.startGesture(Offset( 0.0, appBarHeight + 1.0, )); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // This is not an expanded AppBar. expect(appBarHeight, 104.0); // The outer scroll controller should show an offset of the applied // scrollExtent. expect(globalKey.currentState!.outerController.offset, appBarHeight); // the inner scroll controller should have scrolled equivalent to the // difference between the applied scrollExtent and the outer extent. expect( globalKey.currentState!.innerController.offset, scrollExtent - appBarHeight, ); }); testWidgets('Inertia-cancel event does not modify either position.', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey, expanded: false, )); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 104.0); final double scrollExtent = appBarHeight + 50.0; expect(globalKey.currentState!.outerController.offset, 0.0); expect(globalKey.currentState!.innerController.offset, 0.0); // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. final TestGesture gesture = await tester.startGesture(Offset( 0.0, appBarHeight + 1.0, )); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // This is not an expanded AppBar. expect(appBarHeight, 104.0); // The outer scroll controller should show an offset of the applied // scrollExtent. expect(globalKey.currentState!.outerController.offset, appBarHeight); // the inner scroll controller should have scrolled equivalent to the // difference between the applied scrollExtent and the outer extent. expect( globalKey.currentState!.innerController.offset, scrollExtent - appBarHeight, ); final TestPointer testPointer = TestPointer(3, ui.PointerDeviceKind.trackpad); await tester.sendEventToBinding(testPointer.addPointer( location: Offset(0.0, appBarHeight + 1.0) )); await tester.sendEventToBinding(testPointer.scrollInertiaCancel()); // ensure no change. expect(globalKey.currentState!.outerController.offset, appBarHeight); expect( globalKey.currentState!.innerController.offset, scrollExtent - appBarHeight, ); }); testWidgets('scrolling by less than the expanded outer extent does not scroll the inner body', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest(key: globalKey)); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 200.0); final double scrollExtent = appBarHeight - 50.0; expect(globalKey.currentState!.outerController.offset, 0.0); expect(globalKey.currentState!.innerController.offset, 0.0); // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. final TestGesture gesture = await tester.startGesture(Offset( 0.0, appBarHeight + 1.0, )); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // This is an expanding AppBar. expect(appBarHeight, 104.0); // The outer scroll controller should show an offset of the applied // scrollExtent. expect(globalKey.currentState!.outerController.offset, 150.0); // the inner scroll controller should not have scrolled. expect(globalKey.currentState!.innerController.offset, 0.0); }); testWidgets('scrolling by exactly the expanded outer extent does not scroll the inner body', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest(key: globalKey)); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 200.0); final double scrollExtent = appBarHeight; expect(globalKey.currentState!.outerController.offset, 0.0); expect(globalKey.currentState!.innerController.offset, 0.0); // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. final TestGesture gesture = await tester.startGesture(Offset( 0.0, appBarHeight + 1.0, )); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // This is an expanding AppBar. expect(appBarHeight, 104.0); // The outer scroll controller should show an offset of the applied // scrollExtent. expect(globalKey.currentState!.outerController.offset, 200.0); // the inner scroll controller should not have scrolled. expect(globalKey.currentState!.innerController.offset, 0.0); }); testWidgets('scrolling by greater than the expanded outer extent scrolls the inner body', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest(key: globalKey)); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 200.0); final double scrollExtent = appBarHeight + 50.0; expect(globalKey.currentState!.outerController.offset, 0.0); expect(globalKey.currentState!.innerController.offset, 0.0); // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. final TestGesture gesture = await tester.startGesture(Offset( 0.0, appBarHeight + 1.0, )); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // This is an expanding AppBar. expect(appBarHeight, 104.0); // The outer scroll controller should show an offset of the applied // scrollExtent. expect(globalKey.currentState!.outerController.offset, 200.0); // the inner scroll controller should have scrolled equivalent to the // difference between the applied scrollExtent and the outer extent. expect(globalKey.currentState!.innerController.offset, 50.0); }); testWidgets( 'NestedScrollViewState.outerController should correspond to NestedScrollView.controller', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget(buildTest( controller: scrollController, key: globalKey, )); // Scroll to compare offsets between controllers. final TestGesture gesture = await tester.startGesture(const Offset( 0.0, 100.0, )); await gesture.moveBy(const Offset(0.0, -100.0)); await tester.pump(); expect( scrollController.offset, globalKey.currentState!.outerController.offset, ); expect( tester.widget<NestedScrollView>(find.byType(NestedScrollView)).controller!.offset, globalKey.currentState!.outerController.offset, ); }, ); group('manipulating controllers when', () { testWidgets('outer: not scrolled, inner: not scrolled', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey1 = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey1, expanded: false, )); expect(globalKey1.currentState!.outerController.position.pixels, 0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); final double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // Manipulating Inner globalKey1.currentState!.innerController.jumpTo(100.0); expect(globalKey1.currentState!.innerController.position.pixels, 100.0); expect( globalKey1.currentState!.outerController.position.pixels, appBarHeight, ); globalKey1.currentState!.innerController.jumpTo(0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); expect( globalKey1.currentState!.outerController.position.pixels, appBarHeight, ); // Reset final GlobalKey<NestedScrollViewState> globalKey2 = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey2, expanded: false, )); expect(globalKey2.currentState!.outerController.position.pixels, 0.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); // Manipulating Outer globalKey2.currentState!.outerController.jumpTo(100.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); expect(globalKey2.currentState!.outerController.position.pixels, 100.0); globalKey2.currentState!.outerController.jumpTo(0.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); expect(globalKey2.currentState!.outerController.position.pixels, 0.0); }); testWidgets('outer: not scrolled, inner: scrolled', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey1 = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey1, expanded: false, )); expect(globalKey1.currentState!.outerController.position.pixels, 0.0); globalKey1.currentState!.innerController.position.setPixels(10.0); expect(globalKey1.currentState!.innerController.position.pixels, 10.0); final double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // Manipulating Inner globalKey1.currentState!.innerController.jumpTo(100.0); expect(globalKey1.currentState!.innerController.position.pixels, 100.0); expect( globalKey1.currentState!.outerController.position.pixels, appBarHeight, ); globalKey1.currentState!.innerController.jumpTo(0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); expect( globalKey1.currentState!.outerController.position.pixels, appBarHeight, ); // Reset final GlobalKey<NestedScrollViewState> globalKey2 = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey2, expanded: false, )); expect(globalKey2.currentState!.outerController.position.pixels, 0.0); globalKey2.currentState!.innerController.position.setPixels(10.0); expect(globalKey2.currentState!.innerController.position.pixels, 10.0); // Manipulating Outer globalKey2.currentState!.outerController.jumpTo(100.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); expect(globalKey2.currentState!.outerController.position.pixels, 100.0); globalKey2.currentState!.outerController.jumpTo(0.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); expect(globalKey2.currentState!.outerController.position.pixels, 0.0); }); testWidgets('outer: scrolled, inner: not scrolled', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey1 = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey1, expanded: false, )); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); globalKey1.currentState!.outerController.position.setPixels(10.0); expect(globalKey1.currentState!.outerController.position.pixels, 10.0); final double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // Manipulating Inner globalKey1.currentState!.innerController.jumpTo(100.0); expect(globalKey1.currentState!.innerController.position.pixels, 100.0); expect( globalKey1.currentState!.outerController.position.pixels, appBarHeight, ); globalKey1.currentState!.innerController.jumpTo(0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); expect( globalKey1.currentState!.outerController.position.pixels, appBarHeight, ); // Reset final GlobalKey<NestedScrollViewState> globalKey2 = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey2, expanded: false, )); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); globalKey2.currentState!.outerController.position.setPixels(10.0); expect(globalKey2.currentState!.outerController.position.pixels, 10.0); // Manipulating Outer globalKey2.currentState!.outerController.jumpTo(100.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); expect(globalKey2.currentState!.outerController.position.pixels, 100.0); globalKey2.currentState!.outerController.jumpTo(0.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); expect(globalKey2.currentState!.outerController.position.pixels, 0.0); }); testWidgets('outer: scrolled, inner: scrolled', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey1 = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey1, expanded: false, )); globalKey1.currentState!.innerController.position.setPixels(10.0); expect(globalKey1.currentState!.innerController.position.pixels, 10.0); globalKey1.currentState!.outerController.position.setPixels(10.0); expect(globalKey1.currentState!.outerController.position.pixels, 10.0); final double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; // Manipulating Inner globalKey1.currentState!.innerController.jumpTo(100.0); expect(globalKey1.currentState!.innerController.position.pixels, 100.0); expect( globalKey1.currentState!.outerController.position.pixels, appBarHeight, ); globalKey1.currentState!.innerController.jumpTo(0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); expect( globalKey1.currentState!.outerController.position.pixels, appBarHeight, ); // Reset final GlobalKey<NestedScrollViewState> globalKey2 = GlobalKey(); await tester.pumpWidget(buildTest( key: globalKey2, expanded: false, )); globalKey2.currentState!.innerController.position.setPixels(10.0); expect(globalKey2.currentState!.innerController.position.pixels, 10.0); globalKey2.currentState!.outerController.position.setPixels(10.0); expect(globalKey2.currentState!.outerController.position.pixels, 10.0); // Manipulating Outer globalKey2.currentState!.outerController.jumpTo(100.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); expect(globalKey2.currentState!.outerController.position.pixels, 100.0); globalKey2.currentState!.outerController.jumpTo(0.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); expect(globalKey2.currentState!.outerController.position.pixels, 0.0); }); }); }); // Regression test for https://github.com/flutter/flutter/issues/39963. testWidgets('NestedScrollView with SliverOverlapAbsorber in or out of the first screen', (WidgetTester tester) async { await tester.pumpWidget(const _TestLayoutExtentIsNegative(1)); await tester.pumpWidget(const _TestLayoutExtentIsNegative(10)); }); group('NestedScrollView can float outer sliver with inner scroll view:', () { Widget buildFloatTest({ GlobalKey? appBarKey, GlobalKey? nestedKey, ScrollController? controller, bool floating = false, bool pinned = false, bool snap = false, bool nestedFloat = false, bool expanded = false, }) { return MaterialApp( home: Scaffold( body: NestedScrollView( key: nestedKey, controller: controller, floatHeaderSlivers: nestedFloat, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverAppBar( key: appBarKey, title: const Text('Test Title'), floating: floating, pinned: pinned, snap: snap, expandedHeight: expanded ? 200.0 : 0.0, ), ), ]; }, body: Builder( builder: (BuildContext context) { return CustomScrollView( slivers: <Widget>[ SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)), SliverFixedExtentList( itemExtent: 50.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => ListTile(title: Text('Item $index')), childCount: 30, ), ), ], ); }, ), ), ), ); } double verifyGeometry({ required GlobalKey key, required double paintExtent, bool extentGreaterThan = false, bool extentLessThan = false, required bool visible, }) { final RenderSliver target = key.currentContext!.findRenderObject()! as RenderSliver; final SliverGeometry geometry = target.geometry!; expect(target.parent, isA<RenderSliverOverlapAbsorber>()); expect(geometry.visible, visible); if (extentGreaterThan) { expect(geometry.paintExtent, greaterThan(paintExtent)); } else if (extentLessThan) { expect(geometry.paintExtent, lessThan(paintExtent)); } else { expect(geometry.paintExtent, paintExtent); } return geometry.paintExtent; } testWidgets('float', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, nestedFloat: true, appBarKey: appBarKey, )); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. // We will not scroll back the same amount to indicate that we are // floating in before reaching the top of the inner scrollable. final Offset point1 = tester.getCenter(find.text('Item 5')); await tester.dragFrom(point1, const Offset(0.0, -300.0)); await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); // The outer scrollable should float back in, inner should not change await tester.dragFrom(point1, const Offset(0.0, 50.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // Float the rest of the way in. await tester.dragFrom(point1, const Offset(0.0, 150.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); testWidgets('float expanded', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, nestedFloat: true, expanded: true, appBarKey: appBarKey, )); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. // We will not scroll back the same amount to indicate that we are // floating in before reaching the top of the inner scrollable. final Offset point1 = tester.getCenter(find.text('Item 5')); await tester.dragFrom(point1, const Offset(0.0, -300.0)); await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); // The outer scrollable should float back in, inner should not change // On initial float in, the app bar is collapsed. await tester.dragFrom(point1, const Offset(0.0, 50.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // The inner scrollable should receive leftover delta after the outer has // been scrolled back in fully. await tester.dragFrom(point1, const Offset(0.0, 200.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); }); testWidgets('float with pointer signal', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, nestedFloat: true, appBarKey: appBarKey, )); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(scrollEventLocation); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. // We will not scroll back the same amount to indicate that we are // floating in before reaching the top of the inner scrollable. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0))); await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); // The outer scrollable should float back in, inner should not change await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -50.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // Float the rest of the way in. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -150.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); testWidgets('snap with pointer signal', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, snap: true, appBarKey: appBarKey, )); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(scrollEventLocation); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. // We will not scroll back the same amount to indicate that we are // snapping in before reaching the top of the inner scrollable. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0))); await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); // The snap animation should be triggered to expand the app bar await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -30.0))); await tester.pumpAndSettle(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away a bit more to trigger the snap close animation. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 30.0))); await tester.pumpAndSettle(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect(find.byType(AppBar), findsNothing); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); }); testWidgets('float expanded with pointer signal', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, nestedFloat: true, expanded: true, appBarKey: appBarKey, )); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(scrollEventLocation); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. // We will not scroll back the same amount to indicate that we are // floating in before reaching the top of the inner scrollable. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0))); await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); // The outer scrollable should float back in, inner should not change // On initial float in, the app bar is collapsed. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -50.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // The inner scrollable should receive leftover delta after the outer has // been scrolled back in fully. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -200.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); }); testWidgets('only snap', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); final GlobalKey<NestedScrollViewState> nestedKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, snap: true, appBarKey: appBarKey, nestedKey: nestedKey, )); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll down the list, the app bar should scroll away and no longer be // visible. final Offset point1 = tester.getCenter(find.text('Item 5')); await tester.dragFrom(point1, const Offset(0.0, -300.0)); await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); // The outer scroll view should be at its full extent, here the size of // the app bar. expect(nestedKey.currentState!.outerController.offset, 56.0); // Animate In // Drag the scrollable up and down. The app bar should not snap open, nor // should it float in. final TestGesture animateInGesture = await tester.startGesture(point1); await animateInGesture.moveBy(const Offset(0.0, 100.0)); // Should not float in await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); expect(nestedKey.currentState!.outerController.offset, 56.0); await animateInGesture.moveBy(const Offset(0.0, -50.0)); // No float out await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); expect(nestedKey.currentState!.outerController.offset, 56.0); // Trigger the snap open animation: drag down and release await animateInGesture.moveBy(const Offset(0.0, 10.0)); await animateInGesture.up(); // Now verify that the appbar is animating open await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); double lastExtent = verifyGeometry( key: appBarKey, paintExtent: 10.0, // >10.0 since 0.0 + 10.0 extentGreaterThan: true, visible: true, ); // The outer scroll offset should remain unchanged. expect(nestedKey.currentState!.outerController.offset, 56.0); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry( key: appBarKey, paintExtent: lastExtent, extentGreaterThan: true, visible: true, ); expect(nestedKey.currentState!.outerController.offset, 56.0); // The animation finishes when the appbar is full height. await tester.pumpAndSettle(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); expect(nestedKey.currentState!.outerController.offset, 56.0); // Animate Out // Trigger the snap close animation: drag up and release final TestGesture animateOutGesture = await tester.startGesture(point1); await animateOutGesture.moveBy(const Offset(0.0, -10.0)); await animateOutGesture.up(); // Now verify that the appbar is animating closed await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); lastExtent = verifyGeometry( key: appBarKey, paintExtent: 46.0, // <46.0 since 56.0 - 10.0 extentLessThan: true, visible: true, ); expect(nestedKey.currentState!.outerController.offset, 56.0); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry( key: appBarKey, paintExtent: lastExtent, extentLessThan: true, visible: true, ); expect(nestedKey.currentState!.outerController.offset, 56.0); // The animation finishes when the appbar is no longer in view. await tester.pumpAndSettle(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); expect(nestedKey.currentState!.outerController.offset, 56.0); }); testWidgets('only snap expanded', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); final GlobalKey<NestedScrollViewState> nestedKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, snap: true, expanded: true, appBarKey: appBarKey, nestedKey: nestedKey, )); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll down the list, the app bar should scroll away and no longer be // visible. final Offset point1 = tester.getCenter(find.text('Item 5')); await tester.dragFrom(point1, const Offset(0.0, -400.0)); await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); // The outer scroll view should be at its full extent, here the size of // the app bar. expect(nestedKey.currentState!.outerController.offset, 200.0); // Animate In // Drag the scrollable up and down. The app bar should not snap open, nor // should it float in. final TestGesture animateInGesture = await tester.startGesture(point1); await animateInGesture.moveBy(const Offset(0.0, 100.0)); // Should not float in await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); expect(nestedKey.currentState!.outerController.offset, 200.0); await animateInGesture.moveBy(const Offset(0.0, -50.0)); // No float out await tester.pump(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); expect(nestedKey.currentState!.outerController.offset, 200.0); // Trigger the snap open animation: drag down and release await animateInGesture.moveBy(const Offset(0.0, 10.0)); await animateInGesture.up(); // Now verify that the appbar is animating open await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); double lastExtent = verifyGeometry( key: appBarKey, paintExtent: 10.0, // >10.0 since 0.0 + 10.0 extentGreaterThan: true, visible: true, ); // The outer scroll offset should remain unchanged. expect(nestedKey.currentState!.outerController.offset, 200.0); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry( key: appBarKey, paintExtent: lastExtent, extentGreaterThan: true, visible: true, ); expect(nestedKey.currentState!.outerController.offset, 200.0); // The animation finishes when the appbar is full height. await tester.pumpAndSettle(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); expect(nestedKey.currentState!.outerController.offset, 200.0); // Animate Out // Trigger the snap close animation: drag up and release final TestGesture animateOutGesture = await tester.startGesture(point1); await animateOutGesture.moveBy(const Offset(0.0, -10.0)); await animateOutGesture.up(); // Now verify that the appbar is animating closed await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); lastExtent = verifyGeometry( key: appBarKey, paintExtent: 190.0, // <190.0 since 200.0 - 10.0 extentLessThan: true, visible: true, ); expect(nestedKey.currentState!.outerController.offset, 200.0); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry( key: appBarKey, paintExtent: lastExtent, extentLessThan: true, visible: true, ); expect(nestedKey.currentState!.outerController.offset, 200.0); // The animation finishes when the appbar is no longer in view. await tester.pumpAndSettle(); expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); expect(nestedKey.currentState!.outerController.offset, 200.0); }); testWidgets('float pinned', (WidgetTester tester) async { // This configuration should have the same behavior of a pinned app bar. // No floating should happen, and the app bar should persist. final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, pinned: true, nestedFloat: true, appBarKey: appBarKey, )); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. final Offset point1 = tester.getCenter(find.text('Item 5')); await tester.dragFrom(point1, const Offset(0.0, -300.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); await tester.dragFrom(point1, const Offset(0.0, 50.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); await tester.dragFrom(point1, const Offset(0.0, 150.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); testWidgets('float pinned expanded', (WidgetTester tester) async { // Only the expanded portion (flexible space) of the app bar should float // in and out. final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, pinned: true, expanded: true, nestedFloat: true, appBarKey: appBarKey, )); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. // The expanded portion of the app bar should collapse. final Offset point1 = tester.getCenter(find.text('Item 5')); await tester.dragFrom(point1, const Offset(0.0, -300.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll back some, the app bar should expand. await tester.dragFrom(point1, const Offset(0.0, 50.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 106.0, // 56.0 + 50.0 ); verifyGeometry(key: appBarKey, paintExtent: 106.0, visible: true); // Finish scrolling the rest of the way in. await tester.dragFrom(point1, const Offset(0.0, 150.0)); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); }); testWidgets('float pinned with pointer signal', (WidgetTester tester) async { // This configuration should have the same behavior of a pinned app bar. // No floating should happen, and the app bar should persist. final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, pinned: true, nestedFloat: true, appBarKey: appBarKey, )); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(scrollEventLocation); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -50.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -150.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); testWidgets('float pinned expanded with pointer signal', (WidgetTester tester) async { // Only the expanded portion (flexible space) of the app bar should float // in and out. final GlobalKey appBarKey = GlobalKey(); await tester.pumpWidget(buildFloatTest( floating: true, pinned: true, expanded: true, nestedFloat: true, appBarKey: appBarKey, )); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(scrollEventLocation); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. // The expanded portion of the app bar should collapse. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0, ); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll back some, the app bar should expand. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -50.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 106.0, // 56.0 + 50.0 ); verifyGeometry(key: appBarKey, paintExtent: 106.0, visible: true); // Finish scrolling the rest of the way in. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -150.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); }); }); group('Correctly handles 0 velocity inner ballistic scroll activity:', () { // Regression tests for https://github.com/flutter/flutter/issues/17096 Widget buildBallisticTest(ScrollController controller) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: NestedScrollView( controller: controller, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ const SliverAppBar( pinned: true, expandedHeight: 200.0, ), ]; }, body: ListView.builder( itemCount: 50, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(8.0), child: Text('Item $index'), ); }, ), ), ), ); } testWidgets('overscroll, hold for 0 velocity, and release', (WidgetTester tester) async { // Dragging into an overscroll and holding so that when released, the // ballistic scroll activity has a 0 velocity. final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildBallisticTest(controller)); // Last item of the inner scroll view. expect(find.text('Item 49'), findsNothing); // Scroll to bottom await tester.fling(find.text('Item 3'), const Offset(0.0, -50.0), 10000.0); await tester.pumpAndSettle(); // End of list expect(find.text('Item 49'), findsOneWidget); expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); // Overscroll, dragging like this will release with 0 velocity. await tester.drag(find.text('Item 49'), const Offset(0.0, -50.0)); await tester.pump(); // If handled correctly, the last item should still be visible and // progressing back down to the bottom edge, instead of jumping further // up the list and out of view. expect(find.text('Item 49'), findsOneWidget); await tester.pumpAndSettle(); expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets('overscroll, release, and tap', (WidgetTester tester) async { // Tapping while an inner ballistic scroll activity is in progress will // trigger a secondary ballistic scroll activity with a 0 velocity. final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildBallisticTest(controller)); // Last item of the inner scroll view. expect(find.text('Item 49'), findsNothing); // Scroll to bottom await tester.fling(find.text('Item 3'), const Offset(0.0, -50.0), 10000.0); await tester.pumpAndSettle(); // End of list expect(find.text('Item 49'), findsOneWidget); expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); // Fling again to trigger first ballistic activity. await tester.fling(find.text('Item 48'), const Offset(0.0, -50.0), 10000.0); await tester.pump(); // Tap after releasing the overscroll to trigger secondary inner ballistic // scroll activity with 0 velocity. await tester.tap(find.text('Item 49'), warnIfMissed: false); await tester.pumpAndSettle(); // If handled correctly, the ballistic scroll activity should finish // closing out the overscrolled area, with the last item visible at the // bottom. expect(find.text('Item 49'), findsOneWidget); expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); }); // Regression test for https://github.com/flutter/flutter/issues/63978 testWidgets('Inner _NestedScrollPosition.applyClampedDragUpdate correctly calculates range when in overscroll', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> nestedScrollView = GlobalKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( body: NestedScrollView( key: nestedScrollView, headerSliverBuilder: (BuildContext context, bool boxIsScrolled) { return <Widget>[ const SliverAppBar( expandedHeight: 200, title: Text('Test'), ), ]; }, body: ListView.builder( itemExtent: 100.0, itemBuilder: (BuildContext context, int index) => Container( padding: const EdgeInsets.all(10.0), child: Material( color: index.isEven ? Colors.cyan : Colors.deepOrange, child: Center( child: Text(index.toString()), ), ), ), ), ), ), )); expect(nestedScrollView.currentState!.outerController.position.pixels, 0.0); expect(nestedScrollView.currentState!.innerController.position.pixels, 0.0); expect(nestedScrollView.currentState!.outerController.position.maxScrollExtent, 200.0); final Offset point = tester.getCenter(find.text('1')); // Drag slightly into overscroll in the inner position. final TestGesture gesture = await tester.startGesture(point); await gesture.moveBy(const Offset(0.0, 5.0)); await tester.pump(); expect(nestedScrollView.currentState!.outerController.position.pixels, 0.0); expect(nestedScrollView.currentState!.innerController.position.pixels, -5.0); // Move by a much larger delta than the amount of over scroll, in a very // short period of time. await gesture.moveBy(const Offset(0.0, -500.0)); await tester.pump(); // The overscrolled inner position should have closed, then passed the // correct remaining delta to the outer position, and finally any remainder // back to the inner position. expect( nestedScrollView.currentState!.outerController.position.pixels, nestedScrollView.currentState!.outerController.position.maxScrollExtent, ); expect(nestedScrollView.currentState!.innerController.position.pixels, 295.0); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Scroll pointer signal should not cause overscroll.', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildTest(controller: controller)); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(scrollEventLocation); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); expect(controller.offset, 20); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -40.0))); expect(controller.offset, 0); await tester.tap(find.text('DD')); await tester.pumpAndSettle(); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 1000000.0))); expect(find.text('ddd1'), findsOneWidget); }); testWidgets('NestedScrollView basic scroll with pointer signal', (WidgetTester tester) async{ await tester.pumpWidget(buildTest()); expect(find.text('aaa2'), findsOneWidget); expect(find.text('aaa3'), findsNothing); expect(find.text('bbb1'), findsNothing); await tester.pump(const Duration(milliseconds: 250)); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0, ); // Regression test for https://github.com/flutter/flutter/issues/55362 final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // The offset is the responsibility of innerPosition. testPointer.hover(const Offset(0, 201)); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); await tester.pump(const Duration(milliseconds: 250)); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 180.0, ); testPointer.hover(const Offset(0, 179)); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); await tester.pump(const Duration(milliseconds: 250)); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 160.0, ); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); await tester.pump(const Duration(milliseconds: 250)); expect( tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 140.0, ); }); // Related to https://github.com/flutter/flutter/issues/64266 testWidgets( 'Holding scroll and Scroll pointer signal will update ScrollDirection.forward / ScrollDirection.reverse', (WidgetTester tester) async { ScrollDirection? lastUserScrollingDirection; final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildTest(controller: controller)); controller.addListener(() { if (controller.position.userScrollDirection != ScrollDirection.idle) { lastUserScrollingDirection = controller.position.userScrollDirection; } }); await tester.drag(find.byType(NestedScrollView), const Offset(0.0, -20.0), touchSlopY: 0.0); expect(lastUserScrollingDirection, ScrollDirection.reverse); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(scrollEventLocation); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); expect(lastUserScrollingDirection, ScrollDirection.reverse); await tester.drag(find.byType(NestedScrollView), const Offset(0.0, 20.0), touchSlopY: 0.0); expect(lastUserScrollingDirection, ScrollDirection.forward); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -20.0))); expect(lastUserScrollingDirection, ScrollDirection.forward); }, ); // Regression test for https://github.com/flutter/flutter/issues/72257 testWidgets('NestedScrollView works well when rebuilding during scheduleWarmUpFrame', (WidgetTester tester) async { bool? isScrolled; final Widget myApp = MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Focus( onFocusChange: (_) => setState( (){} ), child: NestedScrollView( headerSliverBuilder: (BuildContext context, bool boxIsScrolled) { isScrolled = boxIsScrolled; return <Widget>[ const SliverAppBar( expandedHeight: 200, title: Text('Test'), ), ]; }, body: CustomScrollView( slivers: <Widget>[ SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return const Text(''); }, childCount: 10, ), ), ], ), ), ); }, ), ), ); await tester.pumpWidget(myApp, duration: Duration.zero, phase: EnginePhase.build); expect(isScrolled, false); expect(tester.takeException(), isNull); }); // Regression test of https://github.com/flutter/flutter/issues/74372 testWidgets('ScrollPosition can be accessed during `_updatePosition()`', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); late ScrollPosition position; Widget buildFrame({ScrollPhysics? physics}) { return Directionality( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], child: MediaQuery( data: const MediaQueryData(), child: NestedScrollView( controller: controller, physics: physics, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ Builder( builder: (BuildContext context) { position = controller.position; return const SliverAppBar( floating: true, title: Text('AA'), ); }, ), ]; }, body: Container(), ), ), ), ); } await tester.pumpWidget(buildFrame()); expect(position.pixels, 0.0); //Trigger `_updatePosition()`. await tester.pumpWidget(buildFrame(physics: const _CustomPhysics())); expect(position.pixels, 0.0); }); testWidgets("NestedScrollView doesn't crash due to precision error", (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/63825 await tester.pumpWidget(MaterialApp( home: Scaffold( body: NestedScrollView( floatHeaderSlivers: true, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ const SliverAppBar( expandedHeight: 250.0, ), ], body: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ SliverPadding( padding: const EdgeInsets.all(8.0), sliver: SliverFixedExtentList( itemExtent: 48.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return ListTile( title: Text('Item $index'), ); }, childCount: 30, ), ), ), ], ), ), ), )); // Scroll to bottom await tester.fling(find.text('Item 3'), const Offset(0.0, -250.0), 10000.0); await tester.pumpAndSettle(); // Fling down for AppBar to show await tester.drag(find.text('Item 29'), const Offset(0.0, 250 - 133.7981622869321)); // Fling up to trigger ballistic activity await tester.fling(find.text('Item 25'), const Offset(0.0, -50.0), 4000.0); await tester.pumpAndSettle(); }); testWidgets('NestedScrollViewCoordinator.pointerScroll dispatches correct scroll notifications', (WidgetTester tester) async { int scrollEnded = 0; int scrollStarted = 0; bool isScrolled = false; await tester.pumpWidget(MaterialApp( home: NotificationListener<ScrollNotification>( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { scrollStarted += 1; } else if (notification is ScrollEndNotification) { scrollEnded += 1; } return false; }, child: Scaffold( body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { isScrolled = innerBoxIsScrolled; return <Widget>[ const SliverAppBar( expandedHeight: 250.0, ), ]; }, body: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ SliverPadding( padding: const EdgeInsets.all(8.0), sliver: SliverFixedExtentList( itemExtent: 48.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return ListTile( title: Text('Item $index'), ); }, childCount: 30, ), ), ), ], ), ), ), ), )); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(scrollEventLocation); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0))); await tester.pumpAndSettle(); expect(isScrolled, isTrue); // There should have been a notification for each nested position (2). expect(scrollStarted, 2); expect(scrollEnded, 2); }); testWidgets('SliverAppBar.medium collapses in NestedScrollView', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> nestedScrollView = GlobalKey(); const double collapsedAppBarHeight = 64; const double expandedAppBarHeight = 112; await tester.pumpWidget(MaterialApp( home: Scaffold( body: NestedScrollView( key: nestedScrollView, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: const SliverAppBar.medium( title: Text('AppBar Title'), ), ), ]; }, body: Builder( builder: (BuildContext context) { return CustomScrollView( slivers: <Widget>[ SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)), SliverFixedExtentList( itemExtent: 50.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => ListTile(title: Text('Item $index')), childCount: 30, ), ), ], ); }, ), ), ), )); // There are two widgets for the title. final Finder expandedTitle = find.text('AppBar Title').first; final Finder expandedTitleClip = find.ancestor( of: expandedTitle, matching: find.byType(ClipRect), ).first; // Default, fully expanded app bar. expect(nestedScrollView.currentState?.outerController.offset, 0); expect(nestedScrollView.currentState?.innerController.offset, 0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), expandedAppBarHeight); expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight); // Scroll the expanded app bar partially out of view. final Offset point1 = tester.getCenter(find.text('Item 5')); await tester.dragFrom(point1, const Offset(0.0, -45.0)); await tester.pump(); expect(nestedScrollView.currentState?.outerController.offset, 45.0); expect(nestedScrollView.currentState?.innerController.offset, 0.0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), expandedAppBarHeight - 45); expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight - 45); // Scroll so that it is completely collapsed. await tester.dragFrom(point1, const Offset(0.0, -555.0)); await tester.pump(); expect(nestedScrollView.currentState?.outerController.offset, 48.0); expect(nestedScrollView.currentState?.innerController.offset, 552.0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), collapsedAppBarHeight); expect(tester.getSize(expandedTitleClip).height, 0); // Scroll back to fully expanded. await tester.dragFrom(point1, const Offset(0.0, 600.0)); await tester.pump(); expect(nestedScrollView.currentState?.outerController.offset, 0); expect(nestedScrollView.currentState?.innerController.offset, 0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), expandedAppBarHeight); expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight); }); testWidgets('SliverAppBar.large collapses in NestedScrollView', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> nestedScrollView = GlobalKey(); const double collapsedAppBarHeight = 64; const double expandedAppBarHeight = 152; await tester.pumpWidget(MaterialApp( home: Scaffold( body: NestedScrollView( key: nestedScrollView, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverAppBar.large( title: const Text('AppBar Title'), forceElevated: innerBoxIsScrolled, ), ), ]; }, body: Builder( builder: (BuildContext context) { return CustomScrollView( slivers: <Widget>[ SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)), SliverFixedExtentList( itemExtent: 50.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => ListTile(title: Text('Item $index')), childCount: 30, ), ), ], ); }, ), ), ), )); // There are two widgets for the title. final Finder expandedTitle = find.text('AppBar Title').first; final Finder expandedTitleClip = find.ancestor( of: expandedTitle, matching: find.byType(ClipRect), ).first; // Default, fully expanded app bar. expect(nestedScrollView.currentState?.outerController.offset, 0); expect(nestedScrollView.currentState?.innerController.offset, 0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), expandedAppBarHeight); expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight); // Scroll the expanded app bar partially out of view. final Offset point1 = tester.getCenter(find.text('Item 5')); await tester.dragFrom(point1, const Offset(0.0, -45.0)); await tester.pump(); expect(nestedScrollView.currentState?.outerController.offset, 45.0); expect(nestedScrollView.currentState?.innerController.offset, 0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), expandedAppBarHeight - 45); expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight - 45); // Scroll so that it is completely collapsed. await tester.dragFrom(point1, const Offset(0.0, -555.0)); await tester.pump(); expect(nestedScrollView.currentState?.outerController.offset, 88.0); expect(nestedScrollView.currentState?.innerController.offset, 512.0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), collapsedAppBarHeight); expect(tester.getSize(expandedTitleClip).height, 0); // Scroll back to fully expanded. await tester.dragFrom(point1, const Offset(0.0, 600.0)); await tester.pump(); expect(nestedScrollView.currentState?.outerController.offset, 0); expect(nestedScrollView.currentState?.innerController.offset, 0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), expandedAppBarHeight); expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight); }); testWidgets('NestedScrollView does not crash when inner scrollable changes while scrolling', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/126454. Widget buildApp({required bool nested}) { final Widget innerScrollable = ListView( children: const <Widget>[SizedBox(height: 1000)], ); return MaterialApp( home: Scaffold( body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( title: const Text('Books'), pinned: true, expandedHeight: 150.0, forceElevated: innerBoxIsScrolled, ), ]; }, body: nested ? Container(child: innerScrollable) : innerScrollable, ), ), ); } await tester.pumpWidget(buildApp(nested: false)); // Start a scroll. final TestGesture scrollDrag = await tester.startGesture(tester.getCenter(find.byType(ListView))); await tester.pump(); await scrollDrag.moveBy(const Offset(0, 50)); await tester.pump(); // Restructuring inner scrollable while scroll is in progress shouldn't crash. await tester.pumpWidget(buildApp(nested: true)); }); testWidgets('SliverOverlapInjector asserts when there is no SliverOverlapAbsorber', (WidgetTester tester) async { Widget buildApp() { return MaterialApp( home: Scaffold( body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ const SliverAppBar(), ]; }, body: Builder( builder: (BuildContext context) { return CustomScrollView( slivers: <Widget>[ SliverOverlapInjector( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), ), ], ); } ), ), ), ); } final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; await tester.pumpWidget(buildApp()); FlutterError.onError = oldHandler; expect(exceptions.length, 4); expect(exceptions[0], isAssertionError); expect( (exceptions[0] as AssertionError).message, contains('SliverOverlapInjector has found no absorbed extent to inject.'), ); }); group('NestedScrollView properly sets drag', () { Future<bool> canDrag(WidgetTester tester) async { await tester.drag( find.byType(CustomScrollView), const Offset(0.0, -20.0), pointer: 1, ); await tester.pumpAndSettle(); final NestedScrollViewState nestedScrollView = tester.state<NestedScrollViewState>( find.byType(NestedScrollView) ); return nestedScrollView.outerController.position.pixels > 0.0 || nestedScrollView.innerController.position.pixels > 0.0; } Widget buildTest({ // The body length is to test when the nested scroll view should or // should not be allowing drag. required _BodyLength bodyLength, Widget? header, bool applyOverlap = false, }) { return MaterialApp( home: Scaffold( body: NestedScrollView( headerSliverBuilder: (BuildContext context, _) { if (applyOverlap) { return <Widget>[ SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: header, ), ]; } return header != null ? <Widget>[ header ] : <Widget>[]; }, body: Builder( builder: (BuildContext context) { return CustomScrollView( slivers: <Widget>[ SliverList.builder( itemCount: switch (bodyLength) { _BodyLength.short => 10, _BodyLength.long => 100, }, itemBuilder: (_, int index) => Text('Item $index'), ), ], ); } ), ), ) ); } testWidgets('when headerSliverBuilder is empty', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/117316 // Regression test for https://github.com/flutter/flutter/issues/46089 // Short body / long body for (final _BodyLength bodyLength in _BodyLength.values) { await tester.pumpWidget( buildTest(bodyLength: bodyLength), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } } }, variant: TargetPlatformVariant.all()); testWidgets('when headerSliverBuilder extent is 0', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/79077 // Short body / long body for (final _BodyLength bodyLength in _BodyLength.values) { // SliverPersistentHeader await tester.pumpWidget( buildTest( bodyLength: bodyLength, header: const SliverPersistentHeader( delegate: TestHeader(minExtent: 0.0, maxExtent: 0.0), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } // SliverPersistentHeader pinned await tester.pumpWidget( buildTest( bodyLength: bodyLength, header: const SliverPersistentHeader( pinned: true, delegate: TestHeader(minExtent: 0.0, maxExtent: 0.0), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } // SliverPersistentHeader floating await tester.pumpWidget( buildTest( bodyLength: bodyLength, header: const SliverPersistentHeader( floating: true, delegate: TestHeader(minExtent: 0.0, maxExtent: 0.0), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } // SliverPersistentHeader pinned+floating await tester.pumpWidget( buildTest( bodyLength: bodyLength, header: const SliverPersistentHeader( pinned: true, floating: true, delegate: TestHeader(minExtent: 0.0, maxExtent: 0.0), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } // SliverPersistentHeader w/ overlap await tester.pumpWidget( buildTest( bodyLength: bodyLength, applyOverlap: true, header: const SliverPersistentHeader( delegate: TestHeader(minExtent: 0.0, maxExtent: 0.0), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } // SliverPersistentHeader pinned w/ overlap await tester.pumpWidget( buildTest( bodyLength: bodyLength, applyOverlap: true, header: const SliverPersistentHeader( pinned: true, delegate: TestHeader(minExtent: 0.0, maxExtent: 0.0), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } // SliverPersistentHeader floating w/ overlap await tester.pumpWidget( buildTest( bodyLength: bodyLength, applyOverlap: true, header: const SliverPersistentHeader( floating: true, delegate: TestHeader(minExtent: 0.0, maxExtent: 0.0), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } // SliverPersistentHeader pinned+floating w/ overlap await tester.pumpWidget( buildTest( bodyLength: bodyLength, applyOverlap: true, header: const SliverPersistentHeader( floating: true, pinned: true, delegate: TestHeader(minExtent: 0.0, maxExtent: 0.0), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } } }, variant: TargetPlatformVariant.all()); testWidgets('With a pinned SliverAppBar', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/110956 // Regression test for https://github.com/flutter/flutter/issues/127282 // Regression test for https://github.com/flutter/flutter/issues/32563 // Regression test for https://github.com/flutter/flutter/issues/79077 // Short / long body for (final _BodyLength bodyLength in _BodyLength.values) { await tester.pumpWidget( buildTest( bodyLength: bodyLength, applyOverlap: true, header: const SliverAppBar( title: Text('Test'), pinned: true, bottom: PreferredSize( preferredSize: Size.square(25), child: SizedBox(), ), ), ), ); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: expect(await canDrag(tester), isFalse); case _BodyLength.long: expect(await canDrag(tester), isTrue); } } }); }); testWidgets('$SliverOverlapAbsorberHandle dispatches creation in constructor', (WidgetTester widgetTester) async { await expectLater( await memoryEvents(() => SliverOverlapAbsorberHandle().dispose(), SliverOverlapAbsorberHandle), areCreateAndDispose, ); }); } double appBarHeight(WidgetTester tester) => tester.getSize(find.byType(AppBar, skipOffstage: false)).height; enum _BodyLength { short, long, } class TestHeader extends SliverPersistentHeaderDelegate { const TestHeader({ this.key, required this.minExtent, required this.maxExtent, }); final Key? key; @override final double minExtent; @override final double maxExtent; @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { return Placeholder(key: key); } @override bool shouldRebuild(TestHeader oldDelegate) => false; } class _TestLayoutExtentIsNegative extends StatelessWidget { const _TestLayoutExtentIsNegative(this.widgetCountBeforeSliverOverlapAbsorber); final int widgetCountBeforeSliverOverlapAbsorber; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Test'), ), body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ ...List<Widget>.generate(widgetCountBeforeSliverOverlapAbsorber, (_) { return SliverToBoxAdapter( child: Container( color: Colors.red, height: 200, margin:const EdgeInsets.all(20), ), ); }), SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverAppBar( pinned: true, forceElevated: innerBoxIsScrolled, backgroundColor: Colors.blue[300], title: const SizedBox( height: 50, child: Center( child: Text('Sticky Header'), ), ), ), ), ]; }, body: Container( height: 2000, margin: const EdgeInsets.only(top: 50), child: ListView( children: List<Widget>.generate(3, (_) { return Container( color: Colors.green[200], height: 200, margin: const EdgeInsets.all(20), ); }), ), ), ), ), ); } }
flutter/packages/flutter/test/widgets/nested_scroll_view_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/nested_scroll_view_test.dart", "repo_id": "flutter", "token_count": 57649 }
692
// 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/foundation.dart'; import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../rendering/rendering_tester.dart' show TestClipPaintingContext; import 'semantics_tester.dart'; import 'states.dart'; void main() { // Regression test for https://github.com/flutter/flutter/issues/100451 testWidgets('PageView.builder respects findChildIndexCallback', (WidgetTester tester) async { bool finderCalled = false; int itemCount = 7; late StateSetter stateSetter; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { stateSetter = setState; return PageView.builder( itemCount: itemCount, itemBuilder: (BuildContext _, int index) => Container( key: Key('$index'), height: 2000.0, ), findChildIndexCallback: (Key key) { finderCalled = true; return null; }, ); }, ), ) ); expect(finderCalled, false); // Trigger update. stateSetter(() => itemCount = 77); await tester.pump(); expect(finderCalled, true); }); testWidgets('PageView resize from zero-size viewport should not lose state', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/88956 final PageController controller = PageController(initialPage: 1); addTearDown(controller.dispose); Widget build(Size size) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox.fromSize( size: size, child: PageView( controller: controller, onPageChanged: (int page) { }, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), ); } // The pageView have a zero viewport, so nothing display. await tester.pumpWidget(build(Size.zero)); expect(find.text('Alabama'), findsNothing); expect(find.text('Alabama', skipOffstage: false), findsOneWidget); // Resize from zero viewport to non-zero, the controller's initialPage 1 will display. await tester.pumpWidget(build(const Size(200.0, 200.0))); expect(find.text('Alaska'), findsOneWidget); // Jump to page 'Iowa'. controller.jumpToPage(kStates.indexOf('Iowa')); await tester.pump(); expect(find.text('Iowa'), findsOneWidget); // Resize to zero viewport again, nothing display. await tester.pumpWidget(build(Size.zero)); expect(find.text('Iowa'), findsNothing); // Resize from zero to non-zero, the pageView should not lose state, so the page 'Iowa' show again. await tester.pumpWidget(build(const Size(200.0, 200.0))); expect(find.text('Iowa'), findsOneWidget); }); testWidgets('Change the page through the controller when zero-size viewport', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/88956 final PageController controller = PageController(initialPage: 1); addTearDown(controller.dispose); Widget build(Size size) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox.fromSize( size: size, child: PageView( controller: controller, onPageChanged: (int page) { }, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), ); } // The pageView have a zero viewport, so nothing display. await tester.pumpWidget(build(Size.zero)); expect(find.text('Alabama'), findsNothing); expect(find.text('Alabama', skipOffstage: false), findsOneWidget); // Change the page through the page controller when zero viewport controller.animateToPage(kStates.indexOf('Iowa'), duration: kTabScrollDuration, curve: Curves.ease); expect(controller.page, kStates.indexOf('Iowa')); controller.jumpToPage(kStates.indexOf('Illinois')); expect(controller.page, kStates.indexOf('Illinois')); // Resize from zero viewport to non-zero, the latest state should not lost. await tester.pumpWidget(build(const Size(200.0, 200.0))); expect(controller.page, kStates.indexOf('Illinois')); expect(find.text('Illinois'), findsOneWidget); }); testWidgets('_PagePosition.applyViewportDimension should not throw', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/101007 final PageController controller = PageController(initialPage: 1); addTearDown(controller.dispose); // Set the starting viewportDimension to 0.0 await tester.binding.setSurfaceSize(Size.zero); final MediaQueryData mediaQueryData = MediaQueryData.fromView(tester.view); Widget build(Size size) { return MediaQuery( data: mediaQueryData.copyWith(size: size), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox.expand( child: PageView( controller: controller, onPageChanged: (int page) { }, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), ), ); } await tester.pumpWidget(build(Size.zero)); const Size surfaceSize = Size(500,400); await tester.binding.setSurfaceSize(surfaceSize); await tester.pumpWidget(build(surfaceSize)); expect(tester.takeException(), isNull); // Reset TestWidgetsFlutterBinding surfaceSize await tester.binding.setSurfaceSize(null); }); testWidgets('PageController cannot return page while unattached', (WidgetTester tester) async { final PageController controller = PageController(); addTearDown(controller.dispose); expect(() => controller.page, throwsAssertionError); }); testWidgets('PageView control test', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( dragStartBehavior: DragStartBehavior.down, children: kStates.map<Widget>((String state) { return GestureDetector( dragStartBehavior: DragStartBehavior.down, onTap: () { log.add(state); }, child: Container( height: 200.0, color: const Color(0xFF0000FF), child: Text(state), ), ); }).toList(), ), )); await tester.tap(find.text('Alabama')); expect(log, equals(<String>['Alabama'])); log.clear(); expect(find.text('Alaska'), findsNothing); await tester.drag(find.byType(PageView), const Offset(-20.0, 0.0)); await tester.pump(); expect(find.text('Alabama'), findsOneWidget); expect(find.text('Alaska'), findsOneWidget); expect(find.text('Arizona'), findsNothing); await tester.pumpAndSettle(); expect(find.text('Alabama'), findsOneWidget); expect(find.text('Alaska'), findsNothing); await tester.drag(find.byType(PageView), const Offset(-401.0, 0.0)); await tester.pumpAndSettle(); expect(find.text('Alabama'), findsNothing); expect(find.text('Alaska'), findsOneWidget); expect(find.text('Arizona'), findsNothing); await tester.tap(find.text('Alaska')); expect(log, equals(<String>['Alaska'])); log.clear(); await tester.fling(find.byType(PageView), const Offset(-200.0, 0.0), 1000.0); await tester.pumpAndSettle(); expect(find.text('Alabama'), findsNothing); expect(find.text('Alaska'), findsNothing); expect(find.text('Arizona'), findsOneWidget); await tester.fling(find.byType(PageView), const Offset(200.0, 0.0), 1000.0); await tester.pumpAndSettle(); expect(find.text('Alabama'), findsNothing); expect(find.text('Alaska'), findsOneWidget); expect(find.text('Arizona'), findsNothing); }); testWidgets('PageView does not squish when overscrolled', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: PageView( children: List<Widget>.generate(10, (int i) { return Container( key: ValueKey<int>(i), color: const Color(0xFF0000FF), ); }), ), )); Size sizeOf(int i) => tester.getSize(find.byKey(ValueKey<int>(i))); double leftOf(int i) => tester.getTopLeft(find.byKey(ValueKey<int>(i))).dx; expect(leftOf(0), equals(0.0)); expect(sizeOf(0), equals(const Size(800.0, 600.0))); // Going into overscroll. await tester.drag(find.byType(PageView), const Offset(100.0, 0.0)); await tester.pump(); expect(leftOf(0), greaterThan(0.0)); expect(sizeOf(0), equals(const Size(800.0, 600.0))); // Easing overscroll past overscroll limit. if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { await tester.drag(find.byType(PageView), const Offset(-500.0, 0.0)); } else { await tester.drag(find.byType(PageView), const Offset(-200.0, 0.0)); } await tester.pump(); expect(leftOf(0), lessThan(0.0)); expect(sizeOf(0), equals(const Size(800.0, 600.0))); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('PageController control test', (WidgetTester tester) async { final PageController controller = PageController(initialPage: 4); addTearDown(controller.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 600.0, height: 400.0, child: PageView( controller: controller, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), )); expect(find.text('California'), findsOneWidget); controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease); await tester.pumpAndSettle(); expect(find.text('Colorado'), findsOneWidget); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 300.0, height: 400.0, child: PageView( controller: controller, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), )); expect(find.text('Colorado'), findsOneWidget); controller.previousPage(duration: const Duration(milliseconds: 150), curve: Curves.ease); await tester.pumpAndSettle(); expect(find.text('California'), findsOneWidget); }); testWidgets('PageController page stability', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 600.0, height: 400.0, child: PageView( children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), )); expect(find.text('Alabama'), findsOneWidget); await tester.drag(find.byType(PageView), const Offset(-1250.0, 0.0)); await tester.pumpAndSettle(); expect(find.text('Arizona'), findsOneWidget); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 250.0, height: 100.0, child: PageView( children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), )); expect(find.text('Arizona'), findsOneWidget); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 450.0, height: 400.0, child: PageView( children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), )); expect(find.text('Arizona'), findsOneWidget); }); testWidgets('PageController nextPage and previousPage return Futures that resolve', (WidgetTester tester) async { final PageController controller = PageController(); addTearDown(controller.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( controller: controller, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), )); bool nextPageCompleted = false; controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease) .then((_) => nextPageCompleted = true); expect(nextPageCompleted, false); await tester.pump(const Duration(milliseconds: 200)); expect(nextPageCompleted, false); await tester.pump(const Duration(milliseconds: 200)); expect(nextPageCompleted, true); bool previousPageCompleted = false; controller.previousPage(duration: const Duration(milliseconds: 150), curve: Curves.ease) .then((_) => previousPageCompleted = true); expect(previousPageCompleted, false); await tester.pump(const Duration(milliseconds: 200)); expect(previousPageCompleted, false); await tester.pump(const Duration(milliseconds: 200)); expect(previousPageCompleted, true); }); testWidgets('PageView in zero-size container', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox.shrink( child: PageView( children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), )); expect(find.text('Alabama', skipOffstage: false), findsOneWidget); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 200.0, height: 200.0, child: PageView( children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), ), )); expect(find.text('Alabama'), findsOneWidget); }); testWidgets('Page changes at halfway point', (WidgetTester tester) async { final List<int> log = <int>[]; await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( onPageChanged: log.add, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), )); expect(log, isEmpty); final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); // The page view is 800.0 wide, so this move is just short of halfway. await gesture.moveBy(const Offset(-380.0, 0.0)); expect(log, isEmpty); // We've crossed the halfway mark. await gesture.moveBy(const Offset(-40.0, 0.0)); expect(log, equals(const <int>[1])); log.clear(); // Moving a bit more should not generate redundant notifications. await gesture.moveBy(const Offset(-40.0, 0.0)); expect(log, isEmpty); await gesture.moveBy(const Offset(-40.0, 0.0)); await tester.pump(); await gesture.moveBy(const Offset(-40.0, 0.0)); await tester.pump(); await gesture.moveBy(const Offset(-40.0, 0.0)); await tester.pump(); expect(log, isEmpty); await gesture.up(); await tester.pumpAndSettle(); expect(log, isEmpty); expect(find.text('Alabama'), findsNothing); expect(find.text('Alaska'), findsOneWidget); }); testWidgets('Bouncing scroll physics ballistics does not overshoot', (WidgetTester tester) async { final List<int> log = <int>[]; final PageController controller = PageController(viewportFraction: 0.9); addTearDown(controller.dispose); Widget build(PageController controller, { Size? size }) { final Widget pageView = Directionality( textDirection: TextDirection.ltr, child: PageView( controller: controller, onPageChanged: log.add, physics: const BouncingScrollPhysics(), children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ); if (size != null) { return OverflowBox( minWidth: size.width, minHeight: size.height, maxWidth: size.width, maxHeight: size.height, child: pageView, ); } else { return pageView; } } await tester.pumpWidget(build(controller)); expect(log, isEmpty); // Fling right to move to a non-existent page at the beginning of the // PageView, and confirm that the PageView settles back on the first page. await tester.fling(find.byType(PageView), const Offset(100.0, 0.0), 800.0); await tester.pumpAndSettle(); expect(log, isEmpty); expect(find.text('Alabama'), findsOneWidget); expect(find.text('Alaska'), findsOneWidget); expect(find.text('Arizona'), findsNothing); // Try again with a Cupertino "Plus" device size. await tester.pumpWidget(build(controller, size: const Size(414.0, 736.0))); expect(log, isEmpty); await tester.fling(find.byType(PageView), const Offset(100.0, 0.0), 800.0); await tester.pumpAndSettle(); expect(log, isEmpty); expect(find.text('Alabama'), findsOneWidget); expect(find.text('Alaska'), findsOneWidget); expect(find.text('Arizona'), findsNothing); }); testWidgets('PageView viewportFraction', (WidgetTester tester) async { PageController controller = PageController(viewportFraction: 7/8); addTearDown(controller.dispose); Widget build(PageController controller) { return Directionality( textDirection: TextDirection.ltr, child: PageView.builder( controller: controller, itemCount: kStates.length, itemBuilder: (BuildContext context, int index) { return Container( height: 200.0, color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), child: Text(kStates[index]), ); }, ), ); } await tester.pumpWidget(build(controller)); expect(tester.getTopLeft(find.text('Alabama')), const Offset(50.0, 0.0)); expect(tester.getTopLeft(find.text('Alaska')), const Offset(750.0, 0.0)); controller.jumpToPage(10); await tester.pump(); expect(tester.getTopLeft(find.text('Georgia')), const Offset(-650.0, 0.0)); expect(tester.getTopLeft(find.text('Hawaii')), const Offset(50.0, 0.0)); expect(tester.getTopLeft(find.text('Idaho')), const Offset(750.0, 0.0)); controller = PageController(viewportFraction: 39/40); addTearDown(controller.dispose); await tester.pumpWidget(build(controller)); expect(tester.getTopLeft(find.text('Georgia')), const Offset(-770.0, 0.0)); expect(tester.getTopLeft(find.text('Hawaii')), const Offset(10.0, 0.0)); expect(tester.getTopLeft(find.text('Idaho')), const Offset(790.0, 0.0)); }); testWidgets('Page snapping disable and reenable', (WidgetTester tester) async { final List<int> log = <int>[]; Widget build({ required bool pageSnapping }) { return Directionality( textDirection: TextDirection.ltr, child: PageView( pageSnapping: pageSnapping, onPageChanged: log.add, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ); } await tester.pumpWidget(build(pageSnapping: true)); expect(log, isEmpty); // Drag more than halfway to the next page, to confirm the default behavior. TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); // The page view is 800.0 wide, so this move is just beyond halfway. await gesture.moveBy(const Offset(-420.0, 0.0)); expect(log, equals(const <int>[1])); log.clear(); // Release the gesture, confirm that the page settles on the next. await gesture.up(); await tester.pumpAndSettle(); expect(find.text('Alabama'), findsNothing); expect(find.text('Alaska'), findsOneWidget); // Disable page snapping, and try moving halfway. Confirm it doesn't snap. await tester.pumpWidget(build(pageSnapping: false)); gesture = await tester.startGesture(const Offset(100.0, 100.0)); // Move just beyond halfway, again. await gesture.moveBy(const Offset(-420.0, 0.0)); // Page notifications still get sent. expect(log, equals(const <int>[2])); log.clear(); // Release the gesture, confirm that both pages are visible. await gesture.up(); await tester.pumpAndSettle(); expect(find.text('Alabama'), findsNothing); expect(find.text('Alaska'), findsOneWidget); expect(find.text('Arizona'), findsOneWidget); expect(find.text('Arkansas'), findsNothing); // Now re-enable snapping, confirm that we've settled on a page. await tester.pumpWidget(build(pageSnapping: true)); await tester.pumpAndSettle(); expect(log, isEmpty); expect(find.text('Alaska'), findsNothing); expect(find.text('Arizona'), findsOneWidget); expect(find.text('Arkansas'), findsNothing); }); testWidgets('PageView small viewportFraction', (WidgetTester tester) async { final PageController controller = PageController(viewportFraction: 1/8); addTearDown(controller.dispose); Widget build(PageController controller) { return Directionality( textDirection: TextDirection.ltr, child: PageView.builder( controller: controller, itemCount: kStates.length, itemBuilder: (BuildContext context, int index) { return Container( height: 200.0, color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), child: Text(kStates[index]), ); }, ), ); } await tester.pumpWidget(build(controller)); expect(tester.getTopLeft(find.text('Alabama')), const Offset(350.0, 0.0)); expect(tester.getTopLeft(find.text('Alaska')), const Offset(450.0, 0.0)); expect(tester.getTopLeft(find.text('Arizona')), const Offset(550.0, 0.0)); expect(tester.getTopLeft(find.text('Arkansas')), const Offset(650.0, 0.0)); expect(tester.getTopLeft(find.text('California')), const Offset(750.0, 0.0)); controller.jumpToPage(10); await tester.pump(); expect(tester.getTopLeft(find.text('Connecticut')), const Offset(-50.0, 0.0)); expect(tester.getTopLeft(find.text('Delaware')), const Offset(50.0, 0.0)); expect(tester.getTopLeft(find.text('Florida')), const Offset(150.0, 0.0)); expect(tester.getTopLeft(find.text('Georgia')), const Offset(250.0, 0.0)); expect(tester.getTopLeft(find.text('Hawaii')), const Offset(350.0, 0.0)); expect(tester.getTopLeft(find.text('Idaho')), const Offset(450.0, 0.0)); expect(tester.getTopLeft(find.text('Illinois')), const Offset(550.0, 0.0)); expect(tester.getTopLeft(find.text('Indiana')), const Offset(650.0, 0.0)); expect(tester.getTopLeft(find.text('Iowa')), const Offset(750.0, 0.0)); }); testWidgets('PageView large viewportFraction', (WidgetTester tester) async { final PageController controller = PageController(viewportFraction: 5/4); addTearDown(controller.dispose); Widget build(PageController controller) { return Directionality( textDirection: TextDirection.ltr, child: PageView.builder( controller: controller, itemCount: kStates.length, itemBuilder: (BuildContext context, int index) { return Container( height: 200.0, color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), child: Text(kStates[index]), ); }, ), ); } await tester.pumpWidget(build(controller)); expect(tester.getTopLeft(find.text('Alabama')), const Offset(-100.0, 0.0)); expect(tester.getBottomRight(find.text('Alabama')), const Offset(900.0, 600.0)); controller.jumpToPage(10); await tester.pump(); expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-100.0, 0.0)); }); testWidgets( 'Updating PageView large viewportFraction', (WidgetTester tester) async { Widget build(PageController controller) { return Directionality( textDirection: TextDirection.ltr, child: PageView.builder( controller: controller, itemCount: kStates.length, itemBuilder: (BuildContext context, int index) { return Container( height: 200.0, color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), child: Text(kStates[index]), ); }, ), ); } final PageController oldController = PageController(viewportFraction: 5/4); addTearDown(oldController.dispose); await tester.pumpWidget(build(oldController)); expect(tester.getTopLeft(find.text('Alabama')), const Offset(-100, 0)); expect(tester.getBottomRight(find.text('Alabama')), const Offset(900.0, 600.0)); final PageController newController = PageController(viewportFraction: 4); addTearDown(newController.dispose); await tester.pumpWidget(build(newController)); newController.jumpToPage(10); await tester.pump(); expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-(4 - 1) * 800 / 2, 0)); }, ); testWidgets( 'PageView large viewportFraction can scroll to the last page and snap', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/45096. final PageController controller = PageController(viewportFraction: 5/4); addTearDown(controller.dispose); Widget build(PageController controller) { return Directionality( textDirection: TextDirection.ltr, child: PageView.builder( controller: controller, itemCount: 3, itemBuilder: (BuildContext context, int index) { return Container( height: 200.0, color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), child: Text(index.toString()), ); }, ), ); } await tester.pumpWidget(build(controller)); expect(tester.getCenter(find.text('0')), const Offset(400, 300)); controller.jumpToPage(2); await tester.pump(); await tester.pumpAndSettle(); expect(tester.getCenter(find.text('2')), const Offset(400, 300)); }, ); testWidgets( 'All visible pages are able to receive touch events', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/23873. final PageController controller = PageController(viewportFraction: 1/4); addTearDown(controller.dispose); late int tappedIndex; Widget build() { return Directionality( textDirection: TextDirection.ltr, child: PageView.builder( controller: controller, itemCount: 20, itemBuilder: (BuildContext context, int index) { return GestureDetector( onTap: () => tappedIndex = index, child: SizedBox.expand(child: Text('$index')), ); }, ), ); } Iterable<int> visiblePages = const <int> [0, 1, 2]; await tester.pumpWidget(build()); // The first 3 items should be visible and tappable. for (final int index in visiblePages) { expect(find.text(index.toString()), findsOneWidget); // The center of page 2's x-coordinate is 800, so we have to manually // offset it a bit to make sure the tap lands within the screen. final Offset center = tester.getCenter(find.text('$index')) - const Offset(3, 0); await tester.tapAt(center); expect(tappedIndex, index); } controller.jumpToPage(19); await tester.pump(); // The last 3 items should be visible and tappable. visiblePages = const <int> [17, 18, 19]; for (final int index in visiblePages) { expect(find.text('$index'), findsOneWidget); await tester.tap(find.text('$index')); expect(tappedIndex, index); } }, ); testWidgets('the current item remains centered on constraint change', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/50505. final PageController controller = PageController( initialPage: kStates.length - 1, viewportFraction: 0.5, ); addTearDown(controller.dispose); Widget build(Size size) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox.fromSize( size: size, child: PageView( controller: controller, children: kStates.map<Widget>((String state) => Text(state)).toList(), onPageChanged: (int page) { }, ), ), ), ); } // Verifies that the last item is centered on screen. void verifyCentered() { expect( tester.getCenter(find.text(kStates.last)), offsetMoreOrLessEquals(const Offset(400, 300)), ); } await tester.pumpWidget(build(const Size(300, 300))); await tester.pumpAndSettle(); verifyCentered(); await tester.pumpWidget(build(const Size(200, 300))); await tester.pumpAndSettle(); verifyCentered(); }); testWidgets('PageView does not report page changed on overscroll', (WidgetTester tester) async { final PageController controller = PageController( initialPage: kStates.length - 1, ); addTearDown(controller.dispose); int changeIndex = 0; Widget build() { return Directionality( textDirection: TextDirection.ltr, child: PageView( controller: controller, children: kStates.map<Widget>((String state) => Text(state)).toList(), onPageChanged: (int page) { changeIndex = page; }, ), ); } await tester.pumpWidget(build()); controller.jumpToPage(kStates.length * 2); // try to move beyond max range // change index should be zero, shouldn't fire onPageChanged expect(changeIndex, 0); await tester.pump(); expect(changeIndex, 0); }); testWidgets('PageView can restore page', (WidgetTester tester) async { final PageController controller = PageController(); addTearDown(controller.dispose); expect( () => controller.page, throwsA(isAssertionError.having( (AssertionError error) => error.message, 'message', equals('PageController.page cannot be accessed before a PageView is built with it.'), )), ); final PageStorageBucket bucket = PageStorageBucket(); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageStorage( bucket: bucket, child: PageView( key: const PageStorageKey<String>('PageView'), controller: controller, children: const <Widget>[ Placeholder(), Placeholder(), Placeholder(), ], ), ), )); expect(controller.page, 0); controller.jumpToPage(2); expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 2); expect(controller.page, 2); await tester.pumpWidget( PageStorage( bucket: bucket, child: Container(), ), ); expect( () => controller.page, throwsA(isAssertionError.having( (AssertionError error) => error.message, 'message', equals('PageController.page cannot be accessed before a PageView is built with it.'), )), ); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageStorage( bucket: bucket, child: PageView( key: const PageStorageKey<String>('PageView'), controller: controller, children: const <Widget>[ Placeholder(), Placeholder(), Placeholder(), ], ), ), )); expect(controller.page, 2); final PageController controller2 = PageController(keepPage: false); addTearDown(controller2.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageStorage( bucket: bucket, child: PageView( key: const PageStorageKey<String>('Check it again against your list and see consistency!'), controller: controller2, children: const <Widget>[ Placeholder(), Placeholder(), Placeholder(), ], ), ), )); expect(controller2.page, 0); }); testWidgets('PageView exposes semantics of children', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final PageController controller = PageController(); addTearDown(controller.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( controller: controller, children: List<Widget>.generate(3, (int i) { return Semantics( container: true, child: Text('Page #$i'), ); }), ), )); expect(controller.page, 0); expect(semantics, includesNodeWith(label: 'Page #0')); expect(semantics, isNot(includesNodeWith(label: 'Page #1'))); expect(semantics, isNot(includesNodeWith(label: 'Page #2'))); controller.jumpToPage(1); await tester.pumpAndSettle(); expect(semantics, isNot(includesNodeWith(label: 'Page #0'))); expect(semantics, includesNodeWith(label: 'Page #1')); expect(semantics, isNot(includesNodeWith(label: 'Page #2'))); controller.jumpToPage(2); await tester.pumpAndSettle(); expect(semantics, isNot(includesNodeWith(label: 'Page #0'))); expect(semantics, isNot(includesNodeWith(label: 'Page #1'))); expect(semantics, includesNodeWith(label: 'Page #2')); semantics.dispose(); }); testWidgets('PageMetrics', (WidgetTester tester) async { final PageMetrics page = PageMetrics( minScrollExtent: 100.0, maxScrollExtent: 200.0, pixels: 150.0, viewportDimension: 25.0, axisDirection: AxisDirection.right, viewportFraction: 1.0, devicePixelRatio: tester.view.devicePixelRatio, ); expect(page.page, 6); final PageMetrics page2 = page.copyWith( pixels: page.pixels - 100.0, ); expect(page2.page, 4.0); }); testWidgets('Page controller can handle rounding issue', (WidgetTester tester) async { final PageController pageController = PageController(); addTearDown(pageController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( controller: pageController, children: List<Widget>.generate(3, (int i) { return Semantics( container: true, child: Text('Page #$i'), ); }), ), )); // Simulate precision error. pageController.position.jumpTo(799.99999999999); expect(pageController.page, 1); }); testWidgets('PageView can participate in a11y scrolling', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final PageController controller = PageController(); addTearDown(controller.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( controller: controller, allowImplicitScrolling: true, children: List<Widget>.generate(4, (int i) { return Semantics( container: true, child: Text('Page #$i'), ); }), ), )); expect(controller.page, 0); expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling])); expect(semantics, includesNodeWith(label: 'Page #0')); expect(semantics, includesNodeWith(label: 'Page #1', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); expect(semantics, isNot(includesNodeWith(label: 'Page #2', flags: <SemanticsFlag>[SemanticsFlag.isHidden]))); expect(semantics, isNot(includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden]))); controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease); await tester.pumpAndSettle(); expect(semantics, includesNodeWith(label: 'Page #0', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); expect(semantics, includesNodeWith(label: 'Page #1')); expect(semantics, includesNodeWith(label: 'Page #2', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); expect(semantics, isNot(includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden]))); controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease); await tester.pumpAndSettle(); expect(semantics, isNot(includesNodeWith(label: 'Page #0', flags: <SemanticsFlag>[SemanticsFlag.isHidden]))); expect(semantics, includesNodeWith(label: 'Page #1', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); expect(semantics, includesNodeWith(label: 'Page #2')); expect(semantics, includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); semantics.dispose(); }); testWidgets('PageView respects clipBehavior', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: PageView( children: <Widget>[Container(height: 2000.0)], ), ), ); // 1st, check that the render object has received the default clip behavior. final RenderViewport renderObject = tester.allRenderObjects.whereType<RenderViewport>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // 2nd, check that the painting context has received the default clip behavior. final TestClipPaintingContext context = TestClipPaintingContext(); renderObject.paint(context, Offset.zero); expect(context.clipBehavior, equals(Clip.hardEdge)); // 3rd, pump a new widget to check that the render object can update its clip behavior. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: PageView( clipBehavior: Clip.antiAlias, children: <Widget>[Container(height: 2000.0)], ), ), ); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); // 4th, check that a non-default clip behavior can be sent to the painting context. renderObject.paint(context, Offset.zero); expect(context.clipBehavior, equals(Clip.antiAlias)); }); testWidgets('PageView.padEnds tests', (WidgetTester tester) async { Finder viewportFinder() => find.byType(SliverFillViewport, skipOffstage: false); // PageView() defaults to true. await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView(), )); expect(tester.widget<SliverFillViewport>(viewportFinder()).padEnds, true); // PageView(padEnds: false) is propagated properly. await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( padEnds: false, ), )); expect(tester.widget<SliverFillViewport>(viewportFinder()).padEnds, false); }); testWidgets('PageView - precision error inside RenderSliverFixedExtentBoxAdaptor', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/95101 final PageController controller = PageController(initialPage: 152); addTearDown(controller.dispose); await tester.pumpWidget( Center( child: SizedBox( width: 392.72727272727275, child: Directionality( textDirection: TextDirection.ltr, child: PageView.builder( controller: controller, itemCount: 366, itemBuilder: (BuildContext context, int index) { return const SizedBox(); }, ), ), ), ), ); controller.jumpToPage(365); await tester.pump(); expect(tester.takeException(), isNull); }); testWidgets('PageView content should not be stretched on precision error', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/126561. final PageController controller = PageController(); addTearDown(controller.dispose); const double pixel6EmulatorWidth = 411.42857142857144; await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: true), home: Center( child: SizedBox( width: pixel6EmulatorWidth, child: PageView( controller: controller, physics: const PageScrollPhysics().applyTo(const ClampingScrollPhysics()), children: const <Widget>[ Center(child: Text('First Page')), Center(child: Text('Second Page')), Center(child: Text('Third Page')), ], ), ), ), )); controller.animateToPage(2, duration: const Duration(milliseconds: 300), curve: Curves.ease); await tester.pumpAndSettle(); final Finder transformFinder = find.descendant(of: find.byType(PageView), matching: find.byType(Transform)); expect(transformFinder, findsOneWidget); // Get the Transform widget that stretches the PageView. final Transform transform = tester.firstWidget<Transform>( find.descendant( of: find.byType(PageView), matching: find.byType(Transform), ), ); // Check the stretch factor in the first element of the transform matrix. expect(transform.transform.storage.first, 1.0); }); testWidgets('PageController onAttach, onDetach', (WidgetTester tester) async { int attach = 0; int detach = 0; final PageController controller = PageController( onAttach: (_) { attach++; }, onDetach: (_) { detach++; }, ); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: true), home: Center( child: PageView( controller: controller, physics: const PageScrollPhysics().applyTo(const ClampingScrollPhysics()), children: const <Widget>[ Center(child: Text('First Page')), Center(child: Text('Second Page')), Center(child: Text('Third Page')), ], ), ), )); await tester.pumpAndSettle(); expect(attach, 1); expect(detach, 0); await tester.pumpWidget(Container()); await tester.pumpAndSettle(); expect(attach, 1); expect(detach, 1); }); group('$PageView handles change of controller', () { final GlobalKey key = GlobalKey(); Widget createPageView(PageController? controller) { return MaterialApp( home: Scaffold( body: PageView( key: key, controller: controller, children: const <Widget>[ Center(child: Text('0')), Center(child: Text('1')), Center(child: Text('2')), ], ), ), ); } Future<void> testPageViewWithController(PageController controller, WidgetTester tester, bool controls) async { int currentVisiblePage() { return int.parse(tester.widgetList(find.byType(Text)).whereType<Text>().first.data!); } final int initialPageInView = currentVisiblePage(); for (int i = 0; i < 3; i++) { if (controls) { controller.jumpToPage(i); await tester.pumpAndSettle(); expect(currentVisiblePage(), i); } else { expect(()=> controller.jumpToPage(i), throwsAssertionError); expect(currentVisiblePage(), initialPageInView); } } } testWidgets('null to value', (WidgetTester tester) async { final PageController controller = PageController(); addTearDown(controller.dispose); await tester.pumpWidget(createPageView(null)); await tester.pumpWidget(createPageView(controller)); await testPageViewWithController(controller, tester, true); }); testWidgets('value to value', (WidgetTester tester) async { final PageController controller1 = PageController(); addTearDown(controller1.dispose); final PageController controller2 = PageController(); addTearDown(controller2.dispose); await tester.pumpWidget(createPageView(controller1)); await testPageViewWithController(controller1, tester, true); await tester.pumpWidget(createPageView(controller2)); await testPageViewWithController(controller1, tester, false); await testPageViewWithController(controller2, tester, true); }); testWidgets('value to null', (WidgetTester tester) async { final PageController controller = PageController(); addTearDown(controller.dispose); await tester.pumpWidget(createPageView(controller)); await testPageViewWithController(controller, tester, true); await tester.pumpWidget(createPageView(null)); await testPageViewWithController(controller, tester, false); }); testWidgets('null to null', (WidgetTester tester) async { await tester.pumpWidget(createPageView(null)); await tester.pumpWidget(createPageView(null)); }); }); }
flutter/packages/flutter/test/widgets/page_view_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/page_view_test.dart", "repo_id": "flutter", "token_count": 18881 }
693
// 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:collection/collection.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { testWidgets('SliverReorderableList works well when having gestureSettings', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/103404 const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); void handleReorder(int fromIndex, int toIndex) { onReorderCallCount += 1; if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( home: MediaQuery( data: const MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 8.0)), child: CustomScrollView( slivers: <Widget>[ SliverReorderableList( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDragStartListener( index: index, child: Text('item ${items[index]}'), ), ); }, onReorder: handleReorder, ) ], ), ), ), ); // Start gesture on first item final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kPressTimeout); // Drag a little bit to make `ImmediateMultiDragGestureRecognizer` compete with `VerticalDragGestureRecognizer` await drag.moveBy(const Offset(0, 10)); await tester.pump(); // Drag enough to move down the first item await drag.moveBy(const Offset(0, 40)); await tester.pump(); await drag.up(); await tester.pumpAndSettle(); expect(onReorderCallCount, 1); expect(items, orderedEquals(<int>[1, 0, 2, 3, 4])); }); testWidgets('SliverReorderableList item has correct semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); void handleReorder(int fromIndex, int toIndex) { onReorderCallCount += 1; if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( home: MediaQuery( data: const MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 8.0)), child: CustomScrollView( slivers: <Widget>[ SliverReorderableList( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDragStartListener( index: index, child: Text('item ${items[index]}'), ), ); }, onReorder: handleReorder, ) ], ), ), ), ); expect( semantics, includesNodeWith( label: 'item 0', actions: <SemanticsAction>[SemanticsAction.customAction], ), ); final SemanticsNode node = tester.getSemantics(find.text('item 0')); // perform custom action 'move down'. final int customActionId = CustomSemanticsAction.getIdentifier(const CustomSemanticsAction(label: 'Move down')); tester.binding.pipelineOwner.semanticsOwner!.performAction(node.id, SemanticsAction.customAction, customActionId); await tester.pumpAndSettle(); expect(onReorderCallCount, 1); expect(items, orderedEquals(<int>[1, 0, 2, 3, 4])); semantics.dispose(); }); testWidgets('SliverReorderableList custom semantics action has correct label', (WidgetTester tester) async { const int itemCount = 5; final List<int> items = List<int>.generate(itemCount, (int index) => index); // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( home: MediaQuery( data: const MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 8.0)), child: CustomScrollView( slivers: <Widget>[ SliverReorderableList( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDragStartListener( index: index, child: Text('item ${items[index]}'), ), ); }, onReorder: (int _, int __) { }, ) ], ), ), ), ); final SemanticsNode node = tester.getSemantics(find.text('item 0')); final SemanticsData data = node.getSemanticsData(); expect(data.customSemanticsActionIds!.length, 2); final CustomSemanticsAction action1 = CustomSemanticsAction.getAction(data.customSemanticsActionIds![0])!; expect(action1.label, 'Move down'); final CustomSemanticsAction action2 = CustomSemanticsAction.getAction(data.customSemanticsActionIds![1])!; expect(action2.label, 'Move to the end'); }); // Regression test for https://github.com/flutter/flutter/issues/100451 testWidgets('SliverReorderableList.builder respects findChildIndexCallback', (WidgetTester tester) async { bool finderCalled = false; int itemCount = 7; late StateSetter stateSetter; await tester.pumpWidget( MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { stateSetter = setState; return CustomScrollView( slivers: <Widget>[ SliverReorderableList( itemCount: itemCount, itemBuilder: (BuildContext _, int index) => Container( key: Key('$index'), height: 2000.0, ), findChildIndexCallback: (Key key) { finderCalled = true; return null; }, onReorder: (int oldIndex, int newIndex) { }, ), ], ); }, ), ) ); expect(finderCalled, false); // Trigger update. stateSetter(() => itemCount = 77); await tester.pump(); expect(finderCalled, true); }); // Regression test for https://github.com/flutter/flutter/issues/88191 testWidgets('Do not crash when dragging with two fingers simultaneously', (WidgetTester tester) async { final List<int> items = List<int>.generate(3, (int index) => index); void handleReorder(int fromIndex, int toIndex) { if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } await tester.pumpWidget(MaterialApp( home: ReorderableList( itemBuilder: (BuildContext context, int index) { return ReorderableDragStartListener( index: index, key: ValueKey<int>(items[index]), child: SizedBox( height: 100, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('item ${items[index]}'), ], ), ), ); }, itemCount: items.length, onReorder: handleReorder, ), )); final TestGesture drag1 = await tester.startGesture(tester.getCenter(find.text('item 0'))); final TestGesture drag2 = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kLongPressTimeout); await drag1.moveBy(const Offset(0, 100)); await drag2.moveBy(const Offset(0, 100)); await tester.pumpAndSettle(); await drag1.up(); await drag2.up(); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }); testWidgets('negative itemCount should assert', (WidgetTester tester) async { final List<int> items = <int>[1, 2, 3]; await tester.pumpWidget(MaterialApp( home: StatefulBuilder( builder: (BuildContext outerContext, StateSetter setState) { return CustomScrollView( slivers: <Widget>[ SliverReorderableList( itemCount: -1, onReorder: (int fromIndex, int toIndex) { setState(() { if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); }); }, itemBuilder: (BuildContext context, int index) { return SizedBox( height: 100, child: Text('item ${items[index]}'), ); }, ), ], ); }, ), )); expect(tester.takeException(), isA<AssertionError>()); }); testWidgets('zero itemCount should not build widget', (WidgetTester tester) async { final List<int> items = <int>[1, 2, 3]; await tester.pumpWidget(MaterialApp( home: StatefulBuilder( builder: (BuildContext outerContext, StateSetter setState) { return CustomScrollView( slivers: <Widget>[ SliverFixedExtentList( itemExtent: 50.0, delegate: SliverChildListDelegate(<Widget>[ const Text('before'), ]), ), SliverReorderableList( itemCount: 0, onReorder: (int fromIndex, int toIndex) { setState(() { if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); }); }, itemBuilder: (BuildContext context, int index) { return SizedBox( height: 100, child: Text('item ${items[index]}'), ); }, ), SliverFixedExtentList( itemExtent: 50.0, delegate: SliverChildListDelegate(<Widget>[ const Text('after'), ]), ), ], ); }, ), )); expect(find.text('before'), findsOneWidget); expect(find.byType(SliverReorderableList), findsNothing); expect(find.text('after'), findsOneWidget); }); testWidgets('SliverReorderableList, drag and drop, fixed height items', (WidgetTester tester) async { final List<int> items = List<int>.generate(8, (int index) => index); Future<void> pressDragRelease(Offset start, Offset delta) async { final TestGesture drag = await tester.startGesture(start); await tester.pump(kPressTimeout); await drag.moveBy(delta); await tester.pump(kPressTimeout); await drag.up(); await tester.pumpAndSettle(); } void check({ List<int> visible = const <int>[], List<int> hidden = const <int>[] }) { for (final int i in visible) { expect(find.text('item $i'), findsOneWidget); } for (final int i in hidden) { expect(find.text('item $i'), findsNothing); } } // The SliverReorderableList is 800x600, 8 items, each item is 800x100 with // an "item $index" text widget at the item's origin. Drags are initiated by // a simple press on the text widget. await tester.pumpWidget(TestList(items: items)); check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]); // Drag item 0 downwards less than halfway and let it snap back. List // should remain as it is. await pressDragRelease(const Offset(12, 50), const Offset(12, 60)); check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]); expect(tester.getTopLeft(find.text('item 0')), Offset.zero); expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 100)); expect(items, orderedEquals(<int>[0, 1, 2, 3, 4, 5, 6, 7])); // Drag item 0 downwards more than halfway to displace item 1. await pressDragRelease(tester.getCenter(find.text('item 0')), const Offset(0, 51)); check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]); expect(tester.getTopLeft(find.text('item 1')), Offset.zero); expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 100)); expect(items, orderedEquals(<int>[1, 0, 2, 3, 4, 5, 6, 7])); // Drag item 0 back to where it was. await pressDragRelease(tester.getCenter(find.text('item 0')), const Offset(0, -51)); check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]); expect(tester.getTopLeft(find.text('item 0')), Offset.zero); expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 100)); expect(items, orderedEquals(<int>[0, 1, 2, 3, 4, 5, 6, 7])); // Drag item 1 to item 3 await pressDragRelease(tester.getCenter(find.text('item 1')), const Offset(0, 151)); check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]); expect(tester.getTopLeft(find.text('item 0')), Offset.zero); expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 300)); expect(tester.getTopLeft(find.text('item 3')), const Offset(0, 200)); expect(items, orderedEquals(<int>[0, 2, 3, 1, 4, 5, 6, 7])); // Drag item 1 back to where it was await pressDragRelease(tester.getCenter(find.text('item 1')), const Offset(0, -200)); check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]); expect(tester.getTopLeft(find.text('item 0')), Offset.zero); expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 100)); expect(tester.getTopLeft(find.text('item 3')), const Offset(0, 300)); expect(items, orderedEquals(<int>[0, 1, 2, 3, 4, 5, 6, 7])); }); testWidgets('SliverReorderableList, items inherit DefaultTextStyle, IconTheme', (WidgetTester tester) async { const Color textColor = Color(0xffffffff); const Color iconColor = Color(0xff0000ff); TextStyle getIconStyle() { return tester.widget<RichText>( find.descendant( of: find.byType(Icon), matching: find.byType(RichText), ), ).text.style!; } TextStyle getTextStyle() { return tester.widget<RichText>( find.descendant( of: find.text('item 0'), matching: find.byType(RichText), ), ).text.style!; } // This SliverReorderableList has just one item: "item 0". await tester.pumpWidget( TestList( items: List<int>.from(<int>[0]), textColor: textColor, iconColor: iconColor, ), ); expect(tester.getTopLeft(find.text('item 0')), Offset.zero); expect(getIconStyle().color, iconColor); expect(getTextStyle().color, textColor); // Dragging item 0 causes it to be reparented in the overlay. The item // should still inherit the IconTheme and DefaultTextStyle because they are // InheritedThemes. final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kPressTimeout); await drag.moveBy(const Offset(0, 50)); await tester.pump(kPressTimeout); expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 50)); expect(getIconStyle().color, iconColor); expect(getTextStyle().color, textColor); // Drag is complete, item 0 returns to where it was. await drag.up(); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('item 0')), Offset.zero); expect(getIconStyle().color, iconColor); expect(getTextStyle().color, textColor); }); testWidgets('SliverReorderableList - custom proxyDecorator', (WidgetTester tester) async { const ValueKey<String> fadeTransitionKey = ValueKey<String>('reordered-fade'); await tester.pumpWidget( TestList( items: List<int>.from(<int>[0, 1, 2, 3]), proxyDecorator: ( Widget child, int index, Animation<double> animation, ) { return AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { final Tween<double> fadeValues = Tween<double>(begin: 1.0, end: 0.5); final Animation<double> fadeAnimation = animation.drive(fadeValues); return FadeTransition( key: fadeTransitionKey, opacity: fadeAnimation, child: child, ); }, child: child, ); }, ), ); Finder getItemFadeTransition() => find.byKey(fadeTransitionKey); expect(getItemFadeTransition(), findsNothing); // Start gesture on first item final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kPressTimeout); // Drag enough for transition animation defined in proxyDecorator to start. await drag.moveBy(const Offset(0, 50)); await tester.pump(); // At the start, opacity should be at 1.0. expect(getItemFadeTransition(), findsOneWidget); FadeTransition fadeTransition = tester.widget(getItemFadeTransition()); expect(fadeTransition.opacity.value, 1.0); // Let animation run halfway. await tester.pump(const Duration(milliseconds: 125)); fadeTransition = tester.widget(getItemFadeTransition()); expect(fadeTransition.opacity.value, greaterThan(0.5)); expect(fadeTransition.opacity.value, lessThan(1.0)); // Allow animation to run to the end. await tester.pumpAndSettle(); expect(find.byKey(fadeTransitionKey), findsOneWidget); fadeTransition = tester.widget(getItemFadeTransition()); expect(fadeTransition.opacity.value, 0.5); // Finish reordering. await drag.up(); await tester.pumpAndSettle(); expect(getItemFadeTransition(), findsNothing); }); testWidgets('ReorderableList supports items with nested list views without throwing layout exception.', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Ensure there is always a top padding to simulate a phone with // safe area at the top. If the nested list doesn't have the // padding removed before it is put into the overlay it will // overflow the layout by the top padding. data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 50)), child: child!, ); }, home: Scaffold( appBar: AppBar(title: const Text('Nested Lists')), body: ReorderableList( itemCount: 10, itemBuilder: (BuildContext context, int index) { return ReorderableDragStartListener( index: index, key: ValueKey<int>(index), child: Column( children: <Widget>[ ListView( shrinkWrap: true, physics: const ClampingScrollPhysics(), children: const <Widget>[ Text('Other data'), Text('Other data'), Text('Other data'), ], ), ], ), ); }, onReorder: (int oldIndex, int newIndex) {}, ), ), ), ); // Start gesture on first item final TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(const ValueKey<int>(0)))); await tester.pump(kPressTimeout); // Drag enough for move to start await drag.moveBy(const Offset(0, 50)); await tester.pumpAndSettle(); // There shouldn't be a layout overflow exception. expect(tester.takeException(), isNull); }); testWidgets('ReorderableList supports items with nested list views without throwing layout exception.', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/83224. await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Ensure there is always a top padding to simulate a phone with // safe area at the top. If the nested list doesn't have the // padding removed before it is put into the overlay it will // overflow the layout by the top padding. data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 50)), child: child!, ); }, home: Scaffold( appBar: AppBar(title: const Text('Nested Lists')), body: ReorderableList( itemCount: 10, itemBuilder: (BuildContext context, int index) { return ReorderableDragStartListener( index: index, key: ValueKey<int>(index), child: Column( children: <Widget>[ ListView( shrinkWrap: true, physics: const ClampingScrollPhysics(), children: const <Widget>[ Text('Other data'), Text('Other data'), Text('Other data'), ], ), ], ), ); }, onReorder: (int oldIndex, int newIndex) {}, ), ), ), ); // Start gesture on first item. final TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(const ValueKey<int>(0)))); await tester.pump(kPressTimeout); // Drag enough for move to start. await drag.moveBy(const Offset(0, 50)); await tester.pumpAndSettle(); // There shouldn't be a layout overflow exception. expect(tester.takeException(), isNull); }); testWidgets('SliverReorderableList - properly animates the drop in a reversed list', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/110949 final List<int> items = List<int>.generate(8, (int index) => index); Future<void> pressDragRelease(Offset start, Offset delta) async { final TestGesture drag = await tester.startGesture(start); await tester.pump(kPressTimeout); await drag.moveBy(delta); await tester.pumpAndSettle(); await drag.up(); await tester.pump(); } // The TestList is 800x600 SliverReorderableList with 8 items 800x100 each. // Each item has a text widget with 'item $index' that can be moved by a // press and drag gesture. For this test we are reversing the order so // the first item is at the bottom. await tester.pumpWidget(TestList(items: items, reverse: true)); expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 500)); expect(tester.getTopLeft(find.text('item 2')), const Offset(0, 300)); // Drag item 0 up and insert it between item 1 and item 2. It should // smoothly animate. await pressDragRelease(tester.getCenter(find.text('item 0')), const Offset(0, -50)); expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 450)); expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 500)); expect(tester.getTopLeft(find.text('item 2')), const Offset(0, 300)); // After the first several frames we should be moving closer to the final position, // not further away as was the case with the original bug. await tester.pump(const Duration(milliseconds: 10)); expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(450)); expect(tester.getTopLeft(find.text('item 0')).dy, greaterThan(400)); // Sample the middle (don't use exact values as it depends on the internal // curve being used). await tester.pump(const Duration(milliseconds: 125)); expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(450)); expect(tester.getTopLeft(find.text('item 0')).dy, greaterThan(400)); // Sample the end of the animation. await tester.pump(const Duration(milliseconds: 100)); expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(450)); expect(tester.getTopLeft(find.text('item 0')).dy, greaterThan(400)); // Wait for it to finish, it should be back to the original position await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 400)); }); testWidgets('SliverReorderableList - properly animates the drop at starting position in a reversed list', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/84625 final List<int> items = List<int>.generate(8, (int index) => index); Future<void> pressDragRelease(Offset start, Offset delta) async { final TestGesture drag = await tester.startGesture(start); await tester.pump(kPressTimeout); await drag.moveBy(delta); await tester.pumpAndSettle(); await drag.up(); await tester.pump(); } // The TestList is 800x600 SliverReorderableList with 8 items 800x100 each. // Each item has a text widget with 'item $index' that can be moved by a // press and drag gesture. For this test we are reversing the order so // the first item is at the bottom. await tester.pumpWidget(TestList(items: items, reverse: true)); expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 500)); expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 400)); // Drag item 0 downwards off the edge and let it snap back. It should // smoothly animate back up. await pressDragRelease(tester.getCenter(find.text('item 0')), const Offset(0, 50)); expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 550)); expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 400)); // After the first several frames we should be moving closer to the final position, // not further away as was the case with the original bug. await tester.pump(const Duration(milliseconds: 10)); expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(550)); // Sample the middle (don't use exact values as it depends on the internal // curve being used). await tester.pump(const Duration(milliseconds: 125)); expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(550)); // Wait for it to finish, it should be back to the original position await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 500)); }); testWidgets('SliverReorderableList calls onReorderStart and onReorderEnd correctly', (WidgetTester tester) async { final List<int> items = List<int>.generate(8, (int index) => index); int? startIndex, endIndex; final Finder item0 = find.textContaining('item 0'); await tester.pumpWidget(TestList( items: items, onReorderStart: (int index) { startIndex = index; }, onReorderEnd: (int index) { endIndex = index; }, )); TestGesture drag = await tester.startGesture(tester.getCenter(item0)); await tester.pump(kPressTimeout); // Drag enough for move to start. await drag.moveBy(const Offset(0, 20)); expect(startIndex, equals(0)); expect(endIndex, isNull); // Move item0 from index 0 to index 3 await drag.moveBy(const Offset(0, 300)); await tester.pumpAndSettle(); await drag.up(); await tester.pumpAndSettle(); expect(endIndex, equals(3)); startIndex = null; endIndex = null; drag = await tester.startGesture(tester.getCenter(item0)); await tester.pump(kPressTimeout); // Drag enough for move to start. await drag.moveBy(const Offset(0, 20)); expect(startIndex, equals(2)); expect(endIndex, isNull); // Move item0 from index 2 to index 0 await drag.moveBy(const Offset(0, -200)); await tester.pumpAndSettle(); await drag.up(); await tester.pumpAndSettle(); expect(endIndex, equals(0)); }); testWidgets('ReorderableList calls onReorderStart and onReorderEnd correctly', (WidgetTester tester) async { final List<int> items = List<int>.generate(8, (int index) => index); int? startIndex, endIndex; final Finder item0 = find.textContaining('item 0'); void handleReorder(int fromIndex, int toIndex) { if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } await tester.pumpWidget(MaterialApp( home: ReorderableList( itemCount: items.length, itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDelayedDragStartListener( index: index, child: Text('item ${items[index]}'), ), ); }, onReorder: handleReorder, onReorderStart: (int index) { startIndex = index; }, onReorderEnd: (int index) { endIndex = index; }, ), )); TestGesture drag = await tester.startGesture(tester.getCenter(item0)); await tester.pump(kLongPressTimeout); // Drag enough for move to start. await drag.moveBy(const Offset(0, 20)); expect(startIndex, equals(0)); expect(endIndex, isNull); // Move item0 from index 0 to index 3 await drag.moveBy(const Offset(0, 300)); await tester.pumpAndSettle(); await drag.up(); await tester.pumpAndSettle(); expect(endIndex, equals(3)); startIndex = null; endIndex = null; drag = await tester.startGesture(tester.getCenter(item0)); await tester.pump(kLongPressTimeout); // Drag enough for move to start. await drag.moveBy(const Offset(0, 20)); expect(startIndex, equals(2)); expect(endIndex, isNull); // Move item0 from index 2 to index 0 await drag.moveBy(const Offset(0, -200)); await tester.pumpAndSettle(); await drag.up(); await tester.pumpAndSettle(); expect(endIndex, equals(0)); }); testWidgets('ReorderableList asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; expect(() => ReorderableList( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, itemExtent: 30, prototypeItem: const SizedBox(), onReorder: (int fromIndex, int toIndex) { }, ), throwsAssertionError); }); testWidgets('SliverReorderableList asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; expect(() => SliverReorderableList( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, itemExtent: 30, prototypeItem: const SizedBox(), onReorder: (int fromIndex, int toIndex) { }, ), throwsAssertionError); }); testWidgets('if itemExtent is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ReorderableList( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), // children with different heights height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, itemExtent: 30, onReorder: (int fromIndex, int toIndex) { if (fromIndex < toIndex) { toIndex--; } final int value = numbers.removeAt(fromIndex); numbers.insert(toIndex, value); }, ); }, ), ), ) ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; final double item1Height = tester.getSize(find.text('1').hitTestable()).height; final double item2Height = tester.getSize(find.text('2').hitTestable()).height; expect(item0Height, 30.0); expect(item1Height, 30.0); expect(item2Height, 30.0); }); testWidgets('if prototypeItem is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ReorderableList( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), // children with different heights height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, prototypeItem: const SizedBox( height: 30, child: Text('3'), ), onReorder: (int oldIndex, int newIndex) { }, ); }, ), ), ) ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; final double item1Height = tester.getSize(find.text('1').hitTestable()).height; final double item2Height = tester.getSize(find.text('2').hitTestable()).height; expect(item0Height, 30.0); expect(item1Height, 30.0); expect(item2Height, 30.0); }); group('ReorderableDragStartListener', () { testWidgets('It should allow the item to be dragged when enabled is true', (WidgetTester tester) async { const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); void handleReorder(int fromIndex, int toIndex) { onReorderCallCount += 1; if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( home: ReorderableList( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDragStartListener( index: index, child: Text('item ${items[index]}'), ), ); }, onReorder: handleReorder, ), ), ); // Start gesture on first item final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kPressTimeout); // Drag enough to move down the first item await drag.moveBy(const Offset(0, 50)); await tester.pump(); await drag.up(); await tester.pumpAndSettle(); expect(onReorderCallCount, 1); expect(items, orderedEquals(<int>[1, 0, 2, 3, 4])); }); testWidgets('It should not allow the item to be dragged when enabled is false', (WidgetTester tester) async { const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); void handleReorder(int fromIndex, int toIndex) { onReorderCallCount += 1; if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( home: ReorderableList( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDragStartListener( index: index, enabled: false, child: Text('item ${items[index]}'), ), ); }, onReorder: handleReorder, ), ), ); // Start gesture on first item final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kLongPressTimeout); // Drag enough to move down the first item await drag.moveBy(const Offset(0, 50)); await tester.pump(); await drag.up(); await tester.pumpAndSettle(); expect(onReorderCallCount, 0); expect(items, orderedEquals(<int>[0, 1, 2, 3, 4])); }); }); group('ReorderableDelayedDragStartListener', () { testWidgets('It should allow the item to be dragged when enabled is true', (WidgetTester tester) async { const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); void handleReorder(int fromIndex, int toIndex) { onReorderCallCount += 1; if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( home: ReorderableList( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDelayedDragStartListener( index: index, child: Text('item ${items[index]}'), ), ); }, onReorder: handleReorder, ), ), ); await tester.pumpAndSettle(); // Start gesture on first item final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kLongPressTimeout); // Drag enough to move down the first item await drag.moveBy(const Offset(0, 50)); await tester.pump(); await drag.up(); await tester.pumpAndSettle(); expect(onReorderCallCount, 1); expect(items, orderedEquals(<int>[1, 0, 2, 3, 4])); }); testWidgets('It should not allow the item to be dragged when enabled is false', (WidgetTester tester) async { const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); void handleReorder(int fromIndex, int toIndex) { onReorderCallCount += 1; if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( home: ReorderableList( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDelayedDragStartListener( index: index, enabled: false, child: Text('item ${items[index]}'), ), ); }, onReorder: handleReorder, ), ), ); // Start gesture on first item final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kLongPressTimeout); // Drag enough to move down the first item await drag.moveBy(const Offset(0, 50)); await tester.pump(); await drag.up(); await tester.pumpAndSettle(); expect(onReorderCallCount, 0); expect(items, orderedEquals(<int>[0, 1, 2, 3, 4])); }); }); testWidgets('SliverReorderableList properly disposes items', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/105010 const int itemCount = 5; final List<int> items = List<int>.generate(itemCount, (int index) => index); await tester.pumpWidget( MaterialApp( home: Scaffold( appBar: AppBar(), drawer: Drawer( child: Builder( builder: (BuildContext context) { return Column( children: <Widget>[ Expanded( child: CustomScrollView( slivers: <Widget>[ SliverReorderableList( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return Material( key: ValueKey<String>('item-$index'), child: ReorderableDragStartListener( index: index, child: ListTile( title: Text('item ${items[index]}'), ), ), ); }, onReorder: (int oldIndex, int newIndex) {}, ), ], ), ), TextButton( onPressed: () { Scaffold.of(context).closeDrawer(); }, child: const Text('Close drawer'), ), ], ); } ), ), ), ), ); await tester.tap(find.byIcon(Icons.menu)); await tester.pumpAndSettle(); final Finder item0 = find.text('item 0'); expect(item0, findsOneWidget); // Start gesture on first item without drag up event. final TestGesture drag = await tester.startGesture(tester.getCenter(item0)); await drag.moveBy(const Offset(0, 200)); await tester.pump(); await tester.tap(find.text('Close drawer')); await tester.pumpAndSettle(); expect(item0, findsNothing); }); testWidgets('SliverReorderableList auto scrolls speed is configurable', (WidgetTester tester) async { Future<void> pumpFor({ required Duration duration, Duration interval = const Duration(milliseconds: 50), }) async { await tester.pump(); int times = (duration.inMilliseconds / interval.inMilliseconds).ceil(); while (times > 0) { await tester.pump(interval + const Duration(milliseconds: 1)); await tester.idle(); times--; } } Future<double> pumpListAndDrag({required double autoScrollerVelocityScalar}) async { final List<int> items = List<int>.generate(10, (int index) => index); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( MaterialApp( home: CustomScrollView( controller: scrollController, slivers: <Widget>[ SliverReorderableList( itemBuilder: (BuildContext context, int index) { return Container( key: ValueKey<int>(items[index]), height: 100, color: items[index].isOdd ? Colors.red : Colors.green, child: ReorderableDragStartListener( index: index, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('item ${items[index]}'), const Icon(Icons.drag_handle), ], ), ), ); }, itemCount: items.length, onReorder: (int fromIndex, int toIndex) {}, autoScrollerVelocityScalar: autoScrollerVelocityScalar, ), ], ), ), ); expect(scrollController.offset, 0); final Finder item = find.text('item 0'); final TestGesture drag = await tester.startGesture(tester.getCenter(item)); // Drag just enough to touch the edge but not surpass it, so the // auto scroller is not yet triggered await drag.moveBy(const Offset(0, 500)); await pumpFor(duration: const Duration(milliseconds: 200)); expect(scrollController.offset, 0); // Now drag a little bit more so the auto scroller triggers await drag.moveBy(const Offset(0, 50)); await pumpFor( duration: const Duration(milliseconds: 600), interval: Duration(milliseconds: (1000 / autoScrollerVelocityScalar).round()), ); return scrollController.offset; } const double fastVelocityScalar = 20; final double offsetForFastScroller = await pumpListAndDrag(autoScrollerVelocityScalar: fastVelocityScalar); // Reset widget tree await tester.pumpWidget(const SizedBox()); const double slowVelocityScalar = 5; final double offsetForSlowScroller = await pumpListAndDrag(autoScrollerVelocityScalar: slowVelocityScalar); expect(offsetForFastScroller / offsetForSlowScroller, fastVelocityScalar / slowVelocityScalar); }); testWidgets('Null check error when dragging and dropping last element into last index with reverse:true', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/132077 const int itemCount = 5; final List<String> items = List<String>.generate(itemCount, (int index) => 'Item ${index+1}'); await tester.pumpWidget( MaterialApp( home: ReorderableList( onReorder: (int oldIndex, int newIndex) { if (newIndex > oldIndex) { newIndex -= 1; } final String item = items.removeAt(oldIndex); items.insert(newIndex, item); }, itemCount: items.length, reverse: true, itemBuilder: (BuildContext context, int index) { return ReorderableDragStartListener( key: Key('$index'), index: index, child: Material( child: ListTile( title: Text(items[index]), ), ), ); }, ), ) ); // Start gesture on last item final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Item 5'))); await tester.pump(kLongPressTimeout); // Drag to move up the last item, and drop at the last index await drag.moveBy(const Offset(0, -50)); await tester.pump(); await drag.up(); await tester.pumpAndSettle(); expect(tester.takeException(), null); }); testWidgets( 'When creating a new item, be in the correct position', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: LayoutBuilder( builder: (_, BoxConstraints view) { // The third one just appears on the screen final double itemSize = view.maxWidth / 2 - 20; return Scaffold( body: CustomScrollView( scrollDirection: Axis.horizontal, cacheExtent: 0, // The fourth one will not be created in the initial state. slivers: <Widget>[ SliverReorderableList( itemBuilder: (BuildContext context, int index) { return ReorderableDragStartListener( key: ValueKey<int>(index), index: index, child: Builder( builder: (BuildContext context) { return SizedBox( width: itemSize, child: Text('$index'), ); }, ), ); }, itemCount: 4, onReorder: (int fromIndex, int toIndex) {}, ), ], ), ); }, ), ), ); final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); await tester.pump(kLongPressTimeout); await drag.moveBy(const Offset(20, 0)); await tester.pump(); expect(find.text('3').hitTestable(at: Alignment.topLeft), findsNothing); await drag.up(); await tester.pumpAndSettle(); }, ); testWidgets('Tests the correctness of the drop animation in various scenarios', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/138994 late Size screenSize; final List<double> itemSizes = <double>[20, 50, 30, 80, 100, 30]; Future<void> pumpFor(bool reverse, Axis scrollDirection) async { await tester.pumpWidget( MaterialApp( home: Builder( builder: (BuildContext context) { screenSize = MediaQuery.sizeOf(context); return Scaffold( body: CustomScrollView( reverse: reverse, scrollDirection: scrollDirection, slivers: <Widget>[ SliverReorderableList( itemBuilder: (BuildContext context, int index) { return ReorderableDragStartListener( key: ValueKey<int>(index), index: index, child: Builder( builder: (BuildContext context) { return SizedBox( height: scrollDirection == Axis.vertical ? itemSizes[index] : double.infinity, width: scrollDirection == Axis.horizontal ? itemSizes[index] : double.infinity, child: Text('$index'), ); }, ), ); }, itemCount: itemSizes.length, onReorder: (int fromIndex, int toIndex) {}, ), ], ), ); } ), ), ); } Future<void> testMove(int from, int to, {bool reverse = false, Axis scrollDirection = Axis.vertical}) async { await pumpFor(reverse, scrollDirection); final double targetOffset = (List<double>.of(itemSizes)..removeAt(from)).sublist(0, to).sum; final Offset targetPosition = reverse ? (scrollDirection == Axis.vertical ? Offset(0, screenSize.height - targetOffset - itemSizes[from]) : Offset(screenSize.width - targetOffset - itemSizes[from], 0)) : (scrollDirection == Axis.vertical ? Offset(0, targetOffset) : Offset(targetOffset, 0)); final Offset moveOffset = targetPosition - tester.getTopLeft(find.text('$from')); await tester.timedDrag(find.text('$from'), moveOffset, const Duration(seconds: 1)); // Before the drop animation starts final Offset animationBeginOffset = tester.getTopLeft(find.text('$from')); // Halfway through the animation await tester.pump(const Duration(milliseconds: 125)); expect(tester.getTopLeft(find.text('$from')), Offset.lerp(animationBeginOffset, targetPosition, 0.5)); // Animation ends await tester.pump(const Duration(milliseconds: 125)); expect(tester.getTopLeft(find.text('$from')), targetPosition); await tester.pumpAndSettle(); } final List<(int,int)> testCases = <(int,int)>[ (3, 1), (3, 3), (3, 5), (0, 5), (5, 0), ]; for (final (int, int) element in testCases) { await testMove(element.$1, element.$2); await testMove(element.$1, element.$2, reverse: true); await testMove(element.$1, element.$2, scrollDirection: Axis.horizontal); await testMove(element.$1, element.$2, reverse: true, scrollDirection: Axis.horizontal); } }); testWidgets('Tests that the item position is correct when prototypeItem or itemExtent are set', (WidgetTester tester) async { Future<void> pumpFor({Widget? prototypeItem, double? itemExtent}) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ SliverReorderableList( itemBuilder: (BuildContext context, int index) { return ReorderableDragStartListener( key: ValueKey<int>(index), index: index, child: SizedBox( height: 100, child: Text('$index'), ), ); }, itemCount: 5, itemExtent: itemExtent, prototypeItem: prototypeItem, onReorder: (int fromIndex, int toIndex) {}, ), ], ), ), ), ); } Future<void> testFor({Widget? prototypeItem, double? itemExtent}) async { await pumpFor(prototypeItem: prototypeItem, itemExtent: itemExtent); final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); await tester.pump(kLongPressTimeout); await drag.moveBy(const Offset(0, 20)); await tester.pump(); expect(tester.getTopLeft(find.text('1')), const Offset(0, 100)); await drag.up(); await tester.pumpAndSettle(); } await testFor(); await testFor(prototypeItem: const SizedBox(height: 100, width: 100, child: Text('prototype'))); await testFor(itemExtent: 100); }); } class TestList extends StatelessWidget { const TestList({ super.key, this.textColor, this.iconColor, this.proxyDecorator, required this.items, this.reverse = false, this.onReorderStart, this.onReorderEnd, this.autoScrollerVelocityScalar, }); final List<int> items; final Color? textColor; final Color? iconColor; final ReorderItemProxyDecorator? proxyDecorator; final bool reverse; final void Function(int)? onReorderStart, onReorderEnd; final double? autoScrollerVelocityScalar; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: DefaultTextStyle( style: TextStyle(color: textColor), child: IconTheme( data: IconThemeData(color: iconColor), child: StatefulBuilder( builder: (BuildContext outerContext, StateSetter setState) { final List<int> items = this.items; return CustomScrollView( reverse: reverse, slivers: <Widget>[ SliverReorderableList( itemBuilder: (BuildContext context, int index) { return Container( key: ValueKey<int>(items[index]), height: 100, color: items[index].isOdd ? Colors.red : Colors.green, child: ReorderableDragStartListener( index: index, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('item ${items[index]}'), const Icon(Icons.drag_handle), ], ), ), ); }, itemCount: items.length, onReorder: (int fromIndex, int toIndex) { setState(() { if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); }); }, proxyDecorator: proxyDecorator, onReorderStart: onReorderStart, onReorderEnd: onReorderEnd, autoScrollerVelocityScalar: autoScrollerVelocityScalar, ), ], ); }, ), ), ), ), ); } }
flutter/packages/flutter/test/widgets/reorderable_list_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/reorderable_list_test.dart", "repo_id": "flutter", "token_count": 27529 }
694
// 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/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class OrderPainter extends CustomPainter { const OrderPainter(this.index); final int index; static List<int> log = <int>[]; @override void paint(Canvas canvas, Size size) { log.add(index); } @override bool shouldRepaint(OrderPainter old) => false; } Widget log(int index) => CustomPaint(painter: OrderPainter(index)); void main() { // NO DIRECTION testWidgets('Row with one Flexible child - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); final FlutterExceptionHandler? oldHandler = FlutterError.onError; dynamic exception; FlutterError.onError = (FlutterErrorDetails details) { exception ??= details.exception; }; // Default is MainAxisAlignment.start so this should fail, asking for a direction. await tester.pumpWidget(Center( child: Row( key: rowKey, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); FlutterError.onError = oldHandler; expect(exception, isAssertionError); expect(exception.toString(), contains('textDirection')); expect(OrderPainter.log, <int>[]); }); testWidgets('Row with default main axis parameters - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); final FlutterExceptionHandler? oldHandler = FlutterError.onError; dynamic exception; FlutterError.onError = (FlutterErrorDetails details) { exception ??= details.exception; }; // Default is MainAxisAlignment.start so this should fail too. await tester.pumpWidget(Center( child: Row( key: rowKey, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); FlutterError.onError = oldHandler; expect(exception, isAssertionError); expect(exception.toString(), contains('textDirection')); expect(OrderPainter.log, <int>[]); }); testWidgets('Row with MainAxisAlignment.center - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); final FlutterExceptionHandler? oldHandler = FlutterError.onError; dynamic exception; FlutterError.onError = (FlutterErrorDetails details) { exception ??= details.exception; }; // More than one child, so it's not clear what direction to lay out in: should fail. await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), ], ), )); FlutterError.onError = oldHandler; expect(exception, isAssertionError); expect(exception.toString(), contains('textDirection')); expect(OrderPainter.log, <int>[]); }); testWidgets('Row with MainAxisAlignment.end - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); final FlutterExceptionHandler? oldHandler = FlutterError.onError; dynamic exception; FlutterError.onError = (FlutterErrorDetails details) { exception ??= details.exception; }; // No direction so this should fail, asking for a direction. await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); FlutterError.onError = oldHandler; expect(exception, isAssertionError); expect(exception.toString(), contains('textDirection')); expect(OrderPainter.log, <int>[]); }); testWidgets('Row with MainAxisAlignment.spaceBetween - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); final FlutterExceptionHandler? oldHandler = FlutterError.onError; dynamic exception; FlutterError.onError = (FlutterErrorDetails details) { exception ??= details.exception; }; // More than one child, so it's not clear what direction to lay out in: should fail. await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); FlutterError.onError = oldHandler; expect(exception, isAssertionError); expect(exception.toString(), contains('textDirection')); expect(OrderPainter.log, <int>[]); }); testWidgets('Row with MainAxisAlignment.spaceAround - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); const Key child3Key = Key('child3'); final FlutterExceptionHandler? oldHandler = FlutterError.onError; dynamic exception; FlutterError.onError = (FlutterErrorDetails details) { exception ??= details.exception; }; // More than one child, so it's not clear what direction to lay out in: should fail. await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), ], ), )); FlutterError.onError = oldHandler; expect(exception, isAssertionError); expect(exception.toString(), contains('textDirection')); expect(OrderPainter.log, <int>[]); }); testWidgets('Row with MainAxisAlignment.spaceEvenly - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); final FlutterExceptionHandler? oldHandler = FlutterError.onError; dynamic exception; FlutterError.onError = (FlutterErrorDetails details) { exception ??= details.exception; }; // More than one child, so it's not clear what direction to lay out in: should fail. await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), ], ), )); FlutterError.onError = oldHandler; expect(exception, isAssertionError); expect(exception.toString(), contains('textDirection')); expect(OrderPainter.log, <int>[]); }); testWidgets('Row and MainAxisSize.min - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('rowKey'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); final FlutterExceptionHandler? oldHandler = FlutterError.onError; dynamic exception; FlutterError.onError = (FlutterErrorDetails details) { exception ??= details.exception; }; // Default is MainAxisAlignment.start so this should fail, asking for a direction. await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), ], ), )); FlutterError.onError = oldHandler; expect(exception, isAssertionError); expect(exception.toString(), contains('textDirection')); expect(OrderPainter.log, <int>[]); }); testWidgets('Row MainAxisSize.min layout at zero size - no textDirection', (WidgetTester tester) async { OrderPainter.log.clear(); const Key childKey = Key('childKey'); await tester.pumpWidget(const Center( child: SizedBox.shrink( child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( key: childKey, width: 100.0, height: 100.0, ), ], ), ), )); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(0.0)); }); // LTR testWidgets('Row with one Flexible child - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // Default is MainAxisAlignment.start so children so the children's // left edges should be at 0, 100, 700, child2's width should be 600 await tester.pumpWidget(Center( child: Row( key: rowKey, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(0.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(600.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(100.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(700.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row with default main axis parameters - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // Default is MainAxisAlignment.start so children so the children's // left edges should be at 0, 100, 200 await tester.pumpWidget(Center( child: Row( key: rowKey, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(0.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(100.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(200.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row with MainAxisAlignment.center - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's left edges should be at 300, 400 await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.center, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(300.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(400.0)); expect(OrderPainter.log, <int>[1, 2]); }); testWidgets('Row with MainAxisAlignment.end - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's left edges should be at 500, 600, 700. await tester.pumpWidget(Center( child: Row( key: rowKey, textDirection: TextDirection.ltr, mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(500.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(600.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(700.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row with MainAxisAlignment.spaceBetween - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's left edges should be at 0, 350, 700 await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceBetween, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(0.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(350.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(700.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row with MainAxisAlignment.spaceAround - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); const Key child3Key = Key('child3'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's left edges should be at 50, 250, 450, 650 await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceAround, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(50.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(250.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(450.0)); renderBox = tester.renderObject(find.byKey(child3Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(650.0)); expect(OrderPainter.log, <int>[1, 2, 3, 4]); }); testWidgets('Row with MainAxisAlignment.spaceEvenly - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 200x100 children's left edges should be at 50, 300, 550 await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceEvenly, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(200.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(50.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(200.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(300.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(200.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(550.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row and MainAxisSize.min - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('rowKey'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); // Row with MainAxisSize.min without flexible children shrink wraps. // Row's width should be 250, children should be at 0, 100. await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisSize: MainAxisSize.min, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(250.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(0.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(150.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(100.0)); expect(OrderPainter.log, <int>[1, 2]); }); testWidgets('Row MainAxisSize.min layout at zero size - LTR', (WidgetTester tester) async { OrderPainter.log.clear(); const Key childKey = Key('childKey'); await tester.pumpWidget(const Center( child: SizedBox.shrink( child: Row( textDirection: TextDirection.ltr, mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( key: childKey, width: 100.0, height: 100.0, ), ], ), ), )); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(0.0)); }); // RTL testWidgets('Row with one Flexible child - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // Default is MainAxisAlignment.start so children so the children's // right edges should be at 0, 100, 700 from the right, child2's width should be 600 await tester.pumpWidget(Center( child: Row( key: rowKey, textDirection: TextDirection.rtl, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(700.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(600.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(100.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(0.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row with default main axis parameters - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // Default is MainAxisAlignment.start so children so the children's // right edges should be at 0, 100, 200 from the right await tester.pumpWidget(Center( child: Row( key: rowKey, textDirection: TextDirection.rtl, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(700.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(600.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(500.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row with MainAxisAlignment.center - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's right edges should be at 300, 400 from the right await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.center, textDirection: TextDirection.rtl, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(400.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(300.0)); expect(OrderPainter.log, <int>[1, 2]); }); testWidgets('Row with MainAxisAlignment.end - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's right edges should be at 500, 600, 700 from the right. await tester.pumpWidget(Center( child: Row( key: rowKey, textDirection: TextDirection.rtl, mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(200.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(100.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(0.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row with MainAxisAlignment.spaceBetween - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's right edges should be at 0, 350, 700 from the right await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceBetween, textDirection: TextDirection.rtl, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(700.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(350.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(0.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row with MainAxisAlignment.spaceAround - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); const Key child3Key = Key('child3'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's right edges should be at 50, 250, 450, 650 from the right await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceAround, textDirection: TextDirection.rtl, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(650.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(450.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(250.0)); renderBox = tester.renderObject(find.byKey(child3Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(50.0)); expect(OrderPainter.log, <int>[1, 2, 3, 4]); }); testWidgets('Row with MainAxisAlignment.spaceEvenly - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 200x100 children's right edges should be at 50, 300, 550 from the right await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisAlignment: MainAxisAlignment.spaceEvenly, textDirection: TextDirection.rtl, children: <Widget>[ SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(200.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(550.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(200.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(300.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(200.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(50.0)); expect(OrderPainter.log, <int>[1, 2, 3]); }); testWidgets('Row and MainAxisSize.min - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key rowKey = Key('rowKey'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); // Row with MainAxisSize.min without flexible children shrink wraps. // Row's width should be 250, children should be at 0, 100 from right. await tester.pumpWidget(Center( child: Row( key: rowKey, mainAxisSize: MainAxisSize.min, textDirection: TextDirection.rtl, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(rowKey)); expect(renderBox.size.width, equals(250.0)); expect(renderBox.size.height, equals(100.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(150.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(150.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dx, equals(0.0)); expect(OrderPainter.log, <int>[1, 2]); }); testWidgets('Row MainAxisSize.min layout at zero size - RTL', (WidgetTester tester) async { OrderPainter.log.clear(); const Key childKey = Key('childKey'); await tester.pumpWidget(const Center( child: SizedBox.shrink( child: Row( textDirection: TextDirection.rtl, mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( key: childKey, width: 100.0, height: 100.0, ), ], ), ), )); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(0.0)); }); }
flutter/packages/flutter/test/widgets/row_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/row_test.dart", "repo_id": "flutter", "token_count": 16993 }
695
// 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/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Does not animate if already at target position', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: List<Widget>.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), ), ), ); expectNoAnimation(); final double currentPosition = controller.position.pixels; controller.position.animateTo(currentPosition, duration: const Duration(seconds: 10), curve: Curves.linear); expectNoAnimation(); expect(controller.position.pixels, currentPosition); }); testWidgets('Does not animate if already at target position within tolerance', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: List<Widget>.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), ), ), ); expectNoAnimation(); final double halfTolerance = controller.position.physics.toleranceFor(controller.position).distance / 2; expect(halfTolerance, isNonZero); final double targetPosition = controller.position.pixels + halfTolerance; controller.position.animateTo(targetPosition, duration: const Duration(seconds: 10), curve: Curves.linear); expectNoAnimation(); expect(controller.position.pixels, targetPosition); }); testWidgets('Animates if going to a position outside of tolerance', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: List<Widget>.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), ), ), ); expectNoAnimation(); final double doubleTolerance = controller.position.physics.toleranceFor(controller.position).distance * 2; expect(doubleTolerance, isNonZero); final double targetPosition = controller.position.pixels + doubleTolerance; controller.position.animateTo(targetPosition, duration: const Duration(seconds: 10), curve: Curves.linear); expect(SchedulerBinding.instance.transientCallbackCount, equals(1), reason: 'Expected an animation.'); }); } void expectNoAnimation() { expect(SchedulerBinding.instance.transientCallbackCount, equals(0), reason: 'Expected no animation.'); }
flutter/packages/flutter/test/widgets/scrollable_animations_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/scrollable_animations_test.dart", "repo_id": "flutter", "token_count": 1029 }
696
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) @TestOn('!chrome') library; import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle; import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../impeller_test_helpers.dart'; import '../widgets/clipboard_utils.dart'; import '../widgets/editable_text_utils.dart' show textOffsetToPosition; import '../widgets/semantics_tester.dart'; class MaterialLocalizationsDelegate extends LocalizationsDelegate<MaterialLocalizations> { @override bool isSupported(Locale locale) => true; @override Future<MaterialLocalizations> load(Locale locale) => DefaultMaterialLocalizations.load(locale); @override bool shouldReload(MaterialLocalizationsDelegate old) => false; } class WidgetsLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocalizations> { @override bool isSupported(Locale locale) => true; @override Future<WidgetsLocalizations> load(Locale locale) => DefaultWidgetsLocalizations.load(locale); @override bool shouldReload(WidgetsLocalizationsDelegate old) => false; } Widget overlay({ Widget? child }) { final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) { return Center( child: Material( child: child, ), ); }, ); addTearDown(() => entry..remove()..dispose()); return overlayWithEntry(entry); } Widget overlayWithEntry(OverlayEntry entry) { return Theme( data: ThemeData(useMaterial3: false), child: Localizations( locale: const Locale('en', 'US'), delegates: <LocalizationsDelegate<dynamic>>[ WidgetsLocalizationsDelegate(), MaterialLocalizationsDelegate(), ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), child: Overlay( initialEntries: <OverlayEntry>[ entry, ], ), ), ), ), ); } Widget boilerplate({ Widget? child }) { return Theme( data: ThemeData(useMaterial3: false), child:Localizations( locale: const Locale('en', 'US'), delegates: <LocalizationsDelegate<dynamic>>[ WidgetsLocalizationsDelegate(), MaterialLocalizationsDelegate(), ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), child: Center( child: Material( child: child, ), ), ), ), ), ); } Future<void> skipPastScrollingAnimation(WidgetTester tester) async { await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final MockClipboard mockClipboard = MockClipboard(); const String kThreeLines = 'First line of text is\n' 'Second line goes until\n' 'Third line of stuff'; const String kMoreThanFourLines = '$kThreeLines\n' "Fourth line won't display and ends at"; // Returns the first RenderEditable. RenderEditable findRenderEditable(WidgetTester tester) { final RenderObject root = tester.renderObject(find.byType(EditableText)); expect(root, isNotNull); late RenderEditable renderEditable; void recursiveFinder(RenderObject child) { if (child is RenderEditable) { renderEditable = child; return; } child.visitChildren(recursiveFinder); } root.visitChildren(recursiveFinder); expect(renderEditable, isNotNull); return renderEditable; } // Check that the Cupertino text selection toolbar is the expected one on iOS and macOS. // TODO(bleroux): try to merge this into text_selection_toolbar_utils.dart // (for instance by adding a 'readOnly' flag). void expectCupertinoSelectionToolbar() { // This function is valid only for tests running on Apple platforms. expect(defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS, isTrue); if (defaultTargetPlatform == TargetPlatform.iOS) { expect(find.byType(CupertinoButton), findsNWidgets(4)); expect(find.text('Copy'), findsOneWidget); expect(find.text('Look Up'), findsOneWidget); expect(find.text('Search Web'), findsOneWidget); expect(find.text('Share...'), findsOneWidget); } else { expect(find.byType(CupertinoButton), findsNWidgets(1)); expect(find.text('Copy'), findsOneWidget); } } // Check that the Material text selection toolbar is the expected one. // TODO(bleroux): Try to merge this into text_selection_toolbar_utils.dart // (for instance by adding a 'readOnly' flag). void expectMaterialSelectionToolbar() { if (defaultTargetPlatform == TargetPlatform.android) { expect(find.byType(TextButton), findsNWidgets(3)); expect(find.text('Copy'), findsOneWidget); expect(find.text('Share'), findsOneWidget); expect(find.text('Select all'), findsOneWidget); } else { expect(find.byType(TextButton), findsNWidgets(2)); expect(find.text('Copy'), findsOneWidget); expect(find.text('Select all'), findsOneWidget); } } List<TextSelectionPoint> globalize(Iterable<TextSelectionPoint> points, RenderBox box) { return points.map<TextSelectionPoint>((TextSelectionPoint point) { return TextSelectionPoint( box.localToGlobal(point.point), point.direction, ); }).toList(); } setUp(() async { debugResetSemanticsIdCounter(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, mockClipboard.handleMethodCall, ); // Fill the clipboard so that the Paste option is available in the text // selection menu. await Clipboard.setData(const ClipboardData(text: 'Clipboard data')); }); tearDown(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, null, ); }); Widget selectableTextBuilder({ String text = '', int? maxLines = 1, int? minLines, }) { return boilerplate( child: SelectableText( text, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: maxLines, minLines: minLines, ), ); } testWidgets('throw if no Overlay widget exists above', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: MediaQueryData(size: Size(800.0, 600.0)), child: Center( child: Material( child: SelectableText('I love Flutter!'), ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(SelectableText)); final TestGesture gesture = await tester.startGesture(textFieldStart, kind: PointerDeviceKind.mouse); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); final FlutterError error = tester.takeException() as FlutterError; expect( error.message, contains('EditableText widgets require an Overlay widget ancestor'), ); await tester.pumpWidget(const SizedBox.shrink()); expect(tester.takeException(), isNotNull); // side effect exception }); testWidgets('Do not crash when remove SelectableText during handle drag', (WidgetTester tester) async { // Regression test https://github.com/flutter/flutter/issues/108242 bool isShow = true; late StateSetter setter; await tester.pumpWidget( MaterialApp( home: Material( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { setter = setState; if (isShow) { return const SelectableText( 'abc def ghi', dragStartBehavior: DragStartBehavior.down, ); } else { return const SizedBox.shrink(); } }, ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, 5); TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); expect(selection.extentOffset, 7); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the left handle to the left. final Offset handlePos = endpoints[0].point + const Offset(-1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, 1); final Offset newHandlePos1 = textOffsetToPosition(tester, 0); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); // Unmount the SelectableText during handle drag. setter(() { isShow = false; }); await tester.pump(); await gesture.moveTo(newHandlePos1); await tester.pump(); // Do not crash here. await gesture.up(); await tester.pump(); }); testWidgets('has expected defaults', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( child: const SelectableText('selectable text'), ), ); final SelectableText selectableText = tester.firstWidget(find.byType(SelectableText)); expect(selectableText.showCursor, false); expect(selectableText.autofocus, false); expect(selectableText.dragStartBehavior, DragStartBehavior.start); expect(selectableText.cursorWidth, 2.0); expect(selectableText.cursorHeight, isNull); expect(selectableText.enableInteractiveSelection, true); }); testWidgets('Rich selectable text has expected defaults', (WidgetTester tester) async { await tester.pumpWidget( const MediaQuery( data: MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: SelectableText.rich( TextSpan( text: 'First line!', style: TextStyle( fontSize: 14, fontFamily: 'Roboto', ), children: <TextSpan>[ TextSpan( text: 'Second line!\n', style: TextStyle( fontSize: 30, fontFamily: 'Roboto', ), ), TextSpan( text: 'Third line!\n', style: TextStyle( fontSize: 14, fontFamily: 'Roboto', ), ), ], ), ), ), ), ); final SelectableText selectableText = tester.firstWidget(find.byType(SelectableText)); expect(selectableText.showCursor, false); expect(selectableText.autofocus, false); expect(selectableText.dragStartBehavior, DragStartBehavior.start); expect(selectableText.cursorWidth, 2.0); expect(selectableText.cursorHeight, isNull); expect(selectableText.enableInteractiveSelection, true); }); testWidgets('Rich selectable text supports WidgetSpan', (WidgetTester tester) async { await tester.pumpWidget( const MediaQuery( data: MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: SelectableText.rich( TextSpan( text: 'First line!', style: TextStyle( fontSize: 14, fontFamily: 'Roboto', ), children: <InlineSpan>[ WidgetSpan( child: SizedBox( width: 120, height: 50, child: Card( child: Center( child: Text('Hello World!'), ), ), ), ), TextSpan( text: 'Third line!\n', style: TextStyle( fontSize: 14, fontFamily: 'Roboto', ), ), ], ), ), ), ), ); expect(tester.takeException(), isNull); }); testWidgets('no text keyboard when widget is focused', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText('selectable text'), ), ); await tester.tap(find.byType(SelectableText)); await tester.idle(); expect(tester.testTextInput.hasAnyClients, false); }); testWidgets('uses DefaultSelectionStyle for selection and cursor colors if provided', (WidgetTester tester) async { const Color selectionColor = Colors.orange; const Color cursorColor = Colors.red; await tester.pumpWidget( const MaterialApp( home: Material( child: DefaultSelectionStyle( selectionColor: selectionColor, cursorColor: cursorColor, child: SelectableText('text'), ), ), ), ); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.widget.selectionColor, selectionColor); expect(state.widget.cursorColor, cursorColor); }); testWidgets('Selectable Text has adaptive size', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( child: const SelectableText('s'), ), ); RenderBox findSelectableTextBox() => tester.renderObject(find.byType(SelectableText)); final RenderBox textBox = findSelectableTextBox(); expect(textBox.size, const Size(17.0, 14.0)); await tester.pumpWidget( boilerplate( child: const SelectableText('very very long'), ), ); final RenderBox longtextBox = findSelectableTextBox(); expect(longtextBox.size, const Size(199.0, 14.0)); }); testWidgets('can scale with textScaleFactor', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( child: const SelectableText('selectable text'), ), ); final RenderBox renderBox = tester.renderObject(find.byType(SelectableText)); expect(renderBox.size.height, 14.0); await tester.pumpWidget( boilerplate( child: const SelectableText( 'selectable text', textScaleFactor: 1.9, ), ), ); final RenderBox scaledBox = tester.renderObject(find.byType(SelectableText)); expect(scaledBox.size.height, 27.0); }); testWidgets('can switch between textWidthBasis', (WidgetTester tester) async { RenderBox findTextBox() => tester.renderObject(find.byType(SelectableText)); const String text = 'I can face roll keyboardkeyboardaszzaaaaszzaaaaszzaaaaszzaaaa'; await tester.pumpWidget( boilerplate( child: const SelectableText( text, textWidthBasis: TextWidthBasis.parent, ), ), ); RenderBox textBox = findTextBox(); expect(textBox.size, const Size(800.0, 28.0)); await tester.pumpWidget( boilerplate( child: const SelectableText( text, textWidthBasis: TextWidthBasis.longestLine, ), ), ); textBox = findTextBox(); expect(textBox.size, const Size(633.0, 28.0)); }); testWidgets('can switch between textHeightBehavior', (WidgetTester tester) async { const String text = 'selectable text'; const TextHeightBehavior textHeightBehavior = TextHeightBehavior( applyHeightToFirstAscent: false, applyHeightToLastDescent: false, ); await tester.pumpWidget( boilerplate( child: const SelectableText(text), ), ); expect(findRenderEditable(tester).textHeightBehavior, isNull); await tester.pumpWidget( boilerplate( child: const SelectableText( text, textHeightBehavior: textHeightBehavior, ), ), ); expect(findRenderEditable(tester).textHeightBehavior, textHeightBehavior); }); testWidgets('Cursor blinks when showCursor is true', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText( 'some text', showCursor: true, ), ), ); await tester.tap(find.byType(SelectableText)); await tester.idle(); final EditableTextState editableText = tester.state(find.byType(EditableText)); // Check that the cursor visibility toggles after each blink interval. final bool initialShowCursor = editableText.cursorCurrentlyVisible; await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(!initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval ~/ 10); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(!initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); }); testWidgets('selectable text selection toolbar renders correctly inside opacity', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Center( child: SizedBox( width: 100, height: 100, child: Opacity( opacity: 0.5, child: SelectableText('selectable text'), ), ), ), ), ), ); // The selectWordsInRange with SelectionChangedCause.tap seems to be needed to show the toolbar. final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); expect(state.showToolbar(), true); // This is needed for the AnimatedOpacity to turn from 0 to 1 so the toolbar is visible. await tester.pumpAndSettle(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Select all'), findsOneWidget); }); testWidgets('Caret position is updated on tap', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText('abc def ghi'), ), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.controller.selection.baseOffset, -1); expect(editableText.controller.selection.extentOffset, -1); // Tap to reposition the caret. const int tapIndex = 4; final Offset ePos = textOffsetToPosition(tester, tapIndex); await tester.tapAt(ePos); await tester.pump(); expect(editableText.controller.selection.baseOffset, tapIndex); expect(editableText.controller.selection.extentOffset, tapIndex); }); testWidgets('enableInteractiveSelection = false, tap', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText( 'abc def ghi', enableInteractiveSelection: false, ), ), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.controller.selection.baseOffset, -1); expect(editableText.controller.selection.extentOffset, -1); // Tap would ordinarily reposition the caret. const int tapIndex = 4; final Offset ePos = textOffsetToPosition(tester, tapIndex); await tester.tapAt(ePos); await tester.pump(); expect(editableText.controller.selection.baseOffset, -1); expect(editableText.controller.selection.extentOffset, -1); }); testWidgets('enableInteractiveSelection = false, long-press', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText( 'abc def ghi', enableInteractiveSelection: false, ), ), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.controller.selection.baseOffset, -1); expect(editableText.controller.selection.extentOffset, -1); // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, 5); final TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); expect(editableText.controller.selection.isCollapsed, true); expect(editableText.controller.selection.baseOffset, -1); expect(editableText.controller.selection.extentOffset, -1); }); testWidgets('Can long press to select', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText('abc def ghi'), ), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.controller.selection.isCollapsed, true); // Long press the 'e' to select 'def'. const int tapIndex = 5; final Offset ePos = textOffsetToPosition(tester, tapIndex); await tester.longPressAt(ePos); await tester.pump(); // 'def' is selected. expect(editableText.controller.selection.baseOffset, 4); expect(editableText.controller.selection.extentOffset, 7); // Tapping elsewhere immediately collapses and moves the cursor. await tester.tapAt(textOffsetToPosition(tester, 9)); await tester.pump(); expect(editableText.controller.selection.isCollapsed, true); expect(editableText.controller.selection.baseOffset, 9); }); testWidgets("Slight movements in longpress don't hide/show handles", (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText('abc def ghi'), ), ); // Long press the 'e' to select 'def', but don't release the gesture. final Offset ePos = textOffsetToPosition(tester, 5); final TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await tester.pumpAndSettle(); // Handles are shown. final Finder fadeFinder = find.byType(FadeTransition); expect(fadeFinder, findsNWidgets(2)); // 2 handles, 1 toolbar FadeTransition handle = tester.widget(fadeFinder.at(0)); expect(handle.opacity.value, equals(1.0)); // Move the gesture very slightly. await gesture.moveBy(const Offset(1.0, 1.0)); await tester.pump(SelectionOverlay.fadeDuration * 0.5); handle = tester.widget(fadeFinder.at(0)); // The handle should still be fully opaque. expect(handle.opacity.value, equals(1.0)); }); testWidgets('Mouse long press is just like a tap', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText('abc def ghi'), ), ); final EditableText editableText = tester.widget(find.byType(EditableText)); // Long press the 'e' using a mouse device. const int eIndex = 5; final Offset ePos = textOffsetToPosition(tester, eIndex); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); // The cursor is placed just like a regular tap. expect(editableText.controller.selection.baseOffset, eIndex); expect(editableText.controller.selection.extentOffset, eIndex); }); testWidgets('selectable text basic', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText('selectable'), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); // Selectable text cannot open keyboard. await tester.showKeyboard(find.byType(SelectableText)); expect(tester.testTextInput.hasAnyClients, false); await skipPastScrollingAnimation(tester); expect(editableTextWidget.controller.selection.isCollapsed, true); await tester.tap(find.byType(SelectableText)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); // Collapse selection should not paint. expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); // Long press on the 't' character of text 'selectable' to show context menu. const int dIndex = 5; final Offset dPos = textOffsetToPosition(tester, dIndex); await tester.longPressAt(dPos); await tester.pump(); // Context menu should not have paste and cut. expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); }); testWidgets('selectable text can disable toolbar options', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText( 'a selectable text', toolbarOptions: ToolbarOptions( selectAll: true, ), ), ), ); const int dIndex = 5; final Offset dPos = textOffsetToPosition(tester, dIndex); await tester.longPressAt(dPos); await tester.pump(); // Context menu should not have copy. expect(find.text('Copy'), findsNothing); expect(find.text('Select all'), findsOneWidget); }); testWidgets('Can select text by dragging with a mouse', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText( 'abc def ghi', dragStartBehavior: DragStartBehavior.down, ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; final Offset ePos = textOffsetToPosition(tester, 5); final Offset gPos = textOffsetToPosition(tester, 8); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.moveTo(gPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 8); }); testWidgets('Continuous dragging does not cause flickering', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText( 'abc def ghi', dragStartBehavior: DragStartBehavior.down, style: TextStyle(fontSize: 10.0), ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; int selectionChangedCount = 0; controller.addListener(() { selectionChangedCount++; }); final Offset cPos = textOffsetToPosition(tester, 2); // Index of 'c'. final Offset gPos = textOffsetToPosition(tester, 8); // Index of 'g'. final Offset hPos = textOffsetToPosition(tester, 9); // Index of 'h'. // Drag from 'c' to 'g'. final TestGesture gesture = await tester.startGesture(cPos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(selectionChangedCount, isNonZero); selectionChangedCount = 0; expect(controller.selection.baseOffset, 2); expect(controller.selection.extentOffset, 8); // Tiny movement shouldn't cause text selection to change. await gesture.moveTo(gPos + const Offset(4.0, 0.0)); await tester.pumpAndSettle(); expect(selectionChangedCount, 0); // Now a text selection change will occur after a significant movement. await gesture.moveTo(hPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(selectionChangedCount, 1); expect(controller.selection.baseOffset, 2); expect(controller.selection.extentOffset, 9); }); testWidgets('Dragging in opposite direction also works', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText( 'abc def ghi', dragStartBehavior: DragStartBehavior.down, ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; final Offset ePos = textOffsetToPosition(tester, 5); final Offset gPos = textOffsetToPosition(tester, 8); final TestGesture gesture = await tester.startGesture(gPos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.moveTo(ePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 5); }); testWidgets('Slow mouse dragging also selects text', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText( 'abc def ghi', dragStartBehavior: DragStartBehavior.down, ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; final Offset ePos = textOffsetToPosition(tester, 5); final Offset gPos = textOffsetToPosition(tester,8); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(const Duration(seconds: 2)); await gesture.moveTo(gPos); await tester.pump(); await gesture.up(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset,8); }); testWidgets('Can drag handles to change selection', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText( 'abc def ghi', dragStartBehavior: DragStartBehavior.down, ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, 5); TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); expect(selection.extentOffset, 7); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle 2 letters to the right. // We use a small offset because the endpoint is on the very corner // of the handle. Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); Offset newHandlePos = textOffsetToPosition(tester, 11); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 11); // Drag the left handle 2 letters to the left. handlePos = endpoints[0].point + const Offset(-1.0, 1.0); newHandlePos = textOffsetToPosition(tester, 0); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 11); }); testWidgets('Dragging handles calls onSelectionChanged', (WidgetTester tester) async { TextSelection? newSelection; await tester.pumpWidget( MaterialApp( home: Material( child: SelectableText( 'abc def ghi', dragStartBehavior: DragStartBehavior.down, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { expect(newSelection, isNull); newSelection = selection; }, ), ), ), ); // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, 5); TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero expect(newSelection!.baseOffset, 4); expect(newSelection!.extentOffset, 7); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(newSelection!), renderEditable, ); expect(endpoints.length, 2); newSelection = null; // Drag the right handle 2 letters to the right. // We use a small offset because the endpoint is on the very corner // of the handle. final Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, 9); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(newSelection!.baseOffset, 4); expect(newSelection!.extentOffset, 9); }); testWidgets('Cannot drag one handle past the other', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText( 'abc def ghi', dragStartBehavior: DragStartBehavior.down, ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; // Long press the 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, 5); // Position before 'e'. TestGesture gesture = await tester.startGesture(ePos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); expect(selection.extentOffset, 7); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle until there's only 1 char selected. // We use a small offset because the endpoint is on the very corner // of the handle. final Offset handlePos = endpoints[1].point + const Offset(4.0, 0.0); Offset newHandlePos = textOffsetToPosition(tester, 5); // Position before 'e'. gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 5); newHandlePos = textOffsetToPosition(tester, 2); // Position before 'c'. await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); // The selection doesn't move beyond the left handle. There's always at // least 1 char selected. expect(controller.selection.extentOffset, 5); }); testWidgets('Can use selection toolbar', (WidgetTester tester) async { const String testValue = 'abc def ghi'; await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText( testValue, ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); // Tapping on the part of the handle's GestureDetector where it overlaps // with the text itself does not show the menu, so add a small vertical // offset to tap below the text. await tester.tapAt(endpoints[0].point + const Offset(1.0, 13.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero // Select all should select all the text. await tester.tap(find.text('Select all')); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, testValue.length); // Copy should reset the selection. await tester.tap(find.text('Copy')); await skipPastScrollingAnimation(tester); expect(controller.selection.isCollapsed, true); }); testWidgets('Selectable height with maxLine', (WidgetTester tester) async { await tester.pumpWidget(selectableTextBuilder()); RenderBox findTextBox() => tester.renderObject(find.byType(SelectableText)); final RenderBox textBox = findTextBox(); final Size emptyInputSize = textBox.size; await tester.pumpWidget(selectableTextBuilder(text: 'No wrapping here.')); expect(findTextBox(), equals(textBox)); expect(textBox.size.height, emptyInputSize.height); // Even when entering multiline text, SelectableText doesn't grow. It's a single // line input. await tester.pumpWidget(selectableTextBuilder(text: kThreeLines)); expect(findTextBox(), equals(textBox)); expect(textBox.size.height, emptyInputSize.height); // maxLines: 3 makes the SelectableText 3 lines tall. await tester.pumpWidget(selectableTextBuilder(maxLines: 3)); expect(findTextBox(), equals(textBox)); expect(textBox.size.height, greaterThan(emptyInputSize.height)); final Size threeLineInputSize = textBox.size; // Filling with 3 lines of text stays the same size. await tester.pumpWidget(selectableTextBuilder(text: kThreeLines, maxLines: 3)); expect(findTextBox(), equals(textBox)); expect(textBox.size.height, threeLineInputSize.height); // An extra line won't increase the size because we max at 3. await tester.pumpWidget(selectableTextBuilder(text: kMoreThanFourLines, maxLines: 3)); expect(findTextBox(), equals(textBox)); expect(textBox.size.height, threeLineInputSize.height); // But now it will... but it will max at four. await tester.pumpWidget(selectableTextBuilder(text: kMoreThanFourLines, maxLines: 4)); expect(findTextBox(), equals(textBox)); expect(textBox.size.height, greaterThan(threeLineInputSize.height)); final Size fourLineInputSize = textBox.size; // Now it won't max out until the end. await tester.pumpWidget(selectableTextBuilder(maxLines: null)); expect(findTextBox(), equals(textBox)); expect(textBox.size, equals(emptyInputSize)); await tester.pumpWidget(selectableTextBuilder(text: kThreeLines, maxLines: null)); expect(textBox.size.height, equals(threeLineInputSize.height)); await tester.pumpWidget(selectableTextBuilder(text: kMoreThanFourLines, maxLines: null)); expect(textBox.size.height, greaterThan(fourLineInputSize.height)); }); testWidgets('Can drag handles to change selection in multiline', (WidgetTester tester) async { const String testValue = kThreeLines; await tester.pumpWidget( overlay( child: const SelectableText( testValue, dragStartBehavior: DragStartBehavior.down, style: TextStyle(color: Colors.black, fontSize: 34.0), maxLines: 3, ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; // Check that the text spans multiple lines. final Offset firstPos = textOffsetToPosition(tester, testValue.indexOf('First')); final Offset secondPos = textOffsetToPosition(tester, testValue.indexOf('Second')); final Offset thirdPos = textOffsetToPosition(tester, testValue.indexOf('Third')); final Offset middleStringPos = textOffsetToPosition(tester, testValue.indexOf('irst')); expect(firstPos.dx, 24.5); expect(secondPos.dx, 24.5); expect(thirdPos.dx, 24.5); expect(middleStringPos.dx, 58.5); expect(firstPos.dx, secondPos.dx); expect(firstPos.dx, thirdPos.dx); expect(firstPos.dy, lessThan(secondPos.dy)); expect(secondPos.dy, lessThan(thirdPos.dy)); // Long press the 'n' in 'until' to select the word. final Offset untilPos = textOffsetToPosition(tester, testValue.indexOf('until')+1); TestGesture gesture = await tester.startGesture(untilPos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero expect(controller.selection.baseOffset, 39); expect(controller.selection.extentOffset, 44); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle to the third line, just after 'Third'. Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); // The distance below the y value returned by textOffsetToPosition required // to register a full vertical line drag. const Offset downLineOffset = Offset(0.0, 3.0); Offset newHandlePos = textOffsetToPosition(tester, testValue.indexOf('Third') + 5) + downLineOffset; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 39, extentOffset: 50, ), ); // Drag the left handle to the first line, just after 'First'. handlePos = endpoints[0].point + const Offset(-1.0, 1.0); newHandlePos = textOffsetToPosition(tester, testValue.indexOf('First') + 5); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 50); await tester.tap(find.text('Copy')); await tester.pump(); expect(controller.selection.isCollapsed, true); }); testWidgets('Can scroll multiline input', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText( kMoreThanFourLines, dragStartBehavior: DragStartBehavior.down, style: TextStyle(color: Colors.black, fontSize: 34.0), maxLines: 2, ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; RenderBox findInputBox() => tester.renderObject(find.byType(SelectableText)); final RenderBox inputBox = findInputBox(); // Check that the last line of text is not displayed. final Offset firstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); final Offset fourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(firstPos.dx, 0.0); expect(fourthPos.dx, 0.0); expect(firstPos.dx, fourthPos.dx); expect(firstPos.dy, lessThan(fourthPos.dy)); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(firstPos)), isTrue); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(fourthPos)), isFalse); TestGesture gesture = await tester.startGesture(firstPos, pointer: 7); await tester.pump(); await gesture.moveBy(const Offset(0.0, -1000.0)); await tester.pump(const Duration(seconds: 1)); // Wait and drag again to trigger https://github.com/flutter/flutter/issues/6329 // (No idea why this is necessary, but the bug wouldn't repro without it.) await gesture.moveBy(const Offset(0.0, -1000.0)); await tester.pump(const Duration(seconds: 1)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); // Now the first line is scrolled up, and the fourth line is visible. Offset newFirstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); Offset newFourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(newFirstPos.dy, lessThan(firstPos.dy)); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFirstPos)), isFalse); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), isTrue); // Now try scrolling by dragging the selection handle. // Long press the middle of the word "won't" in the fourth line. final Offset selectedWordPos = textOffsetToPosition( tester, kMoreThanFourLines.indexOf('Fourth line') + 14, ); gesture = await tester.startGesture(selectedWordPos, pointer: 7); await tester.pump(const Duration(seconds: 1)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.selection.base.offset, 77); expect(controller.selection.extent.offset, 82); // Sanity check for the word selected is the intended one. expect( controller.text.substring(controller.selection.baseOffset, controller.selection.extentOffset), "won't", ); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.length, 2); // Drag the left handle to the first line, just after 'First'. final Offset handlePos = endpoints[0].point + const Offset(-1, 1); final Offset newHandlePos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First') + 5); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(const Duration(seconds: 1)); await gesture.moveTo(newHandlePos + const Offset(0.0, -10.0)); await tester.pump(const Duration(seconds: 1)); await gesture.up(); await tester.pump(const Duration(seconds: 1)); // The text should have scrolled up with the handle to keep the active // cursor visible, back to its original position. newFirstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); newFourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(newFirstPos.dy, firstPos.dy); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFirstPos)), isTrue); expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), isFalse); }); testWidgets('minLines cannot be greater than maxLines', (WidgetTester tester) async { expect( () async { await tester.pumpWidget( overlay( child: SizedBox( width: 300.0, child: SelectableText( 'abcd', minLines: 4, maxLines: 3, ), ), ), ); }, throwsA(isA<AssertionError>().having( (AssertionError error) => error.toString(), '.toString()', contains("minLines can't be greater than maxLines"), )), ); }); testWidgets('Selectable height with minLine', (WidgetTester tester) async { await tester.pumpWidget(selectableTextBuilder()); RenderBox findTextBox() => tester.renderObject(find.byType(SelectableText)); final RenderBox textBox = findTextBox(); final Size emptyInputSize = textBox.size; // Even if the text is a one liner, minimum height of SelectableText will determined by minLines. await tester.pumpWidget(selectableTextBuilder(text: 'No wrapping here.', minLines: 2, maxLines: 3)); expect(findTextBox(), equals(textBox)); expect(textBox.size.height, emptyInputSize.height * 2); }); testWidgets('Can align to center', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SizedBox( width: 300.0, child: SelectableText( 'abcd', textAlign: TextAlign.center, ), ), ), ); final RenderEditable editable = findRenderEditable(tester); final Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 2)).topLeft, ); expect(topLeft.dx, equals(399.0)); }); testWidgets('Can align to center within center', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SizedBox( width: 300.0, child: Center( child: SelectableText( 'abcd', textAlign: TextAlign.center, ), ), ), ), ); final RenderEditable editable = findRenderEditable(tester); final Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 2)).topLeft, ); expect(topLeft.dx, equals(399.0)); }); testWidgets('Selectable text is skipped during focus traversal', (WidgetTester tester) async { final FocusNode firstFieldFocus = FocusNode(); addTearDown(firstFieldFocus.dispose); final FocusNode lastFieldFocus = FocusNode(); addTearDown(lastFieldFocus.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: Column( children: <Widget>[ TextField( focusNode: firstFieldFocus, autofocus: true, ), const SelectableText('some text'), TextField( focusNode: lastFieldFocus, ), ], ), ), ), ), ); await tester.pump(); expect(firstFieldFocus.hasFocus, isTrue); expect(lastFieldFocus.hasFocus, isFalse); firstFieldFocus.nextFocus(); await tester.pump(); // Expecting focus to skip straight to the second field. expect(firstFieldFocus.hasFocus, isFalse); expect(lastFieldFocus.hasFocus, isTrue); }); testWidgets('Selectable text identifies as text field in semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('some text'), ), ), ), ); expect( semantics, includesNodeWith( flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isReadOnly, SemanticsFlag.isMultiline, ], ), ); semantics.dispose(); }); testWidgets('Selectable text rich text with spell out in semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText.rich(TextSpan(text: 'some text', spellOut: true)), ), ), ), ); expect( semantics, includesNodeWith( attributedValue: AttributedString( 'some text', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end:9)), ], ), flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isReadOnly, SemanticsFlag.isMultiline, ], ), ); semantics.dispose(); }); testWidgets('Selectable text rich text with locale in semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText.rich(TextSpan(text: 'some text', locale: Locale('es', 'MX'))), ), ), ), ); expect( semantics, includesNodeWith( attributedValue: AttributedString( 'some text', attributes: <StringAttribute>[ LocaleStringAttribute(range: const TextRange(start: 0, end:9), locale: const Locale('es', 'MX')), ], ), flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isReadOnly, SemanticsFlag.isMultiline, ], ), ); semantics.dispose(); }); testWidgets('Selectable rich text with gesture recognizer has correct semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); await tester.pumpWidget( overlay( child: SelectableText.rich( TextSpan( children: <TextSpan>[ const TextSpan(text: 'text'), TextSpan( text: 'link', recognizer: recognizer..onTap = () { }, ), ], ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, actions: <SemanticsAction>[SemanticsAction.longPress], textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, label: 'text', textDirection: TextDirection.ltr, ), TestSemantics( id: 4, flags: <SemanticsFlag>[SemanticsFlag.isLink], actions: <SemanticsAction>[SemanticsAction.tap], label: 'link', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); group('Keyboard Tests', () { late TextEditingController controller; Future<void> setupWidget(WidgetTester tester, String text) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: RawKeyboardListener( focusNode: focusNode, child: SelectableText( text, maxLines: 3, ), ), ), ), ); await tester.tap(find.byType(SelectableText)); await tester.pumpAndSettle(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); controller = editableTextWidget.controller; } testWidgets('Shift test 1', (WidgetTester tester) async { await setupWidget(tester, 'a big house'); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowLeft); expect(controller.selection.extentOffset - controller.selection.baseOffset, -1); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Shift test 2', (WidgetTester tester) async { await setupWidget(tester, 'abcdefghi'); controller.selection = const TextSelection.collapsed(offset: 3); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 1); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Control Shift test', (WidgetTester tester) async { await setupWidget(tester, 'their big house'); await tester.sendKeyDownEvent(LogicalKeyboardKey.control); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, -5); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Down and up test', (WidgetTester tester) async { await setupWidget(tester, 'a big house'); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, -11); await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 0); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Down and up test 2', (WidgetTester tester) async { await setupWidget(tester, 'a big house\njumped over a mouse\nOne more line yay'); controller.selection = const TextSelection.collapsed(offset: 0); await tester.pump(); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); } await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 12); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 32); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 12); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, -5); }, variant: KeySimulatorTransitModeVariant.all()); }); testWidgets('Copy test', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); String clipboardContent = ''; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'Clipboard.setData') { clipboardContent = (methodCall.arguments as Map<String, dynamic>)['text'] as String; } else if (methodCall.method == 'Clipboard.getData') { return <String, dynamic>{'text': clipboardContent}; } return null; }); const String testValue = 'a big house\njumped over a mouse'; await tester.pumpWidget( MaterialApp( home: Material( child: RawKeyboardListener( focusNode: focusNode, child: const SelectableText( testValue, maxLines: 3, ), ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; focusNode.requestFocus(); await tester.pump(); await tester.tap(find.byType(SelectableText)); await tester.pumpAndSettle(); controller.selection = const TextSelection.collapsed(offset: 0); await tester.pump(); // Select the first 5 characters. await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); // Copy them. await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); await tester.pumpAndSettle(); expect(clipboardContent, 'a big'); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Select all test', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const String testValue = 'a big house\njumped over a mouse'; await tester.pumpWidget( MaterialApp( home: Material( child: RawKeyboardListener( focusNode: focusNode, child: const SelectableText( testValue, maxLines: 3, ), ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; focusNode.requestFocus(); await tester.pump(); await tester.tap(find.byType(SelectableText)); await tester.pumpAndSettle(); // Select All. await tester.sendKeyDownEvent(LogicalKeyboardKey.control); await tester.sendKeyEvent(LogicalKeyboardKey.keyA); await tester.sendKeyUpEvent(LogicalKeyboardKey.control); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 31); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('keyboard selection should call onSelectionChanged', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); TextSelection? newSelection; const String testValue = 'a big house\njumped over a mouse'; await tester.pumpWidget( MaterialApp( home: Material( child: RawKeyboardListener( focusNode: focusNode, child: SelectableText( testValue, maxLines: 3, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { expect(newSelection, isNull); newSelection = selection; }, ), ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; focusNode.requestFocus(); await tester.pump(); await tester.tap(find.byType(SelectableText)); await tester.pumpAndSettle(); expect(newSelection!.baseOffset, 31); expect(newSelection!.extentOffset, 31); newSelection = null; controller.selection = const TextSelection.collapsed(offset: 0); await tester.pump(); // Select the first 5 characters. await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); expect(newSelection!.baseOffset, 0); expect(newSelection!.extentOffset, i + 1); newSelection = null; } }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Changing positions of selectable text', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final List<KeyEvent> events = <KeyEvent>[]; final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SelectableText( 'a big house', key: key1, maxLines: 3, ), SelectableText( 'another big house', key: key2, maxLines: 3, ), ], ), ), ), ), ); EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); TextEditingController c1 = editableTextWidget.controller; await tester.tap(find.byType(EditableText).first); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(c1.selection.extentOffset - c1.selection.baseOffset, -5); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SelectableText( 'another big house', key: key2, maxLines: 3, ), SelectableText( 'a big house', key: key1, maxLines: 3, ), ], ), ), ), ), ); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); editableTextWidget = tester.widget(find.byType(EditableText).last); c1 = editableTextWidget.controller; expect(c1.selection.extentOffset - c1.selection.baseOffset, -10); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Changing focus test', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final List<KeyEvent> events = <KeyEvent>[]; final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SelectableText( 'a big house', key: key1, maxLines: 3, ), SelectableText( 'another big house', key: key2, maxLines: 3, ), ], ), ), ), ), ); final EditableText editableTextWidget1 = tester.widget(find.byType(EditableText).first); final TextEditingController c1 = editableTextWidget1.controller; final EditableText editableTextWidget2 = tester.widget(find.byType(EditableText).last); final TextEditingController c2 = editableTextWidget2.controller; await tester.tap(find.byType(SelectableText).first); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(c1.selection.extentOffset - c1.selection.baseOffset, -5); expect(c2.selection.extentOffset - c2.selection.baseOffset, 0); await tester.tap(find.byType(SelectableText).last); await tester.pumpAndSettle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); for (int i = 0; i < 5; i += 1) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); } await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await tester.pumpAndSettle(); expect(c1.selection.extentOffset - c1.selection.baseOffset, -5); expect(c2.selection.extentOffset - c2.selection.baseOffset, -5); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Caret works when maxLines is null', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SelectableText( 'x', ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect(controller.selection.baseOffset, -1); // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is // Confirm that the selection was updated. expect(controller.selection.baseOffset, 0); }); testWidgets('SelectableText baseline alignment no-strut', (WidgetTester tester) async { final Key keyA = UniqueKey(); final Key keyB = UniqueKey(); await tester.pumpWidget( overlay( child: Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Expanded( child: SelectableText( 'A', key: keyA, style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 10.0), strutStyle: StrutStyle.disabled, ), ), const Text( 'abc', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 20.0), ), Expanded( child: SelectableText( 'B', key: keyB, style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 30.0), strutStyle: StrutStyle.disabled, ), ), ], ), ), ); // The test font extends 0.25 * fontSize below the baseline. // So the three row elements line up like this: // // A abc B // ------------- baseline // 2.5 5 7.5 space below the baseline = 0.25 * fontSize // ------------- rowBottomY final double rowBottomY = tester.getBottomLeft(find.byType(Row)).dy; expect(tester.getBottomLeft(find.byKey(keyA)).dy, rowBottomY - 5.0); expect(tester.getBottomLeft(find.text('abc')).dy, rowBottomY - 2.5); expect(tester.getBottomLeft(find.byKey(keyB)).dy, rowBottomY); }); testWidgets('SelectableText baseline alignment', (WidgetTester tester) async { final Key keyA = UniqueKey(); final Key keyB = UniqueKey(); await tester.pumpWidget( overlay( child: Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Expanded( child: SelectableText( 'A', key: keyA, style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 10.0), ), ), const Text( 'abc', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 20.0), ), Expanded( child: SelectableText( 'B', key: keyB, style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 30.0), ), ), ], ), ), ); // The test font extends 0.25 * fontSize below the baseline. // So the three row elements line up like this: // // A abc B // ------------- baseline // 2.5 5 7.5 space below the baseline = 0.25 * fontSize // ------------- rowBottomY final double rowBottomY = tester.getBottomLeft(find.byType(Row)).dy; expect(tester.getBottomLeft(find.byKey(keyA)).dy, rowBottomY - 5.0); expect(tester.getBottomLeft(find.text('abc')).dy, rowBottomY - 2.5); expect(tester.getBottomLeft(find.byKey(keyB)).dy, rowBottomY); }); testWidgets('SelectableText semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: SelectableText( 'Guten Tag', key: key, ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, value: 'Guten Tag', actions: <SemanticsAction>[ SemanticsAction.longPress, ], flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.isReadOnly, SemanticsFlag.isMultiline, ], ), ], ), ignoreTransform: true, ignoreRect: true)); await tester.tap(find.byKey(key)); await tester.pump(); controller.selection = const TextSelection.collapsed(offset: 9); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, value: 'Guten Tag', textSelection: const TextSelection.collapsed(offset: 9), actions: <SemanticsAction>[ SemanticsAction.longPress, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); controller.selection = const TextSelection.collapsed(offset: 4); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, textSelection: const TextSelection.collapsed(offset: 4), value: 'Guten Tag', actions: <SemanticsAction>[ SemanticsAction.longPress, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, SemanticsAction.setSelection, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); controller.selection = const TextSelection.collapsed(offset: 0); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, textDirection: TextDirection.ltr, textSelection: const TextSelection.collapsed(offset: 0), value: 'Guten Tag', actions: <SemanticsAction>[ SemanticsAction.longPress, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorForwardByWord, SemanticsAction.setSelection, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('SelectableText semantics, with semanticsLabel', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: SelectableText( 'Guten Tag', semanticsLabel: 'German greeting for good day', key: key, ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, actions: <SemanticsAction>[SemanticsAction.longPress], label: 'German greeting for good day', textDirection: TextDirection.ltr, ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('SelectableText semantics, enableInteractiveSelection = false', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: SelectableText( 'Guten Tag', key: key, enableInteractiveSelection: false, ), ), ); await tester.tap(find.byKey(key)); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, value: 'Guten Tag', textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.longPress, // Absent the following because enableInteractiveSelection: false // SemanticsAction.moveCursorBackwardByCharacter, // SemanticsAction.moveCursorBackwardByWord, // SemanticsAction.setSelection, // SemanticsAction.paste, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, // SelectableText act like a text widget when enableInteractiveSelection // is false. It will not respond to any pointer event. // SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('SelectableText semantics for selections', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: SelectableText( 'Hello', key: key, ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, value: 'Hello', textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.longPress, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, ], ), ], ), ignoreTransform: true, ignoreRect: true)); // Focus the selectable text await tester.tap(find.byKey(key)); await tester.pump(); controller.selection = const TextSelection.collapsed(offset: 5); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, value: 'Hello', textSelection: const TextSelection.collapsed(offset: 5), textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.longPress, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); controller.selection = const TextSelection(baseOffset: 5, extentOffset: 3); await tester.pump(); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, value: 'Hello', textSelection: const TextSelection(baseOffset: 5, extentOffset: 3), textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.longPress, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorForwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.moveCursorForwardByWord, SemanticsAction.setSelection, SemanticsAction.copy, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('semantic nodes of offscreen recognizers are marked hidden', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/100395. final SemanticsTester semantics = SemanticsTester(tester); const TextStyle textStyle = TextStyle(fontSize: 200); const String onScreenText = 'onscreen\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'; const String offScreenText = 'off screen'; final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); await tester.pumpWidget( MaterialApp( home: SingleChildScrollView( controller: controller, child: SelectableText.rich( TextSpan( children: <TextSpan>[ const TextSpan(text: onScreenText), TextSpan( text: offScreenText, recognizer: recognizer..onTap = () { }, ), ], style: textStyle, ), textDirection: TextDirection.ltr, ), ) ), ); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], actions: <SemanticsAction>[SemanticsAction.scrollUp], children: <TestSemantics>[ TestSemantics( actions: <SemanticsAction>[SemanticsAction.longPress], children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( label: 'onscreen\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isHidden, SemanticsFlag.isLink, ], actions: <SemanticsAction>[SemanticsAction.tap], label: 'off screen', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ], ), ], ), ], ); expect( semantics, hasSemantics( expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); // Test shows on screen. expect(controller.offset, 0.0); tester.binding.pipelineOwner.semanticsOwner!.performAction(8, SemanticsAction.showOnScreen); await tester.pumpAndSettle(); expect(controller.offset != 0.0, isTrue); semantics.dispose(); }); testWidgets('SelectableText change selection with semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: SelectableText( 'Hello', key: key, ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // Focus the selectable text. await tester.tap(find.byKey(key)); await tester.pump(); controller.selection = const TextSelection(baseOffset: 5, extentOffset: 5); await tester.pump(); const int inputFieldId = 1; expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: inputFieldId, value: 'Hello', textSelection: const TextSelection.collapsed(offset: 5), textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.longPress, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); // Move cursor back once. semanticsOwner.performAction(inputFieldId, SemanticsAction.setSelection, <dynamic, dynamic>{ 'base': 4, 'extent': 4, }); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 4)); // Move cursor to front. semanticsOwner.performAction(inputFieldId, SemanticsAction.setSelection, <dynamic, dynamic>{ 'base': 0, 'extent': 0, }); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 0)); // Select all. semanticsOwner.performAction(inputFieldId, SemanticsAction.setSelection, <dynamic, dynamic>{ 'base': 0, 'extent': 5, }); await tester.pump(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: inputFieldId, value: 'Hello', textSelection: const TextSelection(baseOffset: 0, extentOffset: 5), textDirection: TextDirection.ltr, actions: <SemanticsAction>[ SemanticsAction.longPress, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, SemanticsAction.copy, ], flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, SemanticsFlag.isFocused, ], ), ], ), ignoreTransform: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('Can activate SelectableText with explicit controller via semantics', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/17801 const String testValue = 'Hello'; final SemanticsTester semantics = SemanticsTester(tester); final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final Key key = UniqueKey(); await tester.pumpWidget( overlay( child: SelectableText( testValue, key: key, ), ), ); const int inputFieldId = 1; expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: inputFieldId, flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, ], actions: <SemanticsAction>[SemanticsAction.longPress], value: testValue, textDirection: TextDirection.ltr, ), ], ), ignoreRect: true, ignoreTransform: true, )); semanticsOwner.performAction(inputFieldId, SemanticsAction.longPress); await tester.pump(); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: inputFieldId, flags: <SemanticsFlag>[ SemanticsFlag.isReadOnly, SemanticsFlag.isTextField, SemanticsFlag.isMultiline, SemanticsFlag.isFocused, ], actions: <SemanticsAction>[ SemanticsAction.longPress, SemanticsAction.moveCursorBackwardByCharacter, SemanticsAction.moveCursorBackwardByWord, SemanticsAction.setSelection, ], value: testValue, textDirection: TextDirection.ltr, textSelection: const TextSelection( baseOffset: testValue.length, extentOffset: testValue.length, ), ), ], ), ignoreRect: true, ignoreTransform: true, )); semantics.dispose(); }); testWidgets('onTap is called upon tap', (WidgetTester tester) async { int tapCount = 0; await tester.pumpWidget( overlay( child: SelectableText( 'something', onTap: () { tapCount += 1; }, ), ), ); expect(tapCount, 0); await tester.tap(find.byType(SelectableText)); // Wait a bit so they're all single taps and not double taps. await tester.pump(const Duration(milliseconds: 300)); await tester.tap(find.byType(SelectableText)); await tester.pump(const Duration(milliseconds: 300)); await tester.tap(find.byType(SelectableText)); await tester.pump(const Duration(milliseconds: 300)); expect(tapCount, 3); }); testWidgets('SelectableText style is merged with default text style', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/23994 final TextStyle defaultStyle = TextStyle( color: Colors.blue[500], ); Widget buildFrame(TextStyle style) { return MaterialApp( home: Material( child: DefaultTextStyle ( style: defaultStyle, child: Center( child: SelectableText( 'something', style: style, ), ), ), ), ); } // Empty TextStyle is overridden by theme. await tester.pumpWidget(buildFrame(const TextStyle())); EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, defaultStyle.color); expect(editableText.style.background, defaultStyle.background); expect(editableText.style.shadows, defaultStyle.shadows); expect(editableText.style.decoration, defaultStyle.decoration); expect(editableText.style.locale, defaultStyle.locale); expect(editableText.style.wordSpacing, defaultStyle.wordSpacing); // Properties set on TextStyle override theme. const Color setColor = Colors.red; await tester.pumpWidget(buildFrame(const TextStyle(color: setColor))); editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, setColor); // inherit: false causes nothing to be merged in from theme. await tester.pumpWidget(buildFrame(const TextStyle( fontSize: 24.0, textBaseline: TextBaseline.alphabetic, inherit: false, ))); editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, isNull); }); testWidgets('style enforces required fields', (WidgetTester tester) async { Widget buildFrame(TextStyle style) { return MaterialApp( home: Material( child: SelectableText( 'something', style: style, ), ), ); } await tester.pumpWidget(buildFrame(const TextStyle( inherit: false, fontSize: 12.0, textBaseline: TextBaseline.alphabetic, ))); expect(tester.takeException(), isNull); // With inherit not set to false, will pickup required fields from theme. await tester.pumpWidget(buildFrame(const TextStyle( fontSize: 12.0, ))); expect(tester.takeException(), isNull); await tester.pumpWidget(buildFrame(const TextStyle( inherit: false, fontSize: 12.0, ))); expect(tester.takeException(), isNotNull); }); testWidgets( 'tap moves cursor to the edge of the word it tapped', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // We moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); // But don't trigger the toolbar. expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'tap moves cursor to the position tapped (Android)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // We moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 4, affinity: TextAffinity.upstream), ); // But don't trigger the toolbar. expect(find.byType(TextButton), findsNothing); }, ); testWidgets( 'two slow taps do not trigger a word selection', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // Plain collapsed selection. expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); // No toolbar. expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'double tap selects word and first tap of double tap moves cursor', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(); // Second tap selects the word around the cursor. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'double tap selects word and first tap of double tap moves cursor and shows toolbar (Android)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(); // Second tap selects the word around the cursor. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectMaterialSelectionToolbar(); }, ); testWidgets( 'double tap on top of cursor also selects word (Android)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); // Tap to put the cursor after the "w". const int index = 3; await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect( controller.selection, const TextSelection.collapsed(offset: index), ); // Double tap on the same location. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); // First tap doesn't change the selection. expect( controller.selection, const TextSelection.collapsed(offset: index), ); // Second tap selects the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectMaterialSelectionToolbar(); }, ); testWidgets( 'double tap hold selects word', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(150.0, 5.0)); // Hold the press. await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoSelectionToolbar(); await gesture.up(); await tester.pump(); // Still selected. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // The toolbar is still showing. expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'double tap selects word with semantics label', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText.rich( TextSpan(text: 'Atwater Peel Sherbrooke Bonaventure', semanticsLabel: ''), ), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(220.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(selectableTextStart + const Offset(220.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect( controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'tap after a double tap select is not affected (iOS)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(selectableTextStart + const Offset(100.0, 5.0)); await tester.pump(); // Plain collapsed selection at the edge of first word. In iOS 12, the // first tap after a double tap ends up putting the cursor at where // you tapped instead of the edge like every other single tap. This is // likely a bug in iOS 12 and not present in other versions. expect( controller.selection, const TextSelection.collapsed(offset: 7), ); // No toolbar. expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press selects word and shows toolbar (iOS)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // The long pressed word is selected. expect( controller.selection, const TextSelection( baseOffset: 0, extentOffset: 7, ), ); expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press selects word and shows toolbar (Android)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectMaterialSelectionToolbar(); }, ); testWidgets( 'long press selects word and shows custom toolbar (Cupertino)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure', selectionControls: cupertinoTextSelectionControls, ), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // The long pressed word is selected. expect( controller.selection, const TextSelection( baseOffset: 0, extentOffset: 7, ), ); // Toolbar shows one button (copy). expect(find.byType(CupertinoButton), findsNWidgets(1)); expect(find.text('Copy'), findsOneWidget); }, variant: TargetPlatformVariant.all(), ); testWidgets( 'long press selects word and shows custom toolbar (Material)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure', selectionControls: materialTextSelectionControls, ), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); // Collapsed toolbar shows 2 buttons: copy, select all expect(find.byType(TextButton), findsNWidgets(2)); expect(find.text('Copy'), findsOneWidget); expect(find.text('Select all'), findsOneWidget); }, variant: TargetPlatformVariant.all(), ); testWidgets( 'textSelectionControls is passed to EditableText', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Scaffold( body: SelectableText('Atwater Peel Sherbrooke Bonaventure', selectionControls: materialTextSelectionControls, ), ), ), ), ); final EditableText widget = tester.widget(find.byType(EditableText)); expect(widget.selectionControls, equals(materialTextSelectionControls)); }, ); testWidgets( 'long press tap cannot initiate a double tap', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); // Hide the toolbar so it doesn't interfere with taps on the text. final EditableTextState editableTextState = tester.state<EditableTextState>(find.byType(EditableText)); editableTextState.hideToolbar(); await tester.pumpAndSettle(); await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // We ended up moving the cursor to the edge of the same word and dismissed // the toolbar. expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press drag extends the selection to the word under the drag and shows toolbar on lift on non-Apple platforms', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 18)); await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // Long press selects the word at the long presses position. expect( controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23), ); // Cursor move doesn't trigger a toolbar initially. expect(find.byType(TextButton), findsNothing); await gesture.moveBy(const Offset(100, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection(baseOffset: 13, extentOffset: 35), ); // Still no toolbar. expect(find.byType(TextButton), findsNothing); // The selection is moved on a backwards drag. await gesture.moveBy(const Offset(-200, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection(baseOffset: 23, extentOffset: 8), ); // Still no toolbar. expect(find.byType(TextButton), findsNothing); await gesture.moveBy(const Offset(-100, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection(baseOffset: 23, extentOffset: 0), ); // Still no toolbar. expect(find.byType(TextButton), findsNothing); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection(baseOffset: 23, extentOffset: 0), ); expectMaterialSelectionToolbar(); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press drag extends the selection to the word under the drag and shows toolbar on lift (iOS)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 18)); await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // The long pressed word is selected. expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 23, ), ); // Word select doesn't trigger a toolbar initially. expect(find.byType(CupertinoButton), findsNothing); await gesture.moveBy(const Offset(100, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 35, ), ); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); // The selection is moved with a backwards drag. await gesture.moveBy(const Offset(-200, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection( baseOffset: 23, extentOffset: 8, ), ); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); // The selection is moved with a backwards drag. await gesture.moveBy(const Offset(-100, 0)); await tester.pump(); // The selection is now moved with the drag. expect( controller.selection, const TextSelection( baseOffset: 23, extentOffset: 0, ), ); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); await gesture.up(); await tester.pump(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection( baseOffset: 23, extentOffset: 0, ), ); // The toolbar now shows up. expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'long press drag moves the cursor under the drag and shows toolbar on lift (macOS)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // The long pressed word is selected. expect( controller.selection, const TextSelection( baseOffset: 0, extentOffset: 7, ), ); // Cursor move doesn't trigger a toolbar initially. expect(find.byType(CupertinoButton), findsNothing); await gesture.moveBy(const Offset(50, 0)); await tester.pump(); // The selection position is now moved with the drag. expect( controller.selection, const TextSelection( baseOffset: 0, extentOffset: 8, ), ); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); await gesture.moveBy(const Offset(50, 0)); await tester.pump(); // The selection position is now moved with the drag. expect( controller.selection, const TextSelection( baseOffset: 0, extentOffset: 12, ), ); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); await gesture.up(); await tester.pump(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection( baseOffset: 0, extentOffset: 12, ), ); // The toolbar now shows up. expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }), ); testWidgets('long press drag can edge scroll when inside a scrollable', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/129590. await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: SizedBox( width: 300.0, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: SelectableText( 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges ' * 2, maxLines: 1, ), ), ), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(200.0, 0.0)); await tester.pump(kLongPressTimeout); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect( controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23), ); await gesture.moveBy(const Offset(100, 0)); // To the edge of the screen basically. await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 23, ), ); // Keep moving out. await gesture.moveBy(const Offset(100, 0)); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 35, ), ); await gesture.moveBy(const Offset(1600, 0)); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 134, ), ); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 134, ), ); // The toolbar shows up. if (defaultTargetPlatform == TargetPlatform.iOS) { expectCupertinoSelectionToolbar(); } else { expectMaterialSelectionToolbar(); } final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.isNotEmpty, isTrue); expect(endpoints.length, 2); expect(endpoints[0].point.dx, isNegative); expect(endpoints[1].point.dx, isPositive); }, // TODO(Renzo-Olivares): Add in TargetPlatform.android in the line below when // we fix edge scrolling in a Scrollable https://github.com/flutter/flutter/issues/64059. variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Desktop mouse drag can edge scroll when inside a horizontal scrollable', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/129590. await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: SizedBox( width: 300.0, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: SelectableText( 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges ' * 2, maxLines: 1, ), ), ), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(200.0, 0.0)); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; await gesture.moveBy(const Offset(100, 0)); // To the edge of the screen basically. await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 14, extentOffset: 21, ), ); // Keep moving out. await gesture.moveBy(const Offset(100, 0)); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 14, extentOffset: 28, ), ); await gesture.moveBy(const Offset(1600, 0)); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 14, extentOffset: 134, ), ); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection( baseOffset: 14, extentOffset: 134, ), ); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.isNotEmpty, isTrue); expect(endpoints.length, 2); expect(endpoints[0].point.dx, isNegative); expect(endpoints[1].point.dx, isPositive); }, variant: TargetPlatformVariant.desktop(), ); testWidgets('long press drag can edge scroll', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: SelectableText( 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges ' * 2, maxLines: 1, ), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(300, 5)); await tester.pump(kLongPressTimeout); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect( controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23), ); await gesture.moveBy(const Offset(300, 0)); // To the edge of the screen basically. await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 45, ), ); // Keep moving out. await gesture.moveBy(const Offset(300, 0)); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 66, ), ); await gesture.moveBy(const Offset(400, 0)); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 102, ), ); await gesture.moveBy(const Offset(700, 0)); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 134, ), ); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection( baseOffset: 13, extentOffset: 134, ), ); // The toolbar shows up. if (defaultTargetPlatform == TargetPlatform.iOS) { expectCupertinoSelectionToolbar(); } else { expectMaterialSelectionToolbar(); } // Find the selection handle fade transition after the start handle has been // hidden because it is out of view. final List<FadeTransition> transitionsAfter = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitionsAfter.length, 2); final FadeTransition startHandleAfter = transitionsAfter[0]; final FadeTransition endHandleAfter = transitionsAfter[1]; expect(startHandleAfter.opacity.value, 0.0); expect(endHandleAfter.opacity.value, 1.0); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), ); testWidgets( 'long tap still selects after a double tap select (iOS)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // First tap moved the cursor to the beginning of the second word. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); await tester.longPressAt(selectableTextStart + const Offset(100.0, 5.0)); await tester.pump(); // Selected the "word" where the tap happened, which is the first space. // Because the "word" is a whitespace, the selection will shift to the // previous "word" that is not a whitespace. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'long tap still selects after a double tap select (macOS)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // First tap moved the cursor to the beginning of the second word. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); await tester.longPressAt(selectableTextStart + const Offset(100.0, 5.0)); await tester.pump(); // Selected the "word" where the tap happened, which is the first space. expect( controller.selection, const TextSelection(baseOffset: 7, extentOffset: 8), ); // The toolbar shows up. expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }), ); //convert testWidgets( 'double tap after a long tap is not affected', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); // Hide the toolbar so it doesn't interfere with taps on the text. final EditableTextState editableTextState = tester.state<EditableTextState>(find.byType(EditableText)); editableTextState.hideToolbar(); await tester.pumpAndSettle(); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(); // Double tap selection. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'double tap chains work', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoSelectionToolbar(); // Double tap selecting the same word somewhere else is fine. await tester.pumpAndSettle(kDoubleTapTimeout); await tester.tapAt(selectableTextStart + const Offset(10.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(10.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoSelectionToolbar(); // Hide the toolbar so it doesn't interfere with taps on the text. final EditableTextState editableTextState = tester.state<EditableTextState>(find.byType(EditableText)); editableTextState.hideToolbar(); await tester.pumpAndSettle(); await tester.pumpAndSettle(kDoubleTapTimeout); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('force press does not select a word on (android)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ); final Offset offset = tester.getTopLeft(find.byType(SelectableText)) + const Offset(150.0, 5.0); final int pointerValue = tester.nextPointer; final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( offset, PointerDownEvent( pointer: pointerValue, position: offset, pressure: 0.0, pressureMax: 6.0, pressureMin: 0.0, ), ); await gesture.updateWithCustomEvent(PointerMoveEvent(pointer: pointerValue, position: offset + const Offset(150.0, 5.0), pressure: 0.5, pressureMin: 0)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // We don't want this gesture to select any word on Android. expect(controller.selection, const TextSelection.collapsed(offset: -1)); await gesture.up(); await tester.pump(); expect(find.byType(TextButton), findsNothing); }); testWidgets('force press selects word', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); final int pointerValue = tester.nextPointer; final Offset offset = selectableTextStart + const Offset(150.0, 5.0); final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( offset, PointerDownEvent( pointer: pointerValue, position: offset, pressure: 0.0, pressureMax: 6.0, pressureMin: 0.0, ), ); await gesture.updateWithCustomEvent(PointerMoveEvent(pointer: pointerValue, position: selectableTextStart + const Offset(150.0, 5.0), pressure: 0.5, pressureMin: 0)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // We expect the force press to select a word at the given location. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); await gesture.up(); await tester.pump(); expectCupertinoSelectionToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets('tap on non-force-press-supported devices work', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); final int pointerValue = tester.nextPointer; final Offset offset = selectableTextStart + const Offset(150.0, 5.0); final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( offset, PointerDownEvent( pointer: pointerValue, position: offset, // iPhone 6 and below report 0 across the board. pressure: 0, pressureMax: 0, pressureMin: 0, ), ); await gesture.updateWithCustomEvent(PointerMoveEvent(pointer: pointerValue, position: selectableTextStart + const Offset(150.0, 5.0), pressure: 0.5, pressureMin: 0)); await gesture.up(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // The event should fallback to a normal tap and move the cursor. // Single taps selects the edge of the word. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); await tester.pump(); // Single taps shouldn't trigger the toolbar. expect(find.byType(CupertinoButton), findsNothing); // TODO(gspencergoog): Add in TargetPlatform.macOS in the line below when we // figure out what global state is leaking. // https://github.com/flutter/flutter/issues/43445 }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets('default SelectableText debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const SelectableText('something').debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>['data: something']); }); testWidgets('SelectableText implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); // Not checking controller, inputFormatters, focusNode. const SelectableText( 'something', style: TextStyle(color: Color(0xff00ff00)), textAlign: TextAlign.end, textDirection: TextDirection.ltr, textScaler: TextScaler.noScaling, autofocus: true, showCursor: true, minLines: 2, maxLines: 10, cursorWidth: 1.0, cursorHeight: 1.0, cursorRadius: Radius.zero, cursorColor: Color(0xff00ff00), scrollPhysics: ClampingScrollPhysics(), semanticsLabel: 'something else', enableInteractiveSelection: false, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>[ 'data: something', 'semanticsLabel: something else', 'style: TextStyle(inherit: true, color: Color(0xff00ff00))', 'autofocus: true', 'showCursor: true', 'minLines: 2', 'maxLines: 10', 'textAlign: end', 'textDirection: ltr', 'textScaler: no scaling', 'cursorWidth: 1.0', 'cursorHeight: 1.0', 'cursorRadius: Radius.circular(0.0)', 'cursorColor: Color(0xff00ff00)', 'selection disabled', 'scrollPhysics: ClampingScrollPhysics', ]); }); testWidgets( 'strut basic single line', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: SelectableText('something'), ), ), ), ); expect( tester.getSize(find.byType(SelectableText)), // This is the height of the decoration (24) plus the metrics from the default // TextStyle of the theme (16). const Size(129.0, 14.0), ); }, ); testWidgets( 'strut TextStyle increases height', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: SelectableText( 'something', style: TextStyle(fontSize: 20), ), ), ), ), ); expect( tester.getSize(find.byType(SelectableText)), // Strut should inherit the TextStyle.fontSize by default and produce the // same height as if it were disabled. const Size(183.0, 20.0), ); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: SelectableText( 'something', style: TextStyle(fontSize: 20), strutStyle: StrutStyle.disabled, ), ), ), ), ); expect( tester.getSize(find.byType(SelectableText)), // The height here should match the previous version with strut enabled. const Size(183.0, 20.0), ); }, ); testWidgets( 'strut basic multi line', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: SelectableText( 'something', maxLines: 6, ), ), ), ), ); expect( tester.getSize(find.byType(SelectableText)), const Size(129.0, 84.0), ); }, ); testWidgets( 'strut no force small strut', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: SelectableText( 'something', maxLines: 6, strutStyle: StrutStyle( // The small strut is overtaken by the larger // TextStyle fontSize. fontSize: 5, ), ), ), ), ), ); expect( tester.getSize(find.byType(SelectableText)), // When the strut's height is smaller than TextStyle's and forceStrutHeight // is disabled, then the TextStyle takes precedence. Should be the same height // as 'strut basic multi line'. const Size(129.0, 84.0), ); }, ); testWidgets( 'strut no force large strut', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: SelectableText( 'something', maxLines: 6, strutStyle: StrutStyle( fontSize: 25, ), ), ), ), ), ); expect( tester.getSize(find.byType(SelectableText)), // When the strut's height is larger than TextStyle's and forceStrutHeight // is disabled, then the StrutStyle takes precedence. const Size(129.0, 150.0), ); }, ); testWidgets( 'strut height override', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: SelectableText( 'something', maxLines: 3, strutStyle: StrutStyle( fontSize: 8, forceStrutHeight: true, ), ), ), ), ), ); expect( tester.getSize(find.byType(SelectableText)), // The smaller font size of strut make the field shorter than normal. const Size(129.0, 24.0), ); }, ); testWidgets( 'strut forces field taller', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), home: const Material( child: Center( child: SelectableText( 'something', maxLines: 3, style: TextStyle(fontSize: 10), strutStyle: StrutStyle( fontSize: 18, forceStrutHeight: true, ), ), ), ), ), ); expect( tester.getSize(find.byType(SelectableText)), // When the strut fontSize is larger than a provided TextStyle, the // strut's height takes precedence. const Size(93.0, 54.0), ); }, ); testWidgets('Caret center position', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SizedBox( width: 300.0, child: SelectableText( 'abcd', textAlign: TextAlign.center, ), ), ), ); final RenderEditable editable = findRenderEditable(tester); Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 4)).topLeft, ); expect(topLeft.dx, equals(427)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 3)).topLeft, ); expect(topLeft.dx, equals(413)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 2)).topLeft, ); expect(topLeft.dx, equals(399)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 1)).topLeft, ); expect(topLeft.dx, equals(385)); }); testWidgets('Caret indexes into trailing whitespace center align', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SizedBox( width: 300.0, child: SelectableText( 'abcd ', textAlign: TextAlign.center, ), ), ), ); final RenderEditable editable = findRenderEditable(tester); Offset topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 7)).topLeft, ); expect(topLeft.dx, equals(469)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 8)).topLeft, ); expect(topLeft.dx, equals(483)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 4)).topLeft, ); expect(topLeft.dx, equals(427)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 3)).topLeft, ); expect(topLeft.dx, equals(413)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 2)).topLeft, ); expect(topLeft.dx, equals(399)); topLeft = editable.localToGlobal( editable.getLocalRectForCaret(const TextPosition(offset: 1)).topLeft, ); expect(topLeft.dx, equals(385)); }); testWidgets('selection handles are rendered and not faded away', (WidgetTester tester) async { const String testText = 'lorem ipsum'; await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText(testText), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pumpAndSettle(); final List<FadeTransition> transitions = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0]; final FadeTransition right = transitions[1]; expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); }); testWidgets('selection handles are rendered and not faded away', (WidgetTester tester) async { const String testText = 'lorem ipsum'; await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText(testText), ), ), ); final RenderEditable renderEditable = tester.state<EditableTextState>(find.byType(EditableText)).renderEditable; await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pumpAndSettle(); final List<Widget> transitions = find.byType(FadeTransition).evaluate().map((Element e) => e.widget).toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0] as FadeTransition; final FadeTransition right = transitions[1] as FadeTransition; expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Long press shows handles and toolbar', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('abc def ghi'), ), ), ); // Long press at 'e' in 'def'. final Offset ePos = textOffsetToPosition(tester, 5); await tester.longPressAt(ePos); await tester.pumpAndSettle(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); expect(editableText.selectionOverlay!.toolbarIsVisible, isTrue); }); testWidgets('Double tap shows handles and toolbar', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('abc def ghi'), ), ), ); // Double tap at 'e' in 'def'. final Offset ePos = textOffsetToPosition(tester, 5); await tester.tapAt(ePos); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(ePos); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); expect(editableText.selectionOverlay!.toolbarIsVisible, isTrue); }); testWidgets( 'Mouse tap does not show handles nor toolbar', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('abc def ghi'), ), ), ); // Long press to trigger the selectable text. final Offset ePos = textOffsetToPosition(tester, 5); final TestGesture gesture = await tester.startGesture( ePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); }, ); testWidgets( 'Mouse long press does not show handles nor toolbar', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('abc def ghi'), ), ), ); // Long press to trigger the selectable text. final Offset ePos = textOffsetToPosition(tester, 5); final TestGesture gesture = await tester.startGesture( ePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); }, ); testWidgets( 'Mouse double tap does not show handles nor toolbar', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('abc def ghi'), ), ), ); // Double tap to trigger the selectable text. final Offset selectableTextPos = tester.getCenter(find.byType(SelectableText)); final TestGesture gesture = await tester.startGesture( selectableTextPos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); await tester.pump(); await gesture.down(selectableTextPos); await tester.pump(); await gesture.up(); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); }, ); testWidgets('text span with tap gesture recognizer works in selectable rich text', (WidgetTester tester) async { int spyTaps = 0; final TapGestureRecognizer spyRecognizer = TapGestureRecognizer() ..onTap = () { spyTaps += 1; }; addTearDown(spyRecognizer.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: SelectableText.rich( TextSpan( children: <TextSpan>[ const TextSpan(text: 'Atwater '), TextSpan(text: 'Peel', recognizer: spyRecognizer), const TextSpan(text: ' Sherbrooke Bonaventure'), ], ), ), ), ), ), ); expect(spyTaps, 0); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); expect(spyTaps, 1); // Waits for a while to avoid double taps. await tester.pump(const Duration(seconds: 1)); // Starts a long press. final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // Long press still triggers selection. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // Long press does not trigger gesture recognizer. expect(spyTaps, 1); }); testWidgets('text span with long press gesture recognizer works in selectable rich text', (WidgetTester tester) async { int spyLongPress = 0; final LongPressGestureRecognizer spyRecognizer = LongPressGestureRecognizer() ..onLongPress = () { spyLongPress += 1; }; addTearDown(spyRecognizer.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: SelectableText.rich( TextSpan( children: <TextSpan>[ const TextSpan(text: 'Atwater '), TextSpan(text: 'Peel', recognizer: spyRecognizer), const TextSpan(text: ' Sherbrooke Bonaventure'), ], ), ), ), ), ), ); expect(spyLongPress, 0); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); expect(spyLongPress, 0); // Waits for a while to avoid double taps. await tester.pump(const Duration(seconds: 1)); // Starts a long press. final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // Long press does not trigger selection if there is text span with long // press recognizer. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 11, affinity: TextAffinity.upstream), ); // Long press triggers gesture recognizer. expect(spyLongPress, 1); }); testWidgets('SelectableText changes mouse cursor when hovered', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: SelectableText('test'), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: tester.getCenter(find.text('test'))); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); }); testWidgets('The handles show after pressing Select All', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('abc def ghi'), ), ), ); // Long press at 'e' in 'def'. final Offset ePos = textOffsetToPosition(tester, 5); await tester.longPressAt(ePos); await tester.pumpAndSettle(); expect(find.text('Select all'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); expect(editableText.selectionOverlay!.toolbarIsVisible, isTrue); await tester.tap(find.text('Select all')); await tester.pump(); expect(find.text('Copy'), findsOneWidget); expect(find.text('Select all'), findsNothing); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, }), ); testWidgets('The Select All calls on selection changed', (WidgetTester tester) async { TextSelection? newSelection; await tester.pumpWidget( MaterialApp( home: Material( child: SelectableText( 'abc def ghi', onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { expect(newSelection, isNull); newSelection = selection; }, ), ), ), ); // Long press at 'e' in 'def'. final Offset ePos = textOffsetToPosition(tester, 5); await tester.longPressAt(ePos); await tester.pumpAndSettle(); expect(newSelection!.baseOffset, 4); expect(newSelection!.extentOffset, 7); newSelection = null; await tester.tap(find.text('Select all')); await tester.pump(); expect(newSelection!.baseOffset, 0); expect(newSelection!.extentOffset, 11); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, }), ); testWidgets('The Select All calls on selection changed with a mouse on windows and linux', (WidgetTester tester) async { const String string = 'abc def ghi'; TextSelection? newSelection; await tester.pumpWidget( MaterialApp( home: Material( child: SelectableText( string, onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { expect(newSelection, isNull); newSelection = selection; }, ), ), ), ); // Right-click on the 'e' in 'def'. final Offset ePos = textOffsetToPosition(tester, 5); final TestGesture gesture = await tester.startGesture( ePos, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(newSelection!.isCollapsed, isTrue); expect(newSelection!.baseOffset, 5); newSelection = null; await tester.tap(find.text('Select all')); await tester.pump(); expect(newSelection!.baseOffset, 0); expect(newSelection!.extentOffset, 11); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows, TargetPlatform.linux, }), ); testWidgets('Does not show handles when updated from the web engine', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: SelectableText('abc def ghi'), ), ), ); // Interact with the selectable text to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); final TestGesture gesture = await tester.startGesture( topLeft + const Offset(0.0, 5.0), kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); await tester.pumpAndSettle(); final EditableTextState state = tester.state(find.byType(EditableText)); expect(state.selectionOverlay!.handlesAreVisible, isFalse); expect( state.currentTextEditingValue.selection, const TextSelection.collapsed(offset: 0), ); if (kIsWeb) { tester.testTextInput.updateEditingValue(const TextEditingValue( selection: TextSelection(baseOffset: 2, extentOffset: 7), )); // Wait for all the `setState` calls to be flushed. await tester.pumpAndSettle(); expect( state.currentTextEditingValue.selection, const TextSelection(baseOffset: 2, extentOffset: 7), ); expect(state.selectionOverlay!.handlesAreVisible, isFalse); } }); testWidgets('onSelectionChanged is called when selection changes', (WidgetTester tester) async { int onSelectionChangedCallCount = 0; await tester.pumpWidget( MaterialApp( home: Material( child: SelectableText( 'abc def ghi', onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { onSelectionChangedCallCount += 1; }, ), ), ), ); // Long press to select 'abc'. final Offset aLocation = textOffsetToPosition(tester, 1); await tester.longPressAt(aLocation); await tester.pump(); expect(onSelectionChangedCallCount, equals(1)); // Long press to select 'def'. await tester.longPressAt(textOffsetToPosition(tester, 5)); await tester.pump(); expect(onSelectionChangedCallCount, equals(2)); // Tap on 'Select all' option to select the whole text. await tester.tap(find.text('Select all')); expect(onSelectionChangedCallCount, equals(3)); }); testWidgets('selecting a space selects the previous word on mobile', (WidgetTester tester) async { TextSelection? selection; await tester.pumpWidget( MaterialApp( home: SelectableText( ' blah blah', onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { selection = newSelection; }, ), ), ); expect(selection, isNull); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 10)); expect(selection, isNotNull); expect(selection!.baseOffset, 10); expect(selection!.extentOffset, 10); // Long press on the second space and the previous word is selected. await tester.longPressAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(selection, isNotNull); expect(selection!.baseOffset, 1); expect(selection!.extentOffset, 5); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 10)); expect(selection, isNotNull); expect(selection!.baseOffset, 10); expect(selection!.extentOffset, 10); // Long press on the first space and the space is selected because there is // no previous word. await tester.longPressAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(selection, isNotNull); expect(selection!.baseOffset, 0); expect(selection!.extentOffset, 1); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android })); testWidgets('selecting a space selects the space on non-mobile platforms', (WidgetTester tester) async { TextSelection? selection; await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: SelectableText( ' blah blah', onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { selection = newSelection; }, ), ), ), ), ); expect(selection, isNull); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 10)); expect(selection, isNotNull); expect(selection!.baseOffset, 10); expect(selection!.extentOffset, 10); // Double tapping the second space selects it. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(selection, isNotNull); expect(selection!.baseOffset, 5); expect(selection!.extentOffset, 6); // Tap at the beginning of the text to hide the toolbar, then at the end to // move the cursor to the end. On some platforms, the context menu would // otherwise block a tap on the end of the field. await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); await tester.tapAt(textOffsetToPosition(tester, 10)); expect(selection, isNotNull); expect(selection!.baseOffset, 10); expect(selection!.extentOffset, 10); // Double tapping the first space selects it. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(selection, isNotNull); expect(selection!.baseOffset, 0); expect(selection!.extentOffset, 1); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); testWidgets('double tapping a space selects the previous word on mobile', (WidgetTester tester) async { TextSelection? selection; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: SelectableText( ' blah blah \n blah', onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { selection = newSelection; }, ), ), ), ), ); expect(selection, isNull); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 19)); expect(selection, isNotNull); expect(selection!.baseOffset, 19); expect(selection!.extentOffset, 19); // Double tapping the second space selects the previous word. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(selection, isNotNull); expect(selection!.baseOffset, 1); expect(selection!.extentOffset, 5); // Double tapping does the same thing for the first space. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(selection, isNotNull); expect(selection!.baseOffset, 0); expect(selection!.extentOffset, 1); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 19)); expect(selection, isNotNull); expect(selection!.baseOffset, 19); expect(selection!.extentOffset, 19); // Double tapping the last space selects all previous contiguous spaces on // both lines and the previous word. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 14)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 14)); await tester.pumpAndSettle(); expect(selection, isNotNull); expect(selection!.baseOffset, 6); expect(selection!.extentOffset, 14); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android })); testWidgets('text selection style 1', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: const Material( child: Center( child: Column( children: <Widget>[ SelectableText.rich( TextSpan( children: <TextSpan>[ TextSpan( text: 'Atwater Peel ', style: TextStyle( fontSize: 30.0, ), ), TextSpan( text: 'Sherbrooke Bonaventure ', style: TextStyle( fontSize: 15.0, ), ), TextSpan( text: 'hi wassup!', style: TextStyle( fontSize: 10.0, ), ), ], ), key: Key('field0'), selectionHeightStyle: ui.BoxHeightStyle.includeLineSpacingTop, selectionWidthStyle: ui.BoxWidthStyle.max, ), ], ), ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; controller.selection = const TextSelection(baseOffset: 0, extentOffset: 46); await tester.pump(); await expectLater( find.byType(MaterialApp), matchesGoldenFile('selectable_text_golden.TextSelectionStyle.1.png'), ); }, skip: impellerEnabled); // https://github.com/flutter/flutter/issues/143616 testWidgets('text selection style 2', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: const Material( child: Center( child: Column( children: <Widget>[ SelectableText.rich( TextSpan( children: <TextSpan>[ TextSpan( text: 'Atwater Peel ', style: TextStyle( fontSize: 30.0, ), ), TextSpan( text: 'Sherbrooke Bonaventure ', style: TextStyle( fontSize: 15.0, ), ), TextSpan( text: 'hi wassup!', style: TextStyle( fontSize: 10.0, ), ), ], ), key: Key('field0'), selectionHeightStyle: ui.BoxHeightStyle.includeLineSpacingBottom, ), ], ), ), ), ), ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; controller.selection = const TextSelection(baseOffset: 0, extentOffset: 46); await tester.pump(); await expectLater( find.byType(MaterialApp), matchesGoldenFile('selectable_text_golden.TextSelectionStyle.2.png'), ); }, skip: impellerEnabled); // https://github.com/flutter/flutter/issues/143616 testWidgets('keeps alive when has focus', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: DefaultTabController( length: 2, child: Scaffold( body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverToBoxAdapter( child: Container( height: 200, color: Colors.black12, child: const Center(child: Text('Sliver 1')), ), ), const SliverToBoxAdapter( child: Center( child: TabBar( labelColor: Colors.black, tabs: <Tab>[ Tab(text: 'Sliver Tab 1'), Tab(text: 'Sliver Tab 2'), ], ), ) ), ]; }, body: const TabBarView( children: <Widget>[ Padding( padding: EdgeInsets.only(top: 100.0), child: Text('Regular Text'), ), Padding( padding: EdgeInsets.only(top: 100.0), child: SelectableText('Selectable Text'), ), ], ), ), ), ), ), ); // Without any selection, the offscreen widget is disposed and can't be // found, for both Text and SelectableText. expect(find.text('Regular Text', skipOffstage: false), findsOneWidget); expect(find.byType(SelectableText, skipOffstage: false), findsNothing); await tester.tap(find.text('Sliver Tab 2')); await tester.pumpAndSettle(); expect(find.text('Regular Text', skipOffstage: false), findsNothing); expect(find.byType(SelectableText, skipOffstage: false), findsOneWidget); await tester.tap(find.text('Sliver Tab 1')); await tester.pumpAndSettle(); expect(find.text('Regular Text', skipOffstage: false), findsOneWidget); expect(find.byType(SelectableText, skipOffstage: false), findsNothing); // Switch back to tab 2 and select some text in SelectableText. await tester.tap(find.text('Sliver Tab 2')); await tester.pumpAndSettle(); expect(find.text('Regular Text', skipOffstage: false), findsNothing); expect(find.byType(SelectableText, skipOffstage: false), findsOneWidget); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.controller.selection.isValid, isFalse); await tester.tapAt(textOffsetToPosition(tester, 4)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(editableText.controller.selection.isValid, isTrue); expect(editableText.controller.selection.baseOffset, 0); expect(editableText.controller.selection.extentOffset, 'Selectable'.length); // Switch back to tab 1. The SelectableText remains because it is preserving // its selection. await tester.tap(find.text('Sliver Tab 1')); await tester.pumpAndSettle(); expect(find.text('Regular Text', skipOffstage: false), findsOneWidget); expect(find.byType(SelectableText, skipOffstage: false), findsOneWidget); }); group('magnifier', () { late ValueNotifier<MagnifierInfo> magnifierInfo; final Widget fakeMagnifier = Container(key: UniqueKey()); testWidgets( 'Can drag handles to show, unshow, and update magnifier', (WidgetTester tester) async { const String testValue = 'abc def ghi'; final SelectableText selectableText = SelectableText( testValue, magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: ( _, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ) ); await tester.pumpWidget( overlay( child: selectableText, ), ); await skipPastScrollingAnimation(tester); // Double tap the 'e' to select 'def'. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(const Duration(milliseconds: 30)); await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(const Duration(milliseconds: 30)); final TextSelection selection = TextSelection( baseOffset: testValue.indexOf('d'), extentOffset: testValue.indexOf('f') ); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); // Drag the right handle 2 letters to the right. final Offset handlePos = endpoints.last.point + const Offset(1.0, 1.0); final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); Offset? firstDragGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, testValue.length - 2)); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, testValue.length)); await tester.pump(); // Expect the position the magnifier gets to have moved. expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); await gesture.up(); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsNothing); }); }); testWidgets('SelectableText text span style is merged with default text style', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/71389 const TextStyle textStyle = TextStyle(color: Color(0xff00ff00), fontSize: 12.0); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: const SelectableText.rich( TextSpan( text: 'Abcd', style: textStyle, ), ), ), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.fontSize, textStyle.fontSize); }); testWidgets('SelectableText text span style is merged with default text style', (WidgetTester tester) async { TextSelection? selection; int count = 0; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: SelectableText( 'I love Flutter!', onSelectionChanged: (TextSelection s, _) { selection = s; count++; }, ), ), ); expect(selection, null); expect(count, 0); // Tap to put the cursor before the "F". const int index = 7; await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 500)); expect( selection, const TextSelection.collapsed(offset: index), ); expect(count, 1); // The `onSelectionChanged` will be triggered one time. // Tap on the same location again. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); expect( selection, const TextSelection.collapsed(offset: index), ); expect(count, 1); // The `onSelectionChanged` will not be triggered. }); testWidgets("Off-screen selected text doesn't throw exception", (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/123527 TextSelection? selection; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Builder( builder: (BuildContext context) { return Column( children: <Widget>[ Expanded( child: ListView.builder( itemCount: 100, itemBuilder: (BuildContext context, int index) { return SelectableText( 'I love Flutter! $index', onSelectionChanged: (TextSelection s, _) { selection = s; }, ); }, ), ), TextButton( onPressed: () { Navigator.pop(context); }, child: const Text('Pop'), ), ], ); } ), ), )); expect(selection, null); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText).first); final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(50, 5)); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); expect(selection, isNotNull); await tester.drag(find.byType(ListView), const Offset(0.0, -3000.0)); await tester.pumpAndSettle(); await tester.tap(find.text('Pop')); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }); }
flutter/packages/flutter/test/widgets/selectable_text_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/selectable_text_test.dart", "repo_id": "flutter", "token_count": 79057 }
697
// 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/semantics.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('SemanticsEvent.toString', () { expect( TestSemanticsEvent().toString(), 'TestSemanticsEvent()', ); expect( TestSemanticsEvent(number: 10).toString(), 'TestSemanticsEvent(number: 10)', ); expect( TestSemanticsEvent(text: 'hello').toString(), 'TestSemanticsEvent(text: hello)', ); expect( TestSemanticsEvent(text: 'hello', number: 10).toString(), 'TestSemanticsEvent(number: 10, text: hello)', ); }); test('SemanticsEvent.toMap', () { expect( TestSemanticsEvent(text: 'hi', number: 11).toMap(), <String, dynamic>{ 'type': 'TestEvent', 'data': <String, dynamic>{ 'text': 'hi', 'number': 11, }, }, ); expect( TestSemanticsEvent(text: 'hi', number: 11).toMap(nodeId: 123), <String, dynamic>{ 'type': 'TestEvent', 'nodeId': 123, 'data': <String, dynamic>{ 'text': 'hi', 'number': 11, }, }, ); }); test('FocusSemanticEvent.toMap', () { expect( const FocusSemanticEvent().toMap(), <String, dynamic>{ 'type': 'focus', 'data': <String, dynamic>{}, }, ); }); } class TestSemanticsEvent extends SemanticsEvent { TestSemanticsEvent({ this.text, this.number }) : super('TestEvent'); final String? text; final int? number; @override Map<String, dynamic> getDataMap() { final Map<String, dynamic> result = <String, dynamic>{}; if (text != null) { result['text'] = text; } if (number != null) { result['number'] = number; } return result; } }
flutter/packages/flutter/test/widgets/semantics_event_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/semantics_event_test.dart", "repo_id": "flutter", "token_count": 818 }
698
// 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 'dart:typed_data'; import 'dart:ui' as ui show Image; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../image_data.dart'; import '../painting/mocks_for_image_cache.dart'; import 'test_border.dart' show TestBorder; Future<void> main() async { AutomatedTestWidgetsFlutterBinding(); final ui.Image rawImage = await decodeImageFromList(Uint8List.fromList(kTransparentImage)); final ImageProvider image = TestImageProvider(0, 0, image: rawImage); testWidgets('ShapeDecoration.image', // TODO(polina-c): clean up leaks, https://github.com/flutter/flutter/issues/134787 [leaks-to-clean] experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(), (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: DecoratedBox( decoration: ShapeDecoration( shape: Border.all(color: Colors.white) + Border.all(), image: DecorationImage( image: image, ), ), ), ), ); expect( find.byType(DecoratedBox), paints ..drawImageRect(image: rawImage) ..rect(color: Colors.black) ..rect(color: Colors.white), ); }); testWidgets('ShapeDecoration.color', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: DecoratedBox( decoration: ShapeDecoration( shape: Border.all(color: Colors.white) + Border.all(), color: Colors.blue, ), ), ), ); expect( find.byType(DecoratedBox), paints ..rect(color: Color(Colors.blue.value)) ..rect(color: Colors.black) ..rect(color: Colors.white), ); }); test('ShapeDecoration with BorderDirectional', () { const ShapeDecoration decoration = ShapeDecoration( shape: BorderDirectional(start: BorderSide(color: Colors.red, width: 3)), ); expect(decoration.padding, isA<EdgeInsetsDirectional>()); }); testWidgets('TestBorder and Directionality - 1', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( MaterialApp( home: DecoratedBox( decoration: ShapeDecoration( shape: TestBorder(log.add), color: Colors.green, ), ), ), ); expect( log, <String>[ 'getOuterPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.ltr', 'paint Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.ltr', ], ); }); testWidgets('TestBorder and Directionality - 2', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: DecoratedBox( decoration: ShapeDecoration( shape: TestBorder(log.add), image: DecorationImage( image: image, ), ), ), ), ); expect( log, <String>[ 'getInnerPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.rtl', 'paint Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.rtl', ], ); }); testWidgets('Does not crash with directional gradient', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/76967. await tester.pumpWidget( const Directionality( textDirection: TextDirection.rtl, child: DecoratedBox( decoration: ShapeDecoration( gradient: RadialGradient( focal: AlignmentDirectional.bottomCenter, focalRadius: 5, radius: 2, colors: <Color>[Colors.red, Colors.black], stops: <double>[0.0, 0.4], ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8.0)), ), ), ), ), ); expect(tester.takeException(), isNull); }); test('ShapeDecoration equality', () { const ShapeDecoration a = ShapeDecoration( color: Color(0xFFFFFFFF), shadows: <BoxShadow>[BoxShadow()], shape: Border(), ); const ShapeDecoration b = ShapeDecoration( color: Color(0xFFFFFFFF), shadows: <BoxShadow>[BoxShadow()], shape: Border(), ); expect(a.hashCode, equals(b.hashCode)); expect(a, equals(b)); }); }
flutter/packages/flutter/test/widgets/shape_decoration_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/shape_decoration_test.dart", "repo_id": "flutter", "token_count": 2123 }
699
// 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/src/rendering/sliver_persistent_header.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets( '_SliverScrollingPersistentHeader should update stretchConfiguration', (WidgetTester tester) async { for (final double stretchTriggerOffset in <double>[10.0, 20.0]) { await tester.pumpWidget(MaterialApp( home: CustomScrollView( slivers: <Widget>[ SliverPersistentHeader( delegate: TestDelegate( stretchConfiguration: OverScrollHeaderStretchConfiguration( stretchTriggerOffset: stretchTriggerOffset, ), ), ) ], ), )); } expect( tester.allWidgets.where((Widget w) => w.runtimeType.toString() == '_SliverScrollingPersistentHeader'), isNotEmpty); final RenderSliverScrollingPersistentHeader render = tester.allRenderObjects .whereType<RenderSliverScrollingPersistentHeader>() .first; expect(render.stretchConfiguration?.stretchTriggerOffset, 20); }); testWidgets( '_SliverPinnedPersistentHeader should update stretchConfiguration', (WidgetTester tester) async { for (final double stretchTriggerOffset in <double>[10.0, 20.0]) { await tester.pumpWidget(MaterialApp( home: CustomScrollView( slivers: <Widget>[ SliverPersistentHeader( pinned: true, delegate: TestDelegate( stretchConfiguration: OverScrollHeaderStretchConfiguration( stretchTriggerOffset: stretchTriggerOffset, ), ), ) ], ), )); } expect( tester.allWidgets.where((Widget w) => w.runtimeType.toString() == '_SliverPinnedPersistentHeader'), isNotEmpty); final RenderSliverPinnedPersistentHeader render = tester.allRenderObjects .whereType<RenderSliverPinnedPersistentHeader>() .first; expect(render.stretchConfiguration?.stretchTriggerOffset, 20); }); testWidgets( '_SliverPinnedPersistentHeader should update showOnScreenConfiguration', (WidgetTester tester) async { for (final double maxShowOnScreenExtent in <double>[1000, 2000]) { await tester.pumpWidget(MaterialApp( home: CustomScrollView( slivers: <Widget>[ SliverPersistentHeader( pinned: true, delegate: TestDelegate( showOnScreenConfiguration: PersistentHeaderShowOnScreenConfiguration( maxShowOnScreenExtent: maxShowOnScreenExtent), ), ) ], ), )); } expect( tester.allWidgets.where((Widget w) => w.runtimeType.toString() == '_SliverPinnedPersistentHeader'), isNotEmpty); final RenderSliverPinnedPersistentHeader render = tester.allRenderObjects .whereType<RenderSliverPinnedPersistentHeader>() .first; expect(render.showOnScreenConfiguration?.maxShowOnScreenExtent, 2000); }); } class TestDelegate extends SliverPersistentHeaderDelegate { TestDelegate({this.stretchConfiguration, this.showOnScreenConfiguration}); @override double get maxExtent => 200.0; @override double get minExtent => 200.0; @override Widget build( BuildContext context, double shrinkOffset, bool overlapsContent) { return Container(height: maxExtent); } @override bool shouldRebuild(TestDelegate oldDelegate) => false; @override final OverScrollHeaderStretchConfiguration? stretchConfiguration; @override final PersistentHeaderShowOnScreenConfiguration? showOnScreenConfiguration; }
flutter/packages/flutter/test/widgets/sliver_persistent_header_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/sliver_persistent_header_test.dart", "repo_id": "flutter", "token_count": 1625 }
700
// 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/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; const Color green = Color(0xFF00FF00); const Color yellow = Color(0xFFFFFF00); void main() { testWidgets('SlottedRenderObjectWidget test', (WidgetTester tester) async { await tester.pumpWidget(buildWidget( topLeft: Container( height: 100, width: 80, color: yellow, child: const Text('topLeft'), ), bottomRight: Container( height: 120, width: 110, color: green, child: const Text('bottomRight'), ), )); expect(find.text('topLeft'), findsOneWidget); expect(find.text('bottomRight'), findsOneWidget); expect(tester.getSize(find.byType(_Diagonal)), const Size(80 + 110, 100 + 120)); expect(find.byType(_Diagonal), paints ..rect( rect: const Rect.fromLTWH(0, 0, 80, 100), color: yellow, ) ..rect( rect: const Rect.fromLTWH(80, 100, 110, 120), color: green, ) ); await tester.pumpWidget(buildWidget( topLeft: Container( height: 200, width: 100, color: yellow, child: const Text('topLeft'), ), bottomRight: Container( height: 220, width: 210, color: green, child: const Text('bottomRight'), ), )); expect(find.text('topLeft'), findsOneWidget); expect(find.text('bottomRight'), findsOneWidget); expect(tester.getSize(find.byType(_Diagonal)), const Size(100 + 210, 200 + 220)); expect(find.byType(_Diagonal), paints ..rect( rect: const Rect.fromLTWH(0, 0, 100, 200), color: yellow, ) ..rect( rect: const Rect.fromLTWH(100, 200, 210, 220), color: green, ) ); await tester.pumpWidget(buildWidget( topLeft: Container( height: 200, width: 100, color: yellow, child: const Text('topLeft'), ), bottomRight: Container( key: UniqueKey(), height: 230, width: 220, color: green, child: const Text('bottomRight'), ), )); expect(find.text('topLeft'), findsOneWidget); expect(find.text('bottomRight'), findsOneWidget); expect(tester.getSize(find.byType(_Diagonal)), const Size(100 + 220, 200 + 230)); expect(find.byType(_Diagonal), paints ..rect( rect: const Rect.fromLTWH(0, 0, 100, 200), color: yellow, ) ..rect( rect: const Rect.fromLTWH(100, 200, 220, 230), color: green, ) ); await tester.pumpWidget(buildWidget( topLeft: Container( height: 200, width: 100, color: yellow, child: const Text('topLeft'), ), )); expect(find.text('topLeft'), findsOneWidget); expect(find.text('bottomRight'), findsNothing); expect(tester.getSize(find.byType(_Diagonal)), const Size(100, 200)); expect(find.byType(_Diagonal), paints ..rect( rect: const Rect.fromLTWH(0, 0, 100, 200), color: yellow, ) ); await tester.pumpWidget(buildWidget()); expect(find.text('topLeft'), findsNothing); expect(find.text('bottomRight'), findsNothing); expect(tester.getSize(find.byType(_Diagonal)), Size.zero); expect(find.byType(_Diagonal), paintsNothing); await tester.pumpWidget(Container()); expect(find.byType(_Diagonal), findsNothing); }); test('nameForSlot', () { expect(_RenderDiagonal().publicNameForSlot(_DiagonalSlot.bottomRight), 'bottomRight'); expect(_RenderDiagonal().publicNameForSlot(_DiagonalSlot.topLeft), 'topLeft'); final _Slot slot = _Slot(); expect(_RenderTest().publicNameForSlot(slot), slot.toString()); }); testWidgets('key reparenting', (WidgetTester tester) async { const Widget widget1 = SizedBox(key: ValueKey<String>('smol'), height: 10, width: 10); const Widget widget2 = SizedBox(key: ValueKey<String>('big'), height: 100, width: 100); const Widget nullWidget = SizedBox(key: ValueKey<String>('null'), height: 50, width: 50); await tester.pumpWidget(buildWidget(topLeft: widget1, bottomRight: widget2, nullSlot: nullWidget)); final _RenderDiagonal renderObject = tester.renderObject(find.byType(_Diagonal)); expect(renderObject._topLeft!.size, const Size(10, 10)); expect(renderObject._bottomRight!.size, const Size(100, 100)); expect(renderObject._nullSlot!.size, const Size(50, 50)); final Element widget1Element = tester.element(find.byWidget(widget1)); final Element widget2Element = tester.element(find.byWidget(widget2)); final Element nullWidgetElement = tester.element(find.byWidget(nullWidget)); // Swapping 1 and 2. await tester.pumpWidget(buildWidget(topLeft: widget2, bottomRight: widget1, nullSlot: nullWidget)); expect(renderObject._topLeft!.size, const Size(100, 100)); expect(renderObject._bottomRight!.size, const Size(10, 10)); expect(renderObject._nullSlot!.size, const Size(50, 50)); expect(widget1Element, same(tester.element(find.byWidget(widget1)))); expect(widget2Element, same(tester.element(find.byWidget(widget2)))); expect(nullWidgetElement, same(tester.element(find.byWidget(nullWidget)))); // Shifting slots await tester.pumpWidget(buildWidget(topLeft: nullWidget, bottomRight: widget2, nullSlot: widget1)); expect(renderObject._topLeft!.size, const Size(50, 50)); expect(renderObject._bottomRight!.size, const Size(100, 100)); expect(renderObject._nullSlot!.size, const Size(10, 10)); expect(widget1Element, same(tester.element(find.byWidget(widget1)))); expect(widget2Element, same(tester.element(find.byWidget(widget2)))); expect(nullWidgetElement, same(tester.element(find.byWidget(nullWidget)))); // Moving + Deleting. await tester.pumpWidget(buildWidget(bottomRight: widget2)); expect(renderObject._topLeft, null); expect(renderObject._bottomRight!.size, const Size(100, 100)); expect(renderObject._nullSlot, null); expect(widget1Element.debugIsDefunct, isTrue); expect(nullWidgetElement.debugIsDefunct, isTrue); expect(widget2Element, same(tester.element(find.byWidget(widget2)))); // Moving. await tester.pumpWidget(buildWidget(topLeft: widget2)); expect(renderObject._topLeft!.size, const Size(100, 100)); expect(renderObject._bottomRight, null); expect(widget2Element, same(tester.element(find.byWidget(widget2)))); }); testWidgets('duplicated key error message', (WidgetTester tester) async { const Widget widget1 = SizedBox(key: ValueKey<String>('widget 1'), height: 10, width: 10); const Widget widget2 = SizedBox(key: ValueKey<String>('widget 1'), height: 100, width: 100); const Widget widget3 = SizedBox(key: ValueKey<String>('widget 1'), height: 50, width: 50); await tester.pumpWidget(buildWidget(topLeft: widget1, bottomRight: widget2, nullSlot: widget3)); expect((tester.takeException() as FlutterError).toString(), equalsIgnoringHashCodes( 'Multiple widgets used the same key in _Diagonal.\n' "The key [<'widget 1'>] was used by multiple widgets. The offending widgets were:\n" " - SizedBox-[<'widget 1'>](width: 50.0, height: 50.0, renderObject: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT)\n" " - SizedBox-[<'widget 1'>](width: 10.0, height: 10.0, renderObject: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT)\n" " - SizedBox-[<'widget 1'>](width: 100.0, height: 100.0, renderObject: RenderConstrainedBox#a4685 NEEDS-LAYOUT NEEDS-PAINT)\n" 'A key can only be specified on one widget at a time in the same parent widget.' )); }); testWidgets('debugDescribeChildren', (WidgetTester tester) async { await tester.pumpWidget(buildWidget( topLeft: const SizedBox( height: 100, width: 80, ), bottomRight: const SizedBox( height: 120, width: 110, ), )); expect( tester.renderObject(find.byType(_Diagonal)).toStringDeep(), equalsIgnoringHashCodes( '_RenderDiagonal#00000 relayoutBoundary=up1\n' ' │ creator: _Diagonal ← Align ← Directionality ← MediaQuery ←\n' ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' ' │ [root]\n' ' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n' ' │ size: Size(190.0, 220.0)\n' ' │\n' ' ├─topLeft: RenderConstrainedBox#00000 relayoutBoundary=up2\n' ' │ creator: SizedBox ← _Diagonal ← Align ← Directionality ←\n' ' │ MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n' ' │ _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' ' │ TestFlutterView#00000] ← View ← [root]\n' ' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: BoxConstraints(unconstrained)\n' ' │ size: Size(80.0, 100.0)\n' ' │ additionalConstraints: BoxConstraints(w=80.0, h=100.0)\n' ' │\n' ' └─bottomRight: RenderConstrainedBox#00000 relayoutBoundary=up2\n' ' creator: SizedBox ← _Diagonal ← Align ← Directionality ←\n' ' MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n' ' _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' ' TestFlutterView#00000] ← View ← [root]\n' ' parentData: offset=Offset(80.0, 100.0) (can use size)\n' ' constraints: BoxConstraints(unconstrained)\n' ' size: Size(110.0, 120.0)\n' ' additionalConstraints: BoxConstraints(w=110.0, h=120.0)\n', ) ); }); } Widget buildWidget({Widget? topLeft, Widget? bottomRight, Widget? nullSlot}) { return Directionality( textDirection: TextDirection.ltr, child: Align( alignment: Alignment.topLeft, child: _Diagonal( topLeft: topLeft, bottomRight: bottomRight, nullSlot: nullSlot, ), ), ); } enum _DiagonalSlot { topLeft, bottomRight, } class _Diagonal extends RenderObjectWidget with SlottedMultiChildRenderObjectWidgetMixin<_DiagonalSlot?, RenderBox> { const _Diagonal({ this.topLeft, this.bottomRight, this.nullSlot, }); final Widget? topLeft; final Widget? bottomRight; final Widget? nullSlot; @override Iterable<_DiagonalSlot?> get slots => <_DiagonalSlot?>[null, ..._DiagonalSlot.values]; @override Widget? childForSlot(_DiagonalSlot? slot) { return switch (slot) { null => nullSlot, _DiagonalSlot.topLeft => topLeft, _DiagonalSlot.bottomRight => bottomRight, }; } @override SlottedContainerRenderObjectMixin<_DiagonalSlot?, RenderBox> createRenderObject( BuildContext context, ) { return _RenderDiagonal(); } } class _RenderDiagonal extends RenderBox with SlottedContainerRenderObjectMixin<_DiagonalSlot?, RenderBox> { RenderBox? get _topLeft => childForSlot(_DiagonalSlot.topLeft); RenderBox? get _bottomRight => childForSlot(_DiagonalSlot.bottomRight); RenderBox? get _nullSlot => childForSlot(null); @override void performLayout() { const BoxConstraints childConstraints = BoxConstraints(); Size topLeftSize = Size.zero; if (_topLeft != null) { _topLeft!.layout(childConstraints, parentUsesSize: true); _positionChild(_topLeft!, Offset.zero); topLeftSize = _topLeft!.size; } Size bottomRightSize = Size.zero; if (_bottomRight != null) { _bottomRight!.layout(childConstraints, parentUsesSize: true); _positionChild( _bottomRight!, Offset(topLeftSize.width, topLeftSize.height), ); bottomRightSize = _bottomRight!.size; } Size nullSlotSize = Size.zero; final RenderBox? nullSlot = _nullSlot; if (nullSlot != null) { nullSlot.layout(childConstraints, parentUsesSize: true); _positionChild(nullSlot, Offset.zero); nullSlotSize = nullSlot.size; } size = constraints.constrain(Size( topLeftSize.width + bottomRightSize.width + nullSlotSize.width, topLeftSize.height + bottomRightSize.height + nullSlotSize.height, )); } void _positionChild(RenderBox child, Offset offset) { (child.parentData! as BoxParentData).offset = offset; } @override void paint(PaintingContext context, Offset offset) { if (_topLeft != null) { _paintChild(_topLeft!, context, offset); } if (_bottomRight != null) { _paintChild(_bottomRight!, context, offset); } } void _paintChild(RenderBox child, PaintingContext context, Offset offset) { final BoxParentData childParentData = child.parentData! as BoxParentData; context.paintChild(child, childParentData.offset + offset); } String publicNameForSlot(_DiagonalSlot slot) => debugNameForSlot(slot); } class _Slot { @override String toString() => describeIdentity(this); } class _RenderTest extends RenderBox with SlottedContainerRenderObjectMixin<_Slot, RenderBox> { String publicNameForSlot(_Slot slot) => debugNameForSlot(slot); }
flutter/packages/flutter/test/widgets/slotted_render_object_widget_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/slotted_render_object_widget_test.dart", "repo_id": "flutter", "token_count": 5285 }
701
// 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. // TODO(LongCatIsLooong): Remove this file once textScaleFactor is removed. import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('TextStyle', () { test('getTextStyle is backward compatible', () { expect( const TextStyle(fontSize: 14).getTextStyle(textScaleFactor: 2.0).toString(), contains('fontSize: 28'), ); }, skip: kIsWeb); // [intended] CkTextStyle doesn't have a custom toString implementation. }); group('TextPainter', () { test('textScaleFactor translates to textScaler', () { final TextPainter textPainter = TextPainter( text: const TextSpan(text: 'text'), textDirection: TextDirection.ltr, textScaleFactor: 42, ); expect(textPainter.textScaler, const TextScaler.linear(42.0)); // Linear TextScaler translates to textScaleFactor. textPainter.textScaler = const TextScaler.linear(12.0); expect(textPainter.textScaleFactor, 12.0); textPainter.textScaleFactor = 10; expect(textPainter.textScaler, const TextScaler.linear(10)); }); }); group('MediaQuery', () { test('specifying both textScaler and textScalingFactor asserts', () { expect( () => MediaQueryData(textScaleFactor: 2, textScaler: const TextScaler.linear(2.0)), throwsAssertionError, ); }); test('copyWith is backward compatible', () { const MediaQueryData data = MediaQueryData(textScaler: TextScaler.linear(2.0)); final MediaQueryData data1 = data.copyWith(textScaleFactor: 42); expect(data1.textScaler, const TextScaler.linear(42)); expect(data1.textScaleFactor, 42); final MediaQueryData data2 = data.copyWith(textScaler: TextScaler.noScaling); expect(data2.textScaler, TextScaler.noScaling); expect(data2.textScaleFactor, 1.0); }); test('copyWith specifying both textScaler and textScalingFactor asserts', () { const MediaQueryData data = MediaQueryData(); expect( () => data.copyWith(textScaleFactor: 2, textScaler: const TextScaler.linear(2.0)), throwsAssertionError, ); }); testWidgets('MediaQuery.textScaleFactorOf overriding compatibility', (WidgetTester tester) async { late final double outsideTextScaleFactor; late final TextScaler outsideTextScaler; late final double insideTextScaleFactor; late final TextScaler insideTextScaler; await tester.pumpWidget( Builder( builder: (BuildContext context) { outsideTextScaleFactor = MediaQuery.textScaleFactorOf(context); outsideTextScaler = MediaQuery.textScalerOf(context); return MediaQuery( data: const MediaQueryData( textScaleFactor: 4.0, ), child: Builder( builder: (BuildContext context) { insideTextScaleFactor = MediaQuery.textScaleFactorOf(context); insideTextScaler = MediaQuery.textScalerOf(context); return Container(); }, ), ); }, ), ); // Overriding textScaleFactor should work for unmigrated widgets that are // still using MediaQuery.textScaleFactorOf. Also if a unmigrated widget // overrides MediaQuery.textScaleFactor, migrated widgets in the subtree // should get the correct TextScaler. expect(outsideTextScaleFactor, 1.0); expect(outsideTextScaler.textScaleFactor, 1.0); expect(outsideTextScaler, TextScaler.noScaling); expect(insideTextScaleFactor, 4.0); expect(insideTextScaler.textScaleFactor, 4.0); expect(insideTextScaler, const TextScaler.linear(4.0)); }); testWidgets('textScaleFactor overriding backward compatibility', (WidgetTester tester) async { late final double outsideTextScaleFactor; late final TextScaler outsideTextScaler; late final double insideTextScaleFactor; late final TextScaler insideTextScaler; await tester.pumpWidget( Builder( builder: (BuildContext context) { outsideTextScaleFactor = MediaQuery.textScaleFactorOf(context); outsideTextScaler = MediaQuery.textScalerOf(context); return MediaQuery( data: const MediaQueryData(textScaler: TextScaler.linear(4.0)), child: Builder( builder: (BuildContext context) { insideTextScaleFactor = MediaQuery.textScaleFactorOf(context); insideTextScaler = MediaQuery.textScalerOf(context); return Container(); }, ), ); }, ), ); expect(outsideTextScaleFactor, 1.0); expect(outsideTextScaler.textScaleFactor, 1.0); expect(outsideTextScaler, TextScaler.noScaling); expect(insideTextScaleFactor, 4.0); expect(insideTextScaler.textScaleFactor, 4.0); expect(insideTextScaler, const TextScaler.linear(4.0)); }); }); group('RenderObjects backward compatibility', () { test('RenderEditable', () { final RenderEditable renderObject = RenderEditable( backgroundCursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), textDirection: TextDirection.ltr, cursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), text: const TextSpan( text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed(offset: 0), ); expect(renderObject.textScaleFactor, 1.0); renderObject.textScaleFactor = 3.0; expect(renderObject.textScaleFactor, 3.0); expect(renderObject.textScaler, const TextScaler.linear(3.0)); renderObject.textScaler = const TextScaler.linear(4.0); expect(renderObject.textScaleFactor, 4.0); }); test('RenderParagraph', () { final RenderParagraph renderObject = RenderParagraph( const TextSpan( text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0), ), textDirection: TextDirection.ltr, ); expect(renderObject.textScaleFactor, 1.0); renderObject.textScaleFactor = 3.0; expect(renderObject.textScaleFactor, 3.0); expect(renderObject.textScaler, const TextScaler.linear(3.0)); renderObject.textScaler = const TextScaler.linear(4.0); expect(renderObject.textScaleFactor, 4.0); }); }); group('Widgets backward compatibility', () { testWidgets('RichText', (WidgetTester tester) async { await tester.pumpWidget( RichText( textDirection: TextDirection.ltr, text: const TextSpan(), textScaleFactor: 2.0, ), ); expect( tester.renderObject<RenderParagraph>(find.byType(RichText)).textScaler, const TextScaler.linear(2.0), ); expect(tester.renderObject<RenderParagraph>(find.byType(RichText)).textScaleFactor, 2.0); }); testWidgets('Text', (WidgetTester tester) async { await tester.pumpWidget( const Text( 'text', textDirection: TextDirection.ltr, textScaleFactor: 2.0, ), ); expect( tester.renderObject<RenderParagraph>(find.text('text')).textScaler, const TextScaler.linear(2.0), ); }); testWidgets('EditableText', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(debugLabel: 'EditableText Node'); addTearDown(focusNode.dispose); const TextStyle textStyle = TextStyle(); const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.rtl, child: EditableText( backgroundCursorColor: cursorColor, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, textScaleFactor: 2.0, ), ), ), ); final RenderEditable renderEditable = tester.allRenderObjects.whereType<RenderEditable>().first; expect( renderEditable.textScaler, const TextScaler.linear(2.0), ); }); }); } class _FakeEditableTextState with TextSelectionDelegate { @override TextEditingValue textEditingValue = TextEditingValue.empty; TextSelection? selection; @override void hideToolbar([bool hideHandles = true]) { } @override void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause cause) { selection = value.selection; } @override void bringIntoView(TextPosition position) { } @override void cutSelection(SelectionChangedCause cause) { } @override Future<void> pasteText(SelectionChangedCause cause) { return Future<void>.value(); } @override void selectAll(SelectionChangedCause cause) { } @override void copySelection(SelectionChangedCause cause) { } }
flutter/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart", "repo_id": "flutter", "token_count": 3923 }
702
// 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/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/gestures/monodrag.dart'; import 'package:flutter_test/flutter_test.dart'; import 'two_dimensional_utils.dart'; Widget? _testChildBuilder(BuildContext context, ChildVicinity vicinity) { return SizedBox( height: 200, width: 200, child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), ); } void main() { group('TwoDimensionalScrollView',() { testWidgets('asserts the axis directions do not conflict with one another', (WidgetTester tester) async { final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Horizontal wrong late final TwoDimensionalChildBuilderDelegate delegate1; addTearDown(() => delegate1.dispose()); await tester.pumpWidget(MaterialApp( home: SimpleBuilderTableView( delegate: delegate1 = TwoDimensionalChildBuilderDelegate(builder: (_, __) => null), horizontalDetails: const ScrollableDetails.vertical(), // Horizontal has default const ScrollableDetails.horizontal() ), )); // Vertical wrong late final TwoDimensionalChildBuilderDelegate delegate2; addTearDown(() => delegate2.dispose()); await tester.pumpWidget(MaterialApp( home: SimpleBuilderTableView( delegate: delegate2 = TwoDimensionalChildBuilderDelegate(builder: (_, __) => null), verticalDetails: const ScrollableDetails.horizontal(), // Horizontal has default const ScrollableDetails.horizontal() ), )); // Both wrong late final TwoDimensionalChildBuilderDelegate delegate3; addTearDown(() => delegate3.dispose()); await tester.pumpWidget(MaterialApp( home: SimpleBuilderTableView( delegate: delegate3 = TwoDimensionalChildBuilderDelegate(builder: (_, __) => null), verticalDetails: const ScrollableDetails.horizontal(), horizontalDetails: const ScrollableDetails.vertical(), ), )); FlutterError.onError = oldHandler; expect(exceptions.length, 3); for (final Object exception in exceptions) { expect(exception, isAssertionError); expect((exception as AssertionError).message, contains('are not Axis')); } }, variant: TargetPlatformVariant.all()); testWidgets('ScrollableDetails.controller can set initial scroll positions, modify within bounds', (WidgetTester tester) async { final ScrollController verticalController = ScrollController(initialScrollOffset: 100); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(initialScrollOffset: 50); addTearDown(horizontalController.dispose); late final TwoDimensionalChildBuilderDelegate delegate; addTearDown(() => delegate.dispose()); await tester.pumpWidget(MaterialApp( home: SimpleBuilderTableView( verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), delegate: delegate = TwoDimensionalChildBuilderDelegate( builder: _testChildBuilder, maxXIndex: 99, maxYIndex: 99, ), ), )); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 100); expect(verticalController.position.maxScrollExtent, 19400); expect(horizontalController.position.pixels, 50); expect(horizontalController.position.maxScrollExtent, 19200); verticalController.jumpTo(verticalController.position.maxScrollExtent); horizontalController.jumpTo(horizontalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 19400); expect(horizontalController.position.pixels, 19200); // Out of bounds verticalController.jumpTo(verticalController.position.maxScrollExtent + 100); horizontalController.jumpTo(horizontalController.position.maxScrollExtent + 100); // Account for varying scroll physics for different platforms (overscroll) await tester.pumpAndSettle(); expect(verticalController.position.pixels, 19400); expect(horizontalController.position.pixels, 19200); }, variant: TargetPlatformVariant.all()); testWidgets('Properly assigns the PrimaryScrollController to the main axis on the correct platform', (WidgetTester tester) async { late ScrollController controller; Widget buildForPrimaryScrollController({ bool? explicitPrimary, Axis mainAxis = Axis.vertical, bool addControllerConflict = false, }) { final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); late final TwoDimensionalChildBuilderDelegate delegate; addTearDown(() => delegate.dispose()); return MaterialApp( home: PrimaryScrollController( controller: controller, child: SimpleBuilderTableView( mainAxis: mainAxis, primary: explicitPrimary, verticalDetails: ScrollableDetails.vertical( controller: addControllerConflict && mainAxis == Axis.vertical ? verticalController : null ), horizontalDetails: ScrollableDetails.horizontal( controller: addControllerConflict && mainAxis == Axis.horizontal ? horizontalController : null ), delegate: delegate = TwoDimensionalChildBuilderDelegate( builder: _testChildBuilder, maxXIndex: 99, maxYIndex: 99, ), ), ), ); } // Horizontal default - horizontal never automatically adopts PSC controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildForPrimaryScrollController( mainAxis: Axis.horizontal, )); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(controller.hasClients, isFalse); } // Horizontal explicitly true controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildForPrimaryScrollController( mainAxis: Axis.horizontal, explicitPrimary: true, )); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { // Primary explicitly true is always adopted. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(controller.hasClients, isTrue); expect(controller.position.axis, Axis.horizontal); } // Horizontal explicitly false controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildForPrimaryScrollController( mainAxis: Axis.horizontal, explicitPrimary: false, )); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { // Primary explicitly false is never adopted. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(controller.hasClients, isFalse); } // Vertical default controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildForPrimaryScrollController()); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { // Mobile platforms inherit the PSC without explicitly setting // primary case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: expect(controller.hasClients, isTrue); expect(controller.position.axis, Axis.vertical); case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(controller.hasClients, isFalse); } // Vertical explicitly true controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildForPrimaryScrollController( explicitPrimary: true, )); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { // Primary explicitly true is always adopted. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(controller.hasClients, isTrue); expect(controller.position.axis, Axis.vertical); } // Vertical explicitly false controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildForPrimaryScrollController( explicitPrimary: false, )); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { // Primary explicitly false is never adopted. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(controller.hasClients, isFalse); } // Assertions final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Vertical asserts ScrollableDetails.controller has not been provided if // primary is explicitly set controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildForPrimaryScrollController( explicitPrimary: true, addControllerConflict: true, )); expect(exceptions.length, 1); expect(exceptions[0], isAssertionError); expect( (exceptions[0] as AssertionError).message, contains('TwoDimensionalScrollView.primary was explicitly set to true'), ); exceptions.clear(); // Horizontal asserts ScrollableDetails.controller has not been provided // if primary is explicitly set true controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(buildForPrimaryScrollController( mainAxis: Axis.horizontal, explicitPrimary: true, addControllerConflict: true, )); expect(exceptions.length, 1); expect(exceptions[0], isAssertionError); expect( (exceptions[0] as AssertionError).message, contains('TwoDimensionalScrollView.primary was explicitly set to true'), ); FlutterError.onError = oldHandler; }, variant: TargetPlatformVariant.all()); testWidgets('TwoDimensionalScrollable receives the correct details from TwoDimensionalScrollView', (WidgetTester tester) async { late BuildContext capturedContext; // Default late final TwoDimensionalChildBuilderDelegate delegate1; addTearDown(() => delegate1.dispose()); await tester.pumpWidget(MaterialApp( home: SimpleBuilderTableView( delegate: delegate1 = TwoDimensionalChildBuilderDelegate( builder: (BuildContext context, ChildVicinity vicinity) { capturedContext = context; return Text(vicinity.toString()); }, ), ), )); await tester.pumpAndSettle(); TwoDimensionalScrollableState scrollable = TwoDimensionalScrollable.of( capturedContext, ); expect(scrollable.widget.verticalDetails.direction, AxisDirection.down); expect(scrollable.widget.horizontalDetails.direction, AxisDirection.right); expect(scrollable.widget.diagonalDragBehavior, DiagonalDragBehavior.none); expect(scrollable.widget.dragStartBehavior, DragStartBehavior.start); // Customized late final TwoDimensionalChildBuilderDelegate delegate2; addTearDown(() => delegate2.dispose()); await tester.pumpWidget(MaterialApp( home: SimpleBuilderTableView( verticalDetails: const ScrollableDetails.vertical(reverse: true), horizontalDetails: const ScrollableDetails.horizontal(reverse: true), diagonalDragBehavior: DiagonalDragBehavior.weightedContinuous, dragStartBehavior: DragStartBehavior.down, delegate: delegate2 = TwoDimensionalChildBuilderDelegate( builder: _testChildBuilder, ), ), )); await tester.pumpAndSettle(); scrollable = TwoDimensionalScrollable.of(capturedContext); expect(scrollable.widget.verticalDetails.direction, AxisDirection.up); expect(scrollable.widget.horizontalDetails.direction, AxisDirection.left); expect(scrollable.widget.diagonalDragBehavior, DiagonalDragBehavior.weightedContinuous); expect(scrollable.widget.dragStartBehavior, DragStartBehavior.down); }, variant: TargetPlatformVariant.all()); testWidgets('Interrupt fling with tap stops scrolling', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/133529 final List<String> log = <String>[]; final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SimpleBuilderTableView( verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), diagonalDragBehavior: DiagonalDragBehavior.free, delegate: TwoDimensionalChildBuilderDelegate( maxXIndex: 100, maxYIndex: 100, builder: (BuildContext context, ChildVicinity vicinity) { return GestureDetector( onTapUp: (TapUpDetails details) { log.add('Tapped: $vicinity'); }, child: Text('$vicinity'), ); }, ), ), ), ); await tester.pumpAndSettle(); expect(log, equals(<String>[])); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); // Tap once await tester.tap(find.byType(TwoDimensionalScrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); // Fling the scrollview to get it scrolling, verify that no tap occurs. await tester.fling(find.byType(TwoDimensionalScrollable), const Offset(0.0, -200.0), 2000.0); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(verticalController.position.pixels, greaterThan(170.0)); double unchangedOffset = verticalController.position.pixels; expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity!.isScrolling, isTrue); expect(horizontalController.position.activity!.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, greaterThan(1500)); expect(horizontalController.position.activity!.velocity, 0.0); // Tap to stop the scroll movement, this should stop the fling but not tap anything await tester.tap(find.byType(TwoDimensionalScrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(verticalController.position.pixels, unchangedOffset); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); // Another tap. await tester.tap(find.byType(TwoDimensionalScrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, <String>['Tapped: (xIndex: 0, yIndex: 0)', 'Tapped: (xIndex: 0, yIndex: 0)']); expect(verticalController.position.pixels, unchangedOffset); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); log.clear(); verticalController.jumpTo(0.0); await tester.pump(); // Fling off in the other direction now ---------------------------------- expect(log, equals(<String>[])); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); // Tap once await tester.tap(find.byType(TwoDimensionalScrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); // Fling the scrollview to get it scrolling, verify that no tap occurs. await tester.fling(find.byType(TwoDimensionalScrollable), const Offset(-200.0, 0.0), 2000.0); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(horizontalController.position.pixels, greaterThan(170.0)); unchangedOffset = horizontalController.position.pixels; expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.activity!.isScrolling, isTrue); expect(verticalController.position.activity!.isScrolling, isFalse); expect(horizontalController.position.activity!.velocity, greaterThan(1500)); expect(verticalController.position.activity!.velocity, 0.0); // Tap to stop the scroll movement, this should stop the fling but not tap anything await tester.tap(find.byType(TwoDimensionalScrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(horizontalController.position.pixels, unchangedOffset); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity!.velocity, 0.0); expect(verticalController.position.activity!.velocity, 0.0); // Another tap. await tester.tap(find.byType(TwoDimensionalScrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, <String>['Tapped: (xIndex: 0, yIndex: 0)', 'Tapped: (xIndex: 0, yIndex: 0)']); expect(horizontalController.position.pixels, unchangedOffset); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity!.velocity, 0.0); expect(verticalController.position.activity!.velocity, 0.0); }, variant: TargetPlatformVariant.all()); testWidgets('Fling, wait to stop and tap', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/133529 final List<String> log = <String>[]; final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SimpleBuilderTableView( verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), diagonalDragBehavior: DiagonalDragBehavior.free, delegate: TwoDimensionalChildBuilderDelegate( maxXIndex: 100, maxYIndex: 100, builder: (BuildContext context, ChildVicinity vicinity) { return GestureDetector( onTapUp: (TapUpDetails details) { log.add('Tapped: $vicinity'); }, child: Text('$vicinity'), ); }, ), ), ), ); await tester.pumpAndSettle(); expect(log, equals(<String>[])); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); // Tap once await tester.tap(find.byType(TwoDimensionalScrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); // Fling the scrollview to get it scrolling, verify that no tap occurs. await tester.fling(find.byType(TwoDimensionalScrollable), const Offset(0.0, -200.0), 2000.0); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(verticalController.position.pixels, greaterThan(170.0)); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity!.isScrolling, isTrue); expect(horizontalController.position.activity!.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, greaterThan(1500)); expect(horizontalController.position.activity!.velocity, 0.0); // Wait for the fling to finish. await tester.pumpAndSettle(); expect(log, equals(<String>['Tapped: (xIndex: 0, yIndex: 0)'])); expect(verticalController.position.pixels, greaterThan(800.0)); final double unchangedOffset = verticalController.position.pixels; expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity!.velocity, 0.0); expect(horizontalController.position.activity!.velocity, 0.0); // Another tap. await tester.tap(find.byType(TwoDimensionalScrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, <String>['Tapped: (xIndex: 0, yIndex: 0)', 'Tapped: (xIndex: 0, yIndex: 4)']); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.pixels, unchangedOffset); expect(horizontalController.position.activity?.isScrolling, isFalse); expect(verticalController.position.activity?.isScrolling, isFalse); expect(horizontalController.position.activity!.velocity, 0.0); expect(verticalController.position.activity!.velocity, 0.0); }); }); }
flutter/packages/flutter/test/widgets/two_dimensional_scroll_view_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/two_dimensional_scroll_view_test.dart", "repo_id": "flutter", "token_count": 9825 }
703
// 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'; void main() { // Generic reference variables. BuildContext context; RenderObjectWidget renderObjectWidget; RenderObject renderObject; Object object; // Changes made in https://github.com/flutter/flutter/pull/26259 Scaffold scaffold = Scaffold(resizeToAvoidBottomPadding: true); scaffold = Scaffold(error: ''); final bool resize = scaffold.resizeToAvoidBottomPadding; // Change made in https://github.com/flutter/flutter/pull/15303 showDialog(child: Text('Fix me.')); showDialog(error: ''); // Changes made in https://github.com/flutter/flutter/pull/44189 const Element element = Element(myWidget); element.inheritFromElement(ancestor); element.inheritFromWidgetOfExactType(targetType); element.ancestorInheritedElementForWidgetOfExactType(targetType); element.ancestorWidgetOfExactType(targetType); element.ancestorStateOfType(TypeMatcher<targetType>()); element.rootAncestorStateOfType(TypeMatcher<targetType>()); element.ancestorRenderObjectOfType(TypeMatcher<targetType>()); // Changes made in https://github.com/flutter/flutter/pull/45941 and https://github.com/flutter/flutter/pull/83843 final WidgetsBinding binding = WidgetsBinding.instance!; binding.deferFirstFrameReport(); binding.allowFirstFrameReport(); // Changes made in https://github.com/flutter/flutter/pull/44189 const StatefulElement statefulElement = StatefulElement(myWidget); statefulElement.inheritFromElement(ancestor); // Changes made in https://github.com/flutter/flutter/pull/44189 const BuildContext buildContext = Element(myWidget); buildContext.inheritFromElement(ancestor); buildContext.inheritFromWidgetOfExactType(targetType); buildContext.ancestorInheritedElementForWidgetOfExactType(targetType); buildContext.ancestorWidgetOfExactType(targetType); buildContext.ancestorStateOfType(TypeMatcher<targetType>()); buildContext.rootAncestorStateOfType(TypeMatcher<targetType>()); buildContext.ancestorRenderObjectOfType(TypeMatcher<targetType>()); // Changes made in https://github.com/flutter/flutter/pull/66305 const Stack stack = Stack(overflow: Overflow.visible); const Stack stack = Stack(overflow: Overflow.clip); const Stack stack = Stack(error: ''); final behavior = stack.overflow; // Changes made in https://github.com/flutter/flutter/pull/61648 const Form form = Form(autovalidate: true); const Form form = Form(autovalidate: false); const Form form = Form(error: ''); final autoMode = form.autovalidate; // Changes made in https://github.com/flutter/flutter/pull/61648 const FormField formField = FormField(autovalidate: true); const FormField formField = FormField(autovalidate: false); const FormField formField = FormField(error: ''); final autoMode = formField.autovalidate; // Changes made in https://github.com/flutter/flutter/pull/61648 const TextFormField textFormField = TextFormField(autovalidate: true); const TextFormField textFormField = TextFormField(autovalidate: false); const TextFormField textFormField = TextFormField(error: ''); // Changes made in https://github.com/flutter/flutter/pull/61648 const DropdownButtonFormField dropDownButtonFormField = DropdownButtonFormField(autovalidate: true); const DropdownButtonFormField dropdownButtonFormField = DropdownButtonFormField(autovalidate: false); const DropdownButtonFormField dropdownButtonFormField = DropdownButtonFormField(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68736 MediaQuery.of(context, nullOk: true); MediaQuery.of(context, nullOk: false); MediaQuery.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/70726 Navigator.of(context, nullOk: true); Navigator.of(context, nullOk: false); Navigator.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68908 ScaffoldMessenger.of(context, nullOk: true); ScaffoldMessenger.of(context, nullOk: false); ScaffoldMessenger.of(error: ''); Scaffold.of(error: ''); Scaffold.of(context, nullOk: true); Scaffold.of(context, nullOk: false); // Changes made in https://github.com/flutter/flutter/pull/68910 Router.of(context, nullOk: true); Router.of(context, nullOk: false); Router.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68911 Localizations.localeOf(context, nullOk: true); Localizations.localeOf(context, nullOk: false); Localizations.localeOf(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68917 FocusTraversalOrder.of(context, nullOk: true); FocusTraversalOrder.of(context, nullOk: false); FocusTraversalOrder.of(error: ''); FocusTraversalGroup.of(error: ''); FocusTraversalGroup.of(context, nullOk: true); FocusTraversalGroup.of(context, nullOk: false); Focus.of(context, nullOk: true); Focus.of(context, nullOk: false); Focus.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68921 Shortcuts.of(context, nullOk: true); Shortcuts.of(context, nullOk: false); Shortcuts.of(error: ''); Actions.find(error: ''); Actions.find(context, nullOk: true); Actions.find(context, nullOk: false); Actions.handler(context, nullOk: true); Actions.handler(context, nullOk: false); Actions.handler(error: ''); Actions.invoke(error: ''); Actions.invoke(context, nullOk: true); Actions.invoke(context, nullOk: false); // Changes made in https://github.com/flutter/flutter/pull/68925 AnimatedList.of(context, nullOk: true); AnimatedList.of(context, nullOk: false); AnimatedList.of(error: ''); SliverAnimatedList.of(error: ''); SliverAnimatedList.of(context, nullOk: true); SliverAnimatedList.of(context, nullOk: false); // Changes made in https://github.com/flutter/flutter/pull/68905 MaterialBasedCupertinoThemeData.resolveFrom(context, nullOk: true); MaterialBasedCupertinoThemeData.resolveFrom(context, nullOk: false); MaterialBasedCupertinoThemeData.resolveFrom(error: ''); // Changes made in https://github.com/flutter/flutter/pull/72043 TextField(maxLengthEnforced: true); TextField(maxLengthEnforced: false); TextField(error: ''); final TextField textField; textField.maxLengthEnforced; TextFormField(maxLengthEnforced: true); TextFormField(maxLengthEnforced: false); TextFormField(error: ''); // Changes made in https://github.com/flutter/flutter/pull/59127 const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(title: myTitle); const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(); const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(error: ''); bottomNavigationBarItem.title; // Changes made in https://github.com/flutter/flutter/pull/65246 RectangularSliderTrackShape(disabledThumbGapWidth: 2.0); RectangularSliderTrackShape(error: ''); // Changes made in https://github.com/flutter/flutter/pull/46115 const InputDecoration inputDecoration = InputDecoration(hasFloatingPlaceholder: true); InputDecoration(hasFloatingPlaceholder: false); InputDecoration(); InputDecoration(error: ''); InputDecoration.collapsed(hasFloatingPlaceholder: true); InputDecoration.collapsed(hasFloatingPlaceholder: false); InputDecoration.collapsed(); InputDecoration.collapsed(error: ''); inputDecoration.hasFloatingPlaceholder; const InputDecorationTheme inputDecorationTheme = InputDecorationTheme(hasFloatingPlaceholder: true); InputDecorationTheme(hasFloatingPlaceholder: false); InputDecorationTheme(); InputDecorationTheme(error: ''); inputDecorationTheme.hasFloatingPlaceholder; inputDecorationTheme.copyWith(hasFloatingPlaceholder: false); inputDecorationTheme.copyWith(hasFloatingPlaceholder: true); inputDecorationTheme.copyWith(); inputDecorationTheme.copyWith(error: ''); // Changes made in https://github.com/flutter/flutter/pull/79160 Draggable draggable = Draggable(); draggable = Draggable(dragAnchor: DragAnchor.child); draggable = Draggable(dragAnchor: DragAnchor.pointer); draggable = Draggable(error: ''); draggable.dragAnchor; // Changes made in https://github.com/flutter/flutter/pull/79160 LongPressDraggable longPressDraggable = LongPressDraggable(); longPressDraggable = LongPressDraggable(dragAnchor: DragAnchor.child); longPressDraggable = LongPressDraggable(dragAnchor: DragAnchor.pointer); longPressDraggable = LongPressDraggable(error: ''); longPressDraggable.dragAnchor; // Changes made in https://github.com/flutter/flutter/pull/64254 final LeafRenderObjectElement leafElement = LeafRenderObjectElement(); leafElement.insertChildRenderObject(renderObject, object); leafElement.moveChildRenderObject(renderObject, object); leafElement.removeChildRenderObject(renderObject); final ListWheelElement listWheelElement = ListWheelElement(); listWheelElement.insertChildRenderObject(renderObject, object); listWheelElement.moveChildRenderObject(renderObject, object); listWheelElement.removeChildRenderObject(renderObject); final MultiChildRenderObjectElement multiChildRenderObjectElement = MultiChildRenderObjectElement(); multiChildRenderObjectElement.insertChildRenderObject(renderObject, object); multiChildRenderObjectElement.moveChildRenderObject(renderObject, object); multiChildRenderObjectElement.removeChildRenderObject(renderObject); final SingleChildRenderObjectElement singleChildRenderObjectElement = SingleChildRenderObjectElement(); singleChildRenderObjectElement.insertChildRenderObject(renderObject, object); singleChildRenderObjectElement.moveChildRenderObject(renderObject, object); singleChildRenderObjectElement.removeChildRenderObject(renderObject); final SliverMultiBoxAdaptorElement sliverMultiBoxAdaptorElement = SliverMultiBoxAdaptorElement(); sliverMultiBoxAdaptorElement.insertChildRenderObject(renderObject, object); sliverMultiBoxAdaptorElement.moveChildRenderObject(renderObject, object); sliverMultiBoxAdaptorElement.removeChildRenderObject(renderObject); final RenderObjectToWidgetElement renderObjectToWidgetElement = RenderObjectToWidgetElement(widget); renderObjectToWidgetElement.insertChildRenderObject(renderObject, object); renderObjectToWidgetElement.moveChildRenderObject(renderObject, object); renderObjectToWidgetElement.removeChildRenderObject(renderObject); // Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior ListWheelScrollView listWheelScrollView = ListWheelScrollView(); listWheelScrollView = ListWheelScrollView(clipToSize: true); listWheelScrollView = ListWheelScrollView(clipToSize: false); listWheelScrollView = ListWheelScrollView(error: ''); listWheelScrollView = ListWheelScrollView.useDelegate(error: ''); listWheelScrollView = ListWheelScrollView.useDelegate(); listWheelScrollView = ListWheelScrollView.useDelegate(clipToSize: true); listWheelScrollView = ListWheelScrollView.useDelegate(clipToSize: false); listWheelScrollView.clipToSize; ListWheelViewport listWheelViewport = ListWheelViewport(); listWheelViewport = ListWheelViewport(clipToSize: true); listWheelViewport = ListWheelViewport(clipToSize: false); listWheelViewport = ListWheelViewport(error: ''); listWheelViewport.clipToSize; // Changes made in https://github.com/flutter/flutter/pull/87839 final OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(leading: true); final OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(error: ''); notification.disallowGlow(); // Changes made in https://github.com/flutter/flutter/pull/96115 Icon icon = Icons.pie_chart_outlined; // Changes made in https://github.com/flutter/flutter/pull/96957 Scrollbar scrollbar = Scrollbar(isAlwaysShown: true); bool nowShowing = scrollbar.isAlwaysShown; ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(isAlwaysShown: nowShowing); scrollbarTheme.copyWith(isAlwaysShown: nowShowing); scrollbarTheme.isAlwaysShown; RawScrollbar rawScrollbar = RawScrollbar(isAlwaysShown: true); nowShowing = rawScrollbar.isAlwaysShown; // Changes made in https://github.com/flutter/flutter/pull/96174 Chip chip = Chip(); chip = Chip(useDeleteButtonTooltip: false); chip = Chip(useDeleteButtonTooltip: true); chip = Chip(useDeleteButtonTooltip: false, deleteButtonTooltipMessage: 'Delete Tooltip'); chip.useDeleteButtonTooltip; // Changes made in https://github.com/flutter/flutter/pull/96174 InputChip inputChip = InputChip(); inputChip = InputChip(useDeleteButtonTooltip: false); inputChip = InputChip(useDeleteButtonTooltip: true); inputChip = InputChip(useDeleteButtonTooltip: false, deleteButtonTooltipMessage: 'Delete Tooltip'); inputChip.useDeleteButtonTooltip; // Changes made in https://github.com/flutter/flutter/pull/96174 RawChip rawChip = Rawchip(); rawChip = RawChip(useDeleteButtonTooltip: false); rawChip = RawChip(useDeleteButtonTooltip: true); rawChip = RawChip(useDeleteButtonTooltip: false, deleteButtonTooltipMessage: 'Delete Tooltip'); rawChip.useDeleteButtonTooltip; // Change made in https://github.com/flutter/flutter/pull/100381 TextSelectionOverlay.fadeDuration; // Changes made in https://github.com/flutter/flutter/pull/105291 ButtonStyle elevationButtonStyle = ElevatedButton.styleFrom( primary: Colors.blue, onPrimary: Colors.white, onSurface: Colors.grey, ); ButtonStyle outlinedButtonStyle = OutlinedButton.styleFrom( primary: Colors.blue, onSurface: Colors.grey, ); ButtonStyle textButtonStyle = TextButton.styleFrom( primary: Colors.blue, onSurface: Colors.grey, ); // Changes made in https://github.com/flutter/flutter/pull/78588 final ScrollBehavior scrollBehavior = ScrollBehavior(); scrollBehavior.buildViewportChrome(context, child, axisDirection); final MaterialScrollBehavior materialScrollBehavior = MaterialScrollBehavior(); materialScrollBehavior.buildViewportChrome(context, child, axisDirection); // Changes made in https://github.com/flutter/flutter/pull/111706 Scrollbar scrollbar = Scrollbar(showTrackOnHover: true); bool nowShowing = scrollbar.showTrackOnHover; // The 3 expressions below have `bulkApply` set to true thus can't be tested yet. //ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(showTrackOnHover: nowShowing); //scrollbarTheme.copyWith(showTrackOnHover: nowShowing); //scrollbarTheme.showTrackOnHover; // Changes made in https://github.com/flutter/flutter/pull/114459 MediaQuery.boldTextOverride(context); // Changes made in https://github.com/flutter/flutter/pull/122555 final ScrollableDetails details = ScrollableDetails( direction: AxisDirection.down, clipBehavior: Clip.none, ); final Clip clip = details.clipBehavior; // Changes made in https://github.com/flutter/flutter/pull/134417 const Curve curve = standardEasing; const Curve curve = accelerateEasing; const Curve curve = decelerateEasing; final PlatformMenuBar platformMenuBar = PlatformMenuBar(menus: <PlatformMenuItem>[], body: const SizedBox()); final Widget bodyValue = platformMenuBar.body; }
flutter/packages/flutter/test_fixes/material/material.dart/0
{ "file_path": "flutter/packages/flutter/test_fixes/material/material.dart", "repo_id": "flutter", "token_count": 4616 }
704
// 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/widgets.dart'; void main() { // Changes made in https://github.com/flutter/flutter/pull/68921 Actions.find(error: ''); Actions.find(context, nullOk: true); Actions.find(context, nullOk: false); Actions.handler(context, nullOk: true); Actions.handler(context, nullOk: false); Actions.handler(error: ''); Actions.invoke(error: ''); Actions.invoke(context, nullOk: true); Actions.invoke(context, nullOk: false); }
flutter/packages/flutter/test_fixes/widgets/actions.dart/0
{ "file_path": "flutter/packages/flutter/test_fixes/widgets/actions.dart", "repo_id": "flutter", "token_count": 194 }
705
// 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/widgets.dart'; void main() { // Generic reference variables. BuildContext context; RenderObjectWidget renderObjectWidget; RenderObject renderObject; Object object; TickerProvider vsync; // Changes made in https://github.com/flutter/flutter/pull/123352 WidgetsBinding.instance.renderViewElement; // Changes made in https://github.com/flutter/flutter/pull/119647 MediaQueryData.fromWindow(View.of(context)); // Changes made in https://github.com/flutter/flutter/pull/119186 and https://github.com/flutter/flutter/pull/81067 AnimatedSize(vsync: vsync, duration: Duration.zero); // Changes made in https://github.com/flutter/flutter/pull/45941 and https://github.com/flutter/flutter/pull/83843 final WidgetsBinding binding = WidgetsBinding.instance; binding.deferFirstFrameReport(); binding.allowFirstFrameReport(); // Changes made in https://github.com/flutter/flutter/pull/44189 const StatefulElement statefulElement = StatefulElement(myWidget); statefulElement.inheritFromElement(ancestor); // Changes made in https://github.com/flutter/flutter/pull/61648 const Form form = Form(autovalidate: true); const Form form = Form(autovalidate: false); const Form form = Form(error: ''); final autoMode = form.autovalidate; // Changes made in https://github.com/flutter/flutter/pull/61648 const FormField formField = FormField(autovalidate: true); const FormField formField = FormField(autovalidate: false); const FormField formField = FormField(error: ''); final autoMode = formField.autovalidate; // Changes made in https://github.com/flutter/flutter/pull/66305 const Stack stack = Stack(overflow: Overflow.visible); const Stack stack = Stack(overflow: Overflow.clip); const Stack stack = Stack(error: ''); final behavior = stack.overflow; // Changes made in https://github.com/flutter/flutter/pull/68736 MediaQuery.of(context, nullOk: true); MediaQuery.of(context, nullOk: false); MediaQuery.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/70726 Navigator.of(context, nullOk: true); Navigator.of(context, nullOk: false); Navigator.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68910 Router.of(context, nullOk: true); Router.of(context, nullOk: false); Router.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68911 Localizations.localeOf(context, nullOk: true); Localizations.localeOf(context, nullOk: false); Localizations.localeOf(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68917 FocusTraversalOrder.of(context, nullOk: true); FocusTraversalOrder.of(context, nullOk: false); FocusTraversalOrder.of(error: ''); FocusTraversalGroup.of(error: ''); FocusTraversalGroup.of(context, nullOk: true); FocusTraversalGroup.of(context, nullOk: false); Focus.of(context, nullOk: true); Focus.of(context, nullOk: false); Focus.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68921 Shortcuts.of(context, nullOk: true); Shortcuts.of(context, nullOk: false); Shortcuts.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68925 AnimatedList.of(context, nullOk: true); AnimatedList.of(context, nullOk: false); AnimatedList.of(error: ''); SliverAnimatedList.of(error: ''); SliverAnimatedList.of(context, nullOk: true); SliverAnimatedList.of(context, nullOk: false); // Changes made in https://github.com/flutter/flutter/pull/59127 const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(title: myTitle); const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(); const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(error: ''); bottomNavigationBarItem.title; // Changes made in https://github.com/flutter/flutter/pull/79160 Draggable draggable = Draggable(); draggable = Draggable(dragAnchor: DragAnchor.child); draggable = Draggable(dragAnchor: DragAnchor.pointer); draggable = Draggable(error: ''); draggable.dragAnchor; // Changes made in https://github.com/flutter/flutter/pull/79160 LongPressDraggable longPressDraggable = LongPressDraggable(); longPressDraggable = LongPressDraggable(dragAnchor: DragAnchor.child); longPressDraggable = LongPressDraggable(dragAnchor: DragAnchor.pointer); longPressDraggable = LongPressDraggable(error: ''); longPressDraggable.dragAnchor; // Changes made in https://github.com/flutter/flutter/pull/64254 final LeafRenderObjectElement leafElement = LeafRenderObjectElement(); leafElement.insertChildRenderObject(renderObject, object); leafElement.moveChildRenderObject(renderObject, object); leafElement.removeChildRenderObject(renderObject); final ListWheelElement listWheelElement = ListWheelElement(); listWheelElement.insertChildRenderObject(renderObject, object); listWheelElement.moveChildRenderObject(renderObject, object); listWheelElement.removeChildRenderObject(renderObject); final MultiChildRenderObjectElement multiChildRenderObjectElement = MultiChildRenderObjectElement(); multiChildRenderObjectElement.insertChildRenderObject(renderObject, object); multiChildRenderObjectElement.moveChildRenderObject(renderObject, object); multiChildRenderObjectElement.removeChildRenderObject(renderObject); final SingleChildRenderObjectElement singleChildRenderObjectElement = SingleChildRenderObjectElement(); singleChildRenderObjectElement.insertChildRenderObject(renderObject, object); singleChildRenderObjectElement.moveChildRenderObject(renderObject, object); singleChildRenderObjectElement.removeChildRenderObject(renderObject); final SliverMultiBoxAdaptorElement sliverMultiBoxAdaptorElement = SliverMultiBoxAdaptorElement(); sliverMultiBoxAdaptorElement.insertChildRenderObject(renderObject, object); sliverMultiBoxAdaptorElement.moveChildRenderObject(renderObject, object); sliverMultiBoxAdaptorElement.removeChildRenderObject(renderObject); final RenderObjectToWidgetElement renderObjectToWidgetElement = RenderObjectToWidgetElement(widget); renderObjectToWidgetElement.insertChildRenderObject(renderObject, object); renderObjectToWidgetElement.moveChildRenderObject(renderObject, object); renderObjectToWidgetElement.removeChildRenderObject(renderObject); // Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior ListWheelViewport listWheelViewport = ListWheelViewport(); listWheelViewport = ListWheelViewport(clipToSize: true); listWheelViewport = ListWheelViewport(clipToSize: false); listWheelViewport = ListWheelViewport(error: ''); listWheelViewport.clipToSize; // Changes made in https://github.com/flutter/flutter/pull/87839 final OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(leading: true); final OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(error: ''); notification.disallowGlow(); // Changes made in https://github.com/flutter/flutter/pull/96957 RawScrollbar rawScrollbar = RawScrollbar(isAlwaysShown: true); nowShowing = rawScrollbar.isAlwaysShown; // Change made in https://github.com/flutter/flutter/pull/100381 TextSelectionOverlay.fadeDuration; // Changes made in https://github.com/flutter/flutter/pull/78588 final ScrollBehavior scrollBehavior = ScrollBehavior(); scrollBehavior.buildViewportChrome(context, child, axisDirection); // Changes made in https://github.com/flutter/flutter/pull/114459 MediaQuery.boldTextOverride(context); // Changes made in https://github.com/flutter/flutter/pull/122555 final ScrollableDetails details = ScrollableDetails( direction: AxisDirection.down, clipBehavior: Clip.none, ); final Clip clip = details.clipBehavior; final PlatformMenuBar platformMenuBar = PlatformMenuBar(menus: <PlatformMenuItem>[], body: const SizedBox()); final Widget bodyValue = platformMenuBar.body; // Changes made in TBD final NavigatorState state = Navigator.of(context); state.focusScopeNode; }
flutter/packages/flutter/test_fixes/widgets/widgets.dart/0
{ "file_path": "flutter/packages/flutter/test_fixes/widgets/widgets.dart", "repo_id": "flutter", "token_count": 2458 }
706
// 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/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final FlutterMemoryAllocations ma = FlutterMemoryAllocations.instance; setUp(() { assert(!ma.hasListeners); }); testWidgets( '$FlutterMemoryAllocations is noop when kFlutterMemoryAllocationsEnabled is false.', (WidgetTester tester) async { ObjectEvent? receivedEvent; ObjectEvent listener(ObjectEvent event) => receivedEvent = event; ma.addListener(listener); expect(ma.hasListeners, isFalse); await _activateFlutterObjects(tester); expect(receivedEvent, isNull); expect(ma.hasListeners, isFalse); ma.removeListener(listener); }, ); } class _TestLeafRenderObjectWidget extends LeafRenderObjectWidget { @override RenderObject createRenderObject(BuildContext context) { return _TestRenderObject(); } } class _TestRenderObject extends RenderObject { @override void debugAssertDoesMeetConstraints() {} @override Rect get paintBounds => throw UnimplementedError(); @override void performLayout() {} @override void performResize() {} @override Rect get semanticBounds => throw UnimplementedError(); } class _TestElement extends RenderTreeRootElement with RootElementMixin { _TestElement(): super(_TestLeafRenderObjectWidget()); void makeInactive() { assignOwner(BuildOwner(focusManager: FocusManager())); mount(null, null); deactivate(); } @override void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } @override void moveRenderObjectChild(covariant RenderObject child, covariant Object? oldSlot, covariant Object? newSlot) { } @override void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } } class _MyStatefulWidget extends StatefulWidget { const _MyStatefulWidget(); @override State<_MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<_MyStatefulWidget> { @override Widget build(BuildContext context) { return Container(); } } /// Create and dispose Flutter objects to fire memory allocation events. Future<void> _activateFlutterObjects(WidgetTester tester) async { final _TestElement element = _TestElement(); element.makeInactive(); element.unmount(); // Create and dispose State: await tester.pumpWidget(const _MyStatefulWidget()); await tester.pumpWidget(const SizedBox.shrink()); }
flutter/packages/flutter/test_release/widgets/memory_allocations_test.dart/0
{ "file_path": "flutter/packages/flutter/test_release/widgets/memory_allocations_test.dart", "repo_id": "flutter", "token_count": 836 }
707
// 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 'find.dart'; /// A Flutter Driver command that taps on a target widget located by [finder]. class Tap extends CommandWithTarget { /// Creates a tap command to tap on a widget located by [finder]. Tap(super.finder, { super.timeout }); /// Deserializes this command from the value generated by [serialize]. Tap.deserialize(super.json, super.finderFactory) : super.deserialize(); @override String get kind => 'tap'; } /// A Flutter Driver command that commands the driver to perform a scrolling action. class Scroll extends CommandWithTarget { /// Creates a scroll command that will attempt to scroll a scrollable view by /// dragging a widget located by the given [finder]. Scroll( super.finder, this.dx, this.dy, this.duration, this.frequency, { super.timeout, }); /// Deserializes this command from the value generated by [serialize]. Scroll.deserialize(super.json, super.finderFactory) : dx = double.parse(json['dx']!), dy = double.parse(json['dy']!), duration = Duration(microseconds: int.parse(json['duration']!)), frequency = int.parse(json['frequency']!), super.deserialize(); /// Delta X offset per move event. final double dx; /// Delta Y offset per move event. final double dy; /// The duration of the scrolling action. final Duration duration; /// The frequency in Hz of the generated move events. final int frequency; @override String get kind => 'scroll'; @override Map<String, String> serialize() => super.serialize()..addAll(<String, String>{ 'dx': '$dx', 'dy': '$dy', 'duration': '${duration.inMicroseconds}', 'frequency': '$frequency', }); } /// A Flutter Driver command that commands the driver to ensure that the element /// represented by [finder] has been scrolled completely into view. class ScrollIntoView extends CommandWithTarget { /// Creates this command given a [finder] used to locate the widget to be /// scrolled into view. ScrollIntoView(super.finder, { this.alignment = 0.0, super.timeout }); /// Deserializes this command from the value generated by [serialize]. ScrollIntoView.deserialize(super.json, super.finderFactory) : alignment = double.parse(json['alignment']!), super.deserialize(); /// How the widget should be aligned. /// /// This value is passed to [Scrollable.ensureVisible] as the value of its /// argument of the same name. /// /// Defaults to 0.0. final double alignment; @override String get kind => 'scrollIntoView'; @override Map<String, String> serialize() => super.serialize()..addAll(<String, String>{ 'alignment': '$alignment', }); }
flutter/packages/flutter_driver/lib/src/common/gesture.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/common/gesture.dart", "repo_id": "flutter", "token_count": 855 }
708
// 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 'percentile_utils.dart'; import 'timeline.dart'; /// Summarizes GPU/Device Memory allocations performed by Impeller. class GPUMemorySumarizer { /// Creates a RasterCacheSummarizer given the timeline events. GPUMemorySumarizer(List<TimelineEvent> gpuEvents) { for (final TimelineEvent event in gpuEvents) { final Object? value = event.arguments!['MemoryBudgetUsageMB']; if (value is String) { final double? parsedValue = double.tryParse(value); if (parsedValue != null) { _memoryMB.add(parsedValue); } } } } /// Whether or not this event is a GPU allocation event. static const Set<String> kMemoryEvents = <String>{'AllocatorVK'}; final List<double> _memoryMB = <double>[]; /// Computes the average GPU memory allocated. double computeAverageMemoryUsage() => _computeAverage(_memoryMB); /// The [percentile]-th percentile GPU memory allocated. double computePercentileMemoryUsage(double percentile) { if (_memoryMB.isEmpty) { return 0; } return findPercentile(_memoryMB, percentile); } /// Compute the worst allocation quantity recorded. double computeWorstMemoryUsage() => _computeWorst(_memoryMB); static double _computeAverage(List<double> values) { if (values.isEmpty) { return 0; } double total = 0; for (final double data in values) { total += data; } return total / values.length; } static double _computeWorst(List<double> values) { if (values.isEmpty) { return 0; } values.sort(); return values.last; } }
flutter/packages/flutter_driver/lib/src/driver/memory_summarizer.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/driver/memory_summarizer.dart", "repo_id": "flutter", "token_count": 600 }
709
// 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 'dart:io'; import 'package:flutter_driver/src/common/error.dart'; import 'package:test/test.dart'; export 'package:test/fake.dart'; export 'package:test/test.dart'; void tryToDelete(Directory directory) { // This should not be necessary, but it turns out that // on Windows it's common for deletions to fail due to // bogus (we think) "access denied" errors. try { directory.deleteSync(recursive: true); } on FileSystemException catch (error) { driverLog('test', 'Failed to delete ${directory.path}: $error'); } } /// Matcher for functions that throw [DriverError]. final Matcher throwsDriverError = throwsA(isA<DriverError>());
flutter/packages/flutter_driver/test/common.dart/0
{ "file_path": "flutter/packages/flutter_driver/test/common.dart", "repo_id": "flutter", "token_count": 249 }
710
// 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_driver/src/common/error.dart'; import 'package:flutter_driver/src/common/health.dart'; import 'package:flutter_driver/src/driver/web_driver.dart'; import 'package:webdriver/async_io.dart'; import '../../common.dart'; void main() { group('WebDriver', () { late FakeFlutterWebConnection fakeConnection; late WebFlutterDriver driver; setUp(() { fakeConnection = FakeFlutterWebConnection(); driver = WebFlutterDriver.connectedTo(fakeConnection); }); test('sendCommand succeeds', () async { fakeConnection.fakeResponse = ''' { "isError": false, "response": { "test": "hello" } } '''; final Map<String, Object?> response = await driver.sendCommand(const GetHealth()); expect(response['test'], 'hello'); }); test('sendCommand fails on communication error', () async { fakeConnection.communicationError = Error(); expect( () => driver.sendCommand(const GetHealth()), _throwsDriverErrorWithMessage( 'FlutterDriver command GetHealth failed due to a remote error.\n' 'Command sent: {"command":"get_health"}' ), ); }); test('sendCommand fails on null', () async { fakeConnection.fakeResponse = null; expect( () => driver.sendCommand(const GetHealth()), _throwsDriverErrorWithDataString('Null', 'null'), ); }); test('sendCommand fails when response data is not a string', () async { fakeConnection.fakeResponse = 1234; expect( () => driver.sendCommand(const GetHealth()), _throwsDriverErrorWithDataString('int', '1234'), ); }); test('sendCommand fails when isError is true', () async { fakeConnection.fakeResponse = ''' { "isError": true, "response": "test error message" } '''; expect( () => driver.sendCommand(const GetHealth()), _throwsDriverErrorWithMessage( 'Error in Flutter application: test error message' ), ); }); test('sendCommand fails when isError is not bool', () async { fakeConnection.fakeResponse = '{ "isError": 5 }'; expect( () => driver.sendCommand(const GetHealth()), _throwsDriverErrorWithDataString('String', '{ "isError": 5 }'), ); }); test('sendCommand fails when "response" field is not a JSON map', () async { fakeConnection.fakeResponse = '{ "response": 5 }'; expect( () => driver.sendCommand(const GetHealth()), _throwsDriverErrorWithDataString('String', '{ "response": 5 }'), ); }); }); } Matcher _throwsDriverErrorWithMessage(String expectedMessage) { return throwsA(allOf( isA<DriverError>(), predicate<DriverError>((DriverError error) { final String actualMessage = error.message; return actualMessage == expectedMessage; }, 'contains message: $expectedMessage'), )); } Matcher _throwsDriverErrorWithDataString(String dataType, String dataString) { return _throwsDriverErrorWithMessage( 'Received malformed response from the FlutterDriver extension.\n' 'Expected a JSON map containing a "response" field and, optionally, an ' '"isError" field, but got $dataType: $dataString' ); } class FakeFlutterWebConnection implements FlutterWebConnection { @override bool supportsTimelineAction = false; @override Future<void> close() async {} @override Stream<LogEntry> get logs => throw UnimplementedError(); @override Future<List<int>> screenshot() { throw UnimplementedError(); } Object? fakeResponse; Error? communicationError; @override Future<Object?> sendCommand(String script, Duration? duration) async { if (communicationError != null) { throw communicationError!; } return fakeResponse; } }
flutter/packages/flutter_driver/test/src/web_tests/web_driver_test.dart/0
{ "file_path": "flutter/packages/flutter_driver/test/src/web_tests/web_driver_test.dart", "repo_id": "flutter", "token_count": 1397 }
711
// 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. // See also dev/automated_tests/flutter_test/flutter_gold_test.dart import 'dart:convert'; import 'dart:ffi' show Abi; import 'dart:io' hide Directory; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_goldens/flutter_goldens.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:platform/platform.dart'; import 'package:process/process.dart'; import 'json_templates.dart'; const String _kFlutterRoot = '/flutter'; // 1x1 transparent pixel const List<int> _kTestPngBytes = <int>[ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 11, 73, 68, 65, 84, 120, 1, 99, 97, 0, 2, 0, 0, 25, 0, 5, 144, 240, 54, 245, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, ]; void main() { late MemoryFileSystem fs; late FakePlatform platform; late FakeProcessManager process; late FakeHttpClient fakeHttpClient; setUp(() { fs = MemoryFileSystem(); platform = FakePlatform( environment: <String, String>{'FLUTTER_ROOT': _kFlutterRoot}, operatingSystem: 'macos' ); process = FakeProcessManager(); fakeHttpClient = FakeHttpClient(); fs.directory(_kFlutterRoot).createSync(recursive: true); }); group('SkiaGoldClient', () { late SkiaGoldClient skiaClient; late Directory workDirectory; setUp(() { workDirectory = fs.directory('/workDirectory') ..createSync(recursive: true); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); }); test('web HTML test', () async { platform = FakePlatform( environment: <String, String>{ 'GOLDCTL': 'goldctl', 'FLUTTER_ROOT': _kFlutterRoot, 'FLUTTER_TEST_BROWSER': 'Chrome', 'FLUTTER_WEB_RENDERER': 'html', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); final File goldenFile = fs.file('/workDirectory/temp/golden_file_test.png') ..createSync(recursive: true); const RunInvocation goldctlInvocation = RunInvocation( <String>[ 'goldctl', 'imgtest', 'add', '--work-dir', '/workDirectory/temp', '--test-name', 'golden_file_test', '--png-file', '/workDirectory/temp/golden_file_test.png', '--passfail', '--add-test-optional-key', 'image_matching_algorithm:fuzzy', '--add-test-optional-key', 'fuzzy_max_different_pixels:20', '--add-test-optional-key', 'fuzzy_pixel_delta_threshold:4', ], null, ); process.processResults[goldctlInvocation] = ProcessResult(123, 0, '', ''); expect( await skiaClient.imgtestAdd('golden_file_test.png', goldenFile), isTrue, ); }); test('web CanvasKit test', () async { platform = FakePlatform( environment: <String, String>{ 'GOLDCTL': 'goldctl', 'FLUTTER_ROOT': _kFlutterRoot, 'FLUTTER_TEST_BROWSER': 'Chrome', 'FLUTTER_WEB_RENDERER': 'canvaskit', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); final File goldenFile = fs.file('/workDirectory/temp/golden_file_test.png') ..createSync(recursive: true); const RunInvocation goldctlInvocation = RunInvocation( <String>[ 'goldctl', 'imgtest', 'add', '--work-dir', '/workDirectory/temp', '--test-name', 'golden_file_test', '--png-file', '/workDirectory/temp/golden_file_test.png', '--passfail', ], null, ); process.processResults[goldctlInvocation] = ProcessResult(123, 0, '', ''); expect( await skiaClient.imgtestAdd('golden_file_test.png', goldenFile), isTrue, ); }); test('auth performs minimal work if already authorized', () async { final File authFile = fs.file('/workDirectory/temp/auth_opt.json') ..createSync(recursive: true); authFile.writeAsStringSync(authTemplate()); process.fallbackProcessResult = ProcessResult(123, 0, '', ''); await skiaClient.auth(); expect(process.workingDirectories, isEmpty); }); test('gsutil is checked when authorization file is present', () async { final File authFile = fs.file('/workDirectory/temp/auth_opt.json') ..createSync(recursive: true); authFile.writeAsStringSync(authTemplate(gsutil: true)); expect( await skiaClient.clientIsAuthorized(), isFalse, ); }); test('throws for error state from auth', () async { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLD_SERVICE_ACCOUNT' : 'Service Account', 'GOLDCTL' : 'goldctl', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure'); expect( skiaClient.auth(), throwsException, ); }); test('throws for error state from init', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); const RunInvocation gitInvocation = RunInvocation( <String>['git', 'rev-parse', 'HEAD'], '/flutter', ); const RunInvocation goldctlInvocation = RunInvocation( <String>[ 'goldctl', 'imgtest', 'init', '--instance', 'flutter', '--work-dir', '/workDirectory/temp', '--commit', '12345678', '--keys-file', '/workDirectory/keys.json', '--failure-file', '/workDirectory/failures.json', '--passfail', ], null, ); process.processResults[gitInvocation] = ProcessResult(12345678, 0, '12345678', ''); process.processResults[goldctlInvocation] = ProcessResult(123, 1, 'Expected failure', 'Expected failure'); process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure'); expect( skiaClient.imgtestInit(), throwsException, ); }); test('Only calls init once', () async { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); const RunInvocation gitInvocation = RunInvocation( <String>['git', 'rev-parse', 'HEAD'], '/flutter', ); const RunInvocation goldctlInvocation = RunInvocation( <String>[ 'goldctl', 'imgtest', 'init', '--instance', 'flutter', '--work-dir', '/workDirectory/temp', '--commit', '1234', '--keys-file', '/workDirectory/keys.json', '--failure-file', '/workDirectory/failures.json', '--passfail', ], null, ); process.processResults[gitInvocation] = ProcessResult(1234, 0, '1234', ''); process.processResults[goldctlInvocation] = ProcessResult(5678, 0, '5678', ''); process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure'); // First call await skiaClient.imgtestInit(); // Remove fake process result. // If the init call is executed again, the fallback process will throw. process.processResults.remove(goldctlInvocation); // Second call await skiaClient.imgtestInit(); }); test('Only calls tryjob init once', () async { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', 'SWARMING_TASK_ID' : '4ae997b50dfd4d11', 'LOGDOG_STREAM_PREFIX' : 'buildbucket/cr-buildbucket.appspot.com/8885996262141582672', 'GOLD_TRYJOB' : 'refs/pull/49815/head', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); const RunInvocation gitInvocation = RunInvocation( <String>['git', 'rev-parse', 'HEAD'], '/flutter', ); const RunInvocation goldctlInvocation = RunInvocation( <String>[ 'goldctl', 'imgtest', 'init', '--instance', 'flutter', '--work-dir', '/workDirectory/temp', '--commit', '1234', '--keys-file', '/workDirectory/keys.json', '--failure-file', '/workDirectory/failures.json', '--passfail', '--crs', 'github', '--patchset_id', '1234', '--changelist', '49815', '--cis', 'buildbucket', '--jobid', '8885996262141582672', ], null, ); process.processResults[gitInvocation] = ProcessResult(1234, 0, '1234', ''); process.processResults[goldctlInvocation] = ProcessResult(5678, 0, '5678', ''); process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure'); // First call await skiaClient.tryjobInit(); // Remove fake process result. // If the init call is executed again, the fallback process will throw. process.processResults.remove(goldctlInvocation); // Second call await skiaClient.tryjobInit(); }); test('throws for error state from imgtestAdd', () { final File goldenFile = fs.file('/workDirectory/temp/golden_file_test.png') ..createSync(recursive: true); platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); const RunInvocation goldctlInvocation = RunInvocation( <String>[ 'goldctl', 'imgtest', 'add', '--work-dir', '/workDirectory/temp', '--test-name', 'golden_file_test', '--png-file', '/workDirectory/temp/golden_file_test.png', '--passfail', ], null, ); process.processResults[goldctlInvocation] = ProcessResult(123, 1, 'Expected failure', 'Expected failure'); process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure'); expect( skiaClient.imgtestAdd('golden_file_test', goldenFile), throwsException, ); }); test('correctly inits tryjob for luci', () async { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', 'SWARMING_TASK_ID' : '4ae997b50dfd4d11', 'LOGDOG_STREAM_PREFIX' : 'buildbucket/cr-buildbucket.appspot.com/8885996262141582672', 'GOLD_TRYJOB' : 'refs/pull/49815/head', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); final List<String> ciArguments = skiaClient.getCIArguments(); expect( ciArguments, equals( <String>[ '--changelist', '49815', '--cis', 'buildbucket', '--jobid', '8885996262141582672', ], ), ); }); test('Creates traceID correctly', () async { String traceID; platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', 'SWARMING_TASK_ID' : '4ae997b50dfd4d11', 'LOGDOG_STREAM_PREFIX' : 'buildbucket/cr-buildbucket.appspot.com/8885996262141582672', 'GOLD_TRYJOB' : 'refs/pull/49815/head', }, operatingSystem: 'linux' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, abi: Abi.linuxX64, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); traceID = skiaClient.getTraceID('flutter.golden.1'); expect( traceID, equals('1937c1c93610cc0122a86a83d5bd38a4'), ); // Browser platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', 'SWARMING_TASK_ID' : '4ae997b50dfd4d11', 'LOGDOG_STREAM_PREFIX' : 'buildbucket/cr-buildbucket.appspot.com/8885996262141582672', 'GOLD_TRYJOB' : 'refs/pull/49815/head', 'FLUTTER_TEST_BROWSER' : 'chrome', }, operatingSystem: 'linux' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, abi: Abi.linuxX64, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); traceID = skiaClient.getTraceID('flutter.golden.1'); expect( traceID, equals('bc44a50c01eb3bbaf72a80d76c1c2305'), ); // Locally - should defer to luci traceID platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, abi: Abi.linuxX64, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); traceID = skiaClient.getTraceID('flutter.golden.1'); expect( traceID, equals('8821f4896801fcdd7cd6d30f5a8e4284'), ); }); test('throws for error state from imgtestAdd', () { final File goldenFile = fs.file('/workDirectory/temp/golden_file_test.png') ..createSync(recursive: true); platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); const RunInvocation goldctlInvocation = RunInvocation( <String>[ 'goldctl', 'imgtest', 'add', '--work-dir', '/workDirectory/temp', '--test-name', 'golden_file_test', '--png-file', '/workDirectory/temp/golden_file_test.png', '--passfail', ], null, ); process.processResults[goldctlInvocation] = ProcessResult(123, 1, 'Expected failure', 'Expected failure'); process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure'); expect( skiaClient.imgtestAdd('golden_file_test', goldenFile), throwsA( isA<SkiaException>().having((SkiaException error) => error.message, 'message', contains('result-state.json'), ), ), ); }); test('throws for error state from tryjobAdd', () { final File goldenFile = fs.file('/workDirectory/temp/golden_file_test.png') ..createSync(recursive: true); platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'GOLDCTL' : 'goldctl', }, operatingSystem: 'macos' ); skiaClient = SkiaGoldClient( workDirectory, fs: fs, process: process, platform: platform, httpClient: fakeHttpClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); const RunInvocation goldctlInvocation = RunInvocation( <String>[ 'goldctl', 'imgtest', 'add', '--work-dir', '/workDirectory/temp', '--test-name', 'golden_file_test', '--png-file', '/workDirectory/temp/golden_file_test.png', '--passfail', ], null, ); process.processResults[goldctlInvocation] = ProcessResult(123, 1, 'Expected failure', 'Expected failure'); process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure'); expect( skiaClient.tryjobAdd('golden_file_test', goldenFile), throwsA( isA<SkiaException>().having((SkiaException error) => error.message, 'message', contains('result-state.json'), ), ), ); }); group('Request Handling', () { const String expectation = '55109a4bed52acc780530f7a9aeff6c0'; test('image bytes are processed properly', () async { final Uri imageUrl = Uri.parse( 'https://flutter-gold.skia.org/img/images/$expectation.png' ); final FakeHttpClientRequest fakeImageRequest = FakeHttpClientRequest(); final FakeHttpImageResponse fakeImageResponse = FakeHttpImageResponse( imageResponseTemplate() ); fakeHttpClient.request = fakeImageRequest; fakeImageRequest.response = fakeImageResponse; final List<int> masterBytes = await skiaClient.getImageBytes(expectation); expect(fakeHttpClient.lastUri, imageUrl); expect(masterBytes, equals(_kTestPngBytes)); }); }); }); group('FlutterGoldenFileComparator', () { final List<String> log = <String>[]; late FlutterGoldenFileComparator comparator; setUp(() { log.clear(); // TODO(ianh): inline the setup into the tests to avoid risk of accidental bleed-through final Directory basedir = fs.directory('flutter/test/library/') ..createSync(recursive: true); comparator = FlutterPostSubmitFileComparator( basedir.uri, FakeSkiaGoldClient(), fs: fs, platform: platform, log: log.add, ); }); test('calculates the basedir correctly from defaultComparator for local testing', () async { final FakeLocalFileComparator defaultComparator = FakeLocalFileComparator(); final Directory flutterRoot = fs.directory(platform.environment['FLUTTER_ROOT']) ..createSync(recursive: true); defaultComparator.basedir = flutterRoot.childDirectory('baz').uri; final Directory basedir = FlutterGoldenFileComparator.getBaseDirectory( defaultComparator, platform, ); expect( basedir.uri, fs.directory('/flutter/bin/cache/pkg/skia_goldens/baz').uri, ); }); test('ignores version number', () { final Uri key = comparator.getTestUri(Uri.parse('foo.png'), 1); expect(key, Uri.parse('foo.png')); expect(log, isEmpty); }); test('adds namePrefix', () async { final List<String> log = <String>[]; const String libraryName = 'sidedishes'; const String namePrefix = 'tomatosalad'; const String fileName = 'lettuce.png'; final FakeSkiaGoldClient fakeSkiaClient = FakeSkiaGoldClient(); final Directory basedir = fs.directory('flutter/test/$libraryName/') ..createSync(recursive: true); final FlutterGoldenFileComparator comparator = FlutterPostSubmitFileComparator( basedir.uri, fakeSkiaClient, fs: fs, platform: platform, namePrefix: namePrefix, log: log.add, ); await comparator.compare( Uint8List.fromList(_kTestPngBytes), Uri.parse(fileName), ); expect(fakeSkiaClient.testNames.single, '$namePrefix.$libraryName.$fileName'); expect(log, isEmpty); }); group('Post-Submit', () { final List<String> log = <String>[]; late FakeSkiaGoldClient fakeSkiaClient; setUp(() { log.clear(); // TODO(ianh): inline the setup into the tests to avoid risk of accidental bleed-through fakeSkiaClient = FakeSkiaGoldClient(); final Directory basedir = fs.directory('flutter/test/library/') ..createSync(recursive: true); comparator = FlutterPostSubmitFileComparator( basedir.uri, fakeSkiaClient, fs: fs, platform: platform, log: log.add, ); }); test('asserts .png format', () async { await expectLater( () async { return comparator.compare( Uint8List.fromList(_kTestPngBytes), Uri.parse('flutter.golden_test.1'), ); }, throwsA( isA<AssertionError>().having((AssertionError error) => error.toString(), 'description', contains( 'Golden files in the Flutter framework must end with the file ' 'extension .png.' ), ), ), ); expect(log, isEmpty); }); test('calls init during compare', () { expect(fakeSkiaClient.initCalls, 0); comparator.compare( Uint8List.fromList(_kTestPngBytes), Uri.parse('flutter.golden_test.1.png'), ); expect(fakeSkiaClient.initCalls, 1); expect(log, isEmpty); }); test('does not call init in during construction', () { expect(fakeSkiaClient.initCalls, 0); FlutterPostSubmitFileComparator.fromDefaultComparator( platform, goldens: fakeSkiaClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); expect(fakeSkiaClient.initCalls, 0); }); group('correctly determines testing environment', () { test('returns true for configured Luci', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : '12345678990', 'GOLDCTL' : 'goldctl', 'GIT_BRANCH' : 'master', }, operatingSystem: 'macos', ); expect( FlutterPostSubmitFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns false on release branches in postsubmit', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : 'sweet task ID', 'GOLDCTL' : 'some/path', 'GIT_BRANCH' : 'flutter-3.16-candidate.0', }, operatingSystem: 'macos', ); expect( FlutterPostSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); test('returns true on master branch in postsubmit', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : 'sweet task ID', 'GOLDCTL' : 'some/path', 'GIT_BRANCH' : 'master', }, operatingSystem: 'macos', ); expect( FlutterPostSubmitFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns true on main branch in postsubmit', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : 'sweet task ID', 'GOLDCTL' : 'some/path', 'GIT_BRANCH' : 'main', }, operatingSystem: 'macos', ); expect( FlutterPostSubmitFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns false - GOLDCTL not present', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : '12345678990', }, operatingSystem: 'macos', ); expect( FlutterPostSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); test('returns false - GOLD_TRYJOB active', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : '12345678990', 'GOLDCTL' : 'goldctl', 'GOLD_TRYJOB' : 'git/ref/12345/head', }, operatingSystem: 'macos', ); expect( FlutterPostSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); test('returns false - on Cirrus', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'CIRRUS_CI': 'true', 'CIRRUS_PR': '', 'CIRRUS_BRANCH': 'master', 'GOLD_SERVICE_ACCOUNT': 'service account...', }, operatingSystem: 'macos', ); expect( FlutterPostSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); }); }); group('Pre-Submit', () { final List<String> log = <String>[]; late FakeSkiaGoldClient fakeSkiaClient; setUp(() { log.clear(); // TODO(ianh): inline the setup into the tests to avoid risk of accidental bleed-through fakeSkiaClient = FakeSkiaGoldClient(); final Directory basedir = fs.directory('flutter/test/library/') ..createSync(recursive: true); comparator = FlutterPreSubmitFileComparator( basedir.uri, fakeSkiaClient, fs: fs, platform: platform, log: log.add, ); }); test('asserts .png format', () async { await expectLater( () async { return comparator.compare( Uint8List.fromList(_kTestPngBytes), Uri.parse('flutter.golden_test.1'), ); }, throwsA( isA<AssertionError>().having((AssertionError error) => error.toString(), 'description', contains( 'Golden files in the Flutter framework must end with the file ' 'extension .png.' ), ), ), ); expect(log, isEmpty); }); test('calls init during compare', () { expect(fakeSkiaClient.tryInitCalls, 0); comparator.compare( Uint8List.fromList(_kTestPngBytes), Uri.parse('flutter.golden_test.1.png'), ); expect(fakeSkiaClient.tryInitCalls, 1); expect(log, isEmpty); }); test('does not call init in during construction', () { expect(fakeSkiaClient.tryInitCalls, 0); FlutterPostSubmitFileComparator.fromDefaultComparator( platform, goldens: fakeSkiaClient, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); expect(fakeSkiaClient.tryInitCalls, 0); }); group('correctly determines testing environment', () { test('returns false on release branches in presubmit', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : 'sweet task ID', 'GOLDCTL' : 'some/path', 'GOLD_TRYJOB' : 'true', 'GIT_BRANCH' : 'flutter-3.16-candidate.0', }, operatingSystem: 'macos', ); expect( FlutterPreSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); test('returns true on master branch in presubmit', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : 'sweet task ID', 'GOLDCTL' : 'some/path', 'GOLD_TRYJOB' : 'true', 'GIT_BRANCH' : 'master', }, operatingSystem: 'macos', ); expect( FlutterPreSubmitFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns true on main branch in presubmit', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : 'sweet task ID', 'GOLDCTL' : 'some/path', 'GOLD_TRYJOB' : 'true', 'GIT_BRANCH' : 'main', }, operatingSystem: 'macos', ); expect( FlutterPreSubmitFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns true for Luci', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : '12345678990', 'GOLDCTL' : 'goldctl', 'GOLD_TRYJOB' : 'git/ref/12345/head', 'GIT_BRANCH' : 'master', }, operatingSystem: 'macos', ); expect( FlutterPreSubmitFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns false - not on Luci', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, }, operatingSystem: 'macos', ); expect( FlutterPreSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); test('returns false - GOLDCTL missing', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : '12345678990', 'GOLD_TRYJOB' : 'git/ref/12345/head', }, operatingSystem: 'macos', ); expect( FlutterPreSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); test('returns false - GOLD_TRYJOB missing', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : '12345678990', 'GOLDCTL' : 'goldctl', }, operatingSystem: 'macos', ); expect( FlutterPreSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); test('returns false - on Cirrus', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'CIRRUS_CI': 'true', 'CIRRUS_PR': '', 'CIRRUS_BRANCH': 'master', 'GOLD_SERVICE_ACCOUNT': 'service account...', }, operatingSystem: 'macos', ); expect( FlutterPostSubmitFileComparator.isForEnvironment(platform), isFalse, ); }); }); }); group('Skipping', () { group('correctly determines testing environment', () { test('returns true on release branches in presubmit', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : 'sweet task ID', 'GOLDCTL' : 'some/path', 'GOLD_TRYJOB' : 'true', 'GIT_BRANCH' : 'flutter-3.16-candidate.0', }, operatingSystem: 'macos', ); expect( FlutterSkippingFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns true on release branches in postsubmit', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : 'sweet task ID', 'GOLDCTL' : 'some/path', 'GIT_BRANCH' : 'flutter-3.16-candidate.0', }, operatingSystem: 'macos', ); expect( FlutterSkippingFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns true on Cirrus builds', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'CIRRUS_CI' : 'yep', }, operatingSystem: 'macos', ); expect( FlutterSkippingFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns true on irrelevant LUCI builds', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, 'SWARMING_TASK_ID' : '1234567890', }, operatingSystem: 'macos' ); expect( FlutterSkippingFileComparator.isForEnvironment(platform), isTrue, ); }); test('returns false - not in CI', () { platform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': _kFlutterRoot, }, operatingSystem: 'macos', ); expect( FlutterSkippingFileComparator.isForEnvironment(platform), isFalse, ); }); }); }); group('Local', () { final List<String> log = <String>[]; late FlutterLocalFileComparator comparator; final FakeSkiaGoldClient fakeSkiaClient = FakeSkiaGoldClient(); setUp(() async { log.clear(); // TODO(ianh): inline the setup into the tests to avoid risk of accidental bleed-through final Directory basedir = fs.directory('flutter/test/library/') ..createSync(recursive: true); comparator = FlutterLocalFileComparator( basedir.uri, fakeSkiaClient, fs: fs, platform: FakePlatform( environment: <String, String>{'FLUTTER_ROOT': _kFlutterRoot}, operatingSystem: 'macos', ), log: log.add, ); const String hash = '55109a4bed52acc780530f7a9aeff6c0'; fakeSkiaClient.expectationForTestValues['flutter.golden_test.1'] = hash; fakeSkiaClient.imageBytesValues[hash] =_kTestPngBytes; fakeSkiaClient.cleanTestNameValues['library.flutter.golden_test.1.png'] = 'flutter.golden_test.1'; }); test('asserts .png format', () async { await expectLater( () async { return comparator.compare( Uint8List.fromList(_kTestPngBytes), Uri.parse('flutter.golden_test.1'), ); }, throwsA( isA<AssertionError>().having((AssertionError error) => error.toString(), 'description', contains( 'Golden files in the Flutter framework must end with the file ' 'extension .png.' ), ), ), ); expect(log, isEmpty); }); test('passes when bytes match', () async { expect( await comparator.compare( Uint8List.fromList(_kTestPngBytes), Uri.parse('flutter.golden_test.1.png'), ), isTrue, ); expect(log, isEmpty); }); test('returns FlutterSkippingGoldenFileComparator when network connection is unavailable', () async { final FakeDirectory fakeDirectory = FakeDirectory(); fakeDirectory.existsSyncValue = true; fakeDirectory.uri = Uri.parse('/flutter'); fakeSkiaClient.getExpectationForTestThrowable = const OSError("Can't reach Gold"); FlutterGoldenFileComparator comparator = await FlutterLocalFileComparator.fromDefaultComparator( platform, goldens: fakeSkiaClient, baseDirectory: fakeDirectory, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); expect(comparator.runtimeType, FlutterSkippingFileComparator); fakeSkiaClient.getExpectationForTestThrowable = const SocketException("Can't reach Gold"); comparator = await FlutterLocalFileComparator.fromDefaultComparator( platform, goldens: fakeSkiaClient, baseDirectory: fakeDirectory, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); expect(comparator.runtimeType, FlutterSkippingFileComparator); fakeSkiaClient.getExpectationForTestThrowable = const FormatException("Can't reach Gold"); comparator = await FlutterLocalFileComparator.fromDefaultComparator( platform, goldens: fakeSkiaClient, baseDirectory: fakeDirectory, log: (String message) => fail('skia gold client printed unexpected output: "$message"'), ); expect(comparator.runtimeType, FlutterSkippingFileComparator); // reset property or it will carry on to other tests fakeSkiaClient.getExpectationForTestThrowable = null; }); }); }); } @immutable class RunInvocation { const RunInvocation(this.command, this.workingDirectory); final List<String> command; final String? workingDirectory; @override int get hashCode => Object.hash(Object.hashAll(command), workingDirectory); bool _commandEquals(List<String> other) { if (other == command) { return true; } if (other.length != command.length) { return false; } for (int index = 0; index < other.length; index += 1) { if (other[index] != command[index]) { return false; } } return true; } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is RunInvocation && _commandEquals(other.command) && other.workingDirectory == workingDirectory; } @override String toString() => '$command ($workingDirectory)'; } class FakeProcessManager extends Fake implements ProcessManager { Map<RunInvocation, ProcessResult> processResults = <RunInvocation, ProcessResult>{}; /// Used if [processResults] does not contain a matching invocation. ProcessResult? fallbackProcessResult; final List<String?> workingDirectories = <String?>[]; @override Future<ProcessResult> run( List<Object> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding, }) async { workingDirectories.add(workingDirectory); final ProcessResult? result = processResults[RunInvocation(command.cast<String>(), workingDirectory)]; if (result == null && fallbackProcessResult == null) { printOnFailure('ProcessManager.run was called with $command ($workingDirectory) unexpectedly - $processResults.'); fail('See above.'); } return result ?? fallbackProcessResult!; } } // See also dev/automated_tests/flutter_test/flutter_gold_test.dart class FakeSkiaGoldClient extends Fake implements SkiaGoldClient { Map<String, String> expectationForTestValues = <String, String>{}; Exception? getExpectationForTestThrowable; @override Future<String> getExpectationForTest(String testName) async { if (getExpectationForTestThrowable != null) { throw getExpectationForTestThrowable!; } return expectationForTestValues[testName] ?? ''; } @override Future<void> auth() async {} final List<String> testNames = <String>[]; int initCalls = 0; @override Future<void> imgtestInit() async => initCalls += 1; @override Future<bool> imgtestAdd(String testName, File goldenFile) async { testNames.add(testName); return true; } int tryInitCalls = 0; @override Future<void> tryjobInit() async => tryInitCalls += 1; @override Future<bool> tryjobAdd(String testName, File goldenFile) async => true; Map<String, List<int>> imageBytesValues = <String, List<int>>{}; @override Future<List<int>> getImageBytes(String imageHash) async => imageBytesValues[imageHash]!; Map<String, String> cleanTestNameValues = <String, String>{}; @override String cleanTestName(String fileName) => cleanTestNameValues[fileName] ?? ''; } class FakeLocalFileComparator extends Fake implements LocalFileComparator { @override late Uri basedir; } class FakeDirectory extends Fake implements Directory { late bool existsSyncValue; @override bool existsSync() => existsSyncValue; @override late Uri uri; } class FakeHttpClient extends Fake implements HttpClient { late Uri lastUri; late FakeHttpClientRequest request; @override Future<HttpClientRequest> getUrl(Uri url) async { lastUri = url; return request; } } class FakeHttpClientRequest extends Fake implements HttpClientRequest { late FakeHttpImageResponse response; @override Future<HttpClientResponse> close() async { return response; } } class FakeHttpImageResponse extends Fake implements HttpClientResponse { FakeHttpImageResponse(this.response); final List<List<int>> response; @override Future<void> forEach(void Function(List<int> element) action) async { response.forEach(action); } }
flutter/packages/flutter_goldens/test/flutter_goldens_test.dart/0
{ "file_path": "flutter/packages/flutter_goldens/test/flutter_goldens_test.dart", "repo_id": "flutter", "token_count": 20262 }
712
{ "datePickerHourSemanticsLabelFew": "$hour hodiny", "datePickerHourSemanticsLabelMany": "$hour hodiny", "datePickerMinuteSemanticsLabelFew": "$minute minuty", "datePickerMinuteSemanticsLabelMany": "$minute minuty", "timerPickerHourLabelFew": "hodiny", "timerPickerHourLabelMany": "hodiny", "timerPickerMinuteLabelFew": "min", "timerPickerMinuteLabelMany": "min", "timerPickerSecondLabelFew": "s", "timerPickerSecondLabelMany": "s", "datePickerHourSemanticsLabelOne": "$hour hodina", "datePickerHourSemanticsLabelOther": "$hour hodin", "datePickerMinuteSemanticsLabelOne": "1 minuta", "datePickerMinuteSemanticsLabelOther": "$minute minut", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Dnes", "alertDialogLabel": "Upozornění", "timerPickerHourLabelOne": "hodina", "timerPickerHourLabelOther": "hodin", "timerPickerMinuteLabelOne": "min", "timerPickerMinuteLabelOther": "min", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Vyjmout", "copyButtonLabel": "Kopírovat", "pasteButtonLabel": "Vložit", "clearButtonLabel": "Clear", "selectAllButtonLabel": "Vybrat vše", "tabSemanticsLabel": "Karta $tabIndex z $tabCount", "modalBarrierDismissLabel": "Zavřít", "searchTextFieldPlaceholderLabel": "Hledat", "noSpellCheckReplacementsLabel": "Žádná nahrazení nenalezena", "menuDismissLabel": "Zavřít nabídku", "lookUpButtonLabel": "Vyhledat", "searchWebButtonLabel": "Vyhledávat na webu", "shareButtonLabel": "Sdílet…" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_cs.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_cs.arb", "repo_id": "flutter", "token_count": 621 }
713
{ "datePickerHourSemanticsLabelFew": "$hour sata", "datePickerMinuteSemanticsLabelFew": "$minute minute", "timerPickerHourLabelFew": "sata", "timerPickerMinuteLabelFew": "min", "timerPickerSecondLabelFew": "s", "datePickerHourSemanticsLabelOne": "$hour sat", "datePickerHourSemanticsLabelOther": "$hour sati", "datePickerMinuteSemanticsLabelOne": "Jedna minuta", "datePickerMinuteSemanticsLabelOther": "$minute minuta", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "prijepodne", "postMeridiemAbbreviation": "popodne", "todayLabel": "Danas", "alertDialogLabel": "Upozorenje", "timerPickerHourLabelOne": "sat", "timerPickerHourLabelOther": "sati", "timerPickerMinuteLabelOne": "min", "timerPickerMinuteLabelOther": "min", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Izreži", "copyButtonLabel": "Kopiraj", "pasteButtonLabel": "Zalijepi", "selectAllButtonLabel": "Odaberi sve", "tabSemanticsLabel": "Kartica $tabIndex od $tabCount", "modalBarrierDismissLabel": "Odbaci", "searchTextFieldPlaceholderLabel": "Pretraživanje", "noSpellCheckReplacementsLabel": "Nema pronađenih zamjena", "menuDismissLabel": "Odbacivanje izbornika", "lookUpButtonLabel": "Pogled prema gore", "searchWebButtonLabel": "Pretraži web", "shareButtonLabel": "Dijeli...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_hr.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_hr.arb", "repo_id": "flutter", "token_count": 534 }
714
{ "datePickerHourSemanticsLabelOne": "$hour часот", "datePickerHourSemanticsLabelOther": "$hour часот", "datePickerMinuteSemanticsLabelOne": "1 минута", "datePickerMinuteSemanticsLabelOther": "$minute минути", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "ПРЕТПЛАДНЕ", "postMeridiemAbbreviation": "ПОПЛАДНЕ", "todayLabel": "Денес", "alertDialogLabel": "Предупредување", "timerPickerHourLabelOne": "час", "timerPickerHourLabelOther": "часа", "timerPickerMinuteLabelOne": "мин.", "timerPickerMinuteLabelOther": "мин.", "timerPickerSecondLabelOne": "сек.", "timerPickerSecondLabelOther": "сек.", "cutButtonLabel": "Исечи", "copyButtonLabel": "Копирај", "pasteButtonLabel": "Залепи", "selectAllButtonLabel": "Избери ги сите", "tabSemanticsLabel": "Картичка $tabIndex од $tabCount", "modalBarrierDismissLabel": "Отфрли", "searchTextFieldPlaceholderLabel": "Пребарувајте", "noSpellCheckReplacementsLabel": "Не се најдени заменски зборови", "menuDismissLabel": "Отфрлете го менито", "lookUpButtonLabel": "Погледнете нагоре", "searchWebButtonLabel": "Пребарајте на интернет", "shareButtonLabel": "Споделете...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_mk.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_mk.arb", "repo_id": "flutter", "token_count": 650 }
715
{ "datePickerHourSemanticsLabelFew": "$hour часа", "datePickerHourSemanticsLabelMany": "$hour часов", "datePickerMinuteSemanticsLabelFew": "$minute минуты", "datePickerMinuteSemanticsLabelMany": "$minute минут", "timerPickerHourLabelFew": "часа", "timerPickerHourLabelMany": "часов", "timerPickerMinuteLabelFew": "мин.", "timerPickerMinuteLabelMany": "мин.", "timerPickerSecondLabelFew": "сек.", "timerPickerSecondLabelMany": "сек.", "datePickerHourSemanticsLabelOne": "$hour час", "datePickerHourSemanticsLabelOther": "$hour часа", "datePickerMinuteSemanticsLabelOne": "1 минута", "datePickerMinuteSemanticsLabelOther": "$minute минуты", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "АМ", "postMeridiemAbbreviation": "PM", "todayLabel": "Сегодня", "alertDialogLabel": "Оповещение", "timerPickerHourLabelOne": "час", "timerPickerHourLabelOther": "часа", "timerPickerMinuteLabelOne": "мин.", "timerPickerMinuteLabelOther": "мин.", "timerPickerSecondLabelOne": "сек.", "timerPickerSecondLabelOther": "сек.", "cutButtonLabel": "Вырезать", "copyButtonLabel": "Копировать", "pasteButtonLabel": "Вставить", "selectAllButtonLabel": "Выбрать все", "tabSemanticsLabel": "Вкладка $tabIndex из $tabCount", "modalBarrierDismissLabel": "Закрыть", "searchTextFieldPlaceholderLabel": "Поиск", "noSpellCheckReplacementsLabel": "Варианты замены не найдены", "menuDismissLabel": "Закрыть меню", "lookUpButtonLabel": "Найти", "searchWebButtonLabel": "Искать в интернете", "shareButtonLabel": "Поделиться", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ru.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ru.arb", "repo_id": "flutter", "token_count": 762 }
716
{ "datePickerHourSemanticsLabelOne": "$hour soat", "datePickerHourSemanticsLabelOther": "$hour soat", "datePickerMinuteSemanticsLabelOne": "1 daqiqa", "datePickerMinuteSemanticsLabelOther": "$minute daqiqa", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Bugun", "alertDialogLabel": "Ogohlantirish", "timerPickerHourLabelOne": "soat", "timerPickerHourLabelOther": "soat", "timerPickerMinuteLabelOne": "daqiqa", "timerPickerMinuteLabelOther": "daqiqa", "timerPickerSecondLabelOne": "soniya", "timerPickerSecondLabelOther": "soniya", "cutButtonLabel": "Kesib olish", "copyButtonLabel": "Nusxa olish", "pasteButtonLabel": "Joylash", "selectAllButtonLabel": "Barchasini tanlash", "tabSemanticsLabel": "$tabCount varaqdan $tabIndex", "modalBarrierDismissLabel": "Yopish", "searchTextFieldPlaceholderLabel": "Qidiruv", "noSpellCheckReplacementsLabel": "Almashtirish uchun soʻz topilmadi", "menuDismissLabel": "Menyuni yopish", "lookUpButtonLabel": "Tepaga qarang", "searchWebButtonLabel": "Internetdan qidirish", "shareButtonLabel": "Ulashish…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_uz.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_uz.arb", "repo_id": "flutter", "token_count": 456 }
717
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "openAppDrawerTooltip": "Отваряне на менюто за навигация", "backButtonTooltip": "Назад", "closeButtonTooltip": "Затваряне", "deleteButtonTooltip": "Изтриване", "nextMonthTooltip": "Следващият месец", "previousMonthTooltip": "Предишният месец", "nextPageTooltip": "Следващата страница", "firstPageTooltip": "Първа страница", "lastPageTooltip": "Последна страница", "previousPageTooltip": "Предишната страница", "showMenuTooltip": "Показване на менюто", "aboutListTileTitle": "Всичко за $applicationName", "licensesPageTitle": "Лицензи", "pageRowsInfoTitle": "$firstRow – $lastRow от $rowCount", "pageRowsInfoTitleApproximate": "$firstRow – $lastRow от около $rowCount", "rowsPerPageTitle": "Редове на страница:", "tabLabel": "Раздел $tabIndex от $tabCount", "selectedRowCountTitleOne": "Избран е 1 елемент", "selectedRowCountTitleOther": "Избрани са $selectedRowCount елемента", "cancelButtonLabel": "Отказ", "closeButtonLabel": "Затваряне", "continueButtonLabel": "Напред", "copyButtonLabel": "Копиране", "cutButtonLabel": "Изрязване", "scanTextButtonLabel": "Сканирайте текст", "okButtonLabel": "OK", "pasteButtonLabel": "Поставяне", "selectAllButtonLabel": "Избиране на всички", "viewLicensesButtonLabel": "Преглед на лицензите", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Избиране на часове", "timePickerMinuteModeAnnouncement": "Избиране на минути", "modalBarrierDismissLabel": "Отхвърляне", "signedInLabel": "В профила си сте", "hideAccountsLabel": "Скриване на профилите", "showAccountsLabel": "Показване на профилите", "drawerLabel": "Меню за навигация", "popupMenuLabel": "Изскачащо меню", "dialogLabel": "Диалогов прозорец", "alertDialogLabel": "Сигнал", "searchFieldLabel": "Търсене", "reorderItemToStart": "Преместване в началото", "reorderItemToEnd": "Преместване в края", "reorderItemUp": "Преместване нагоре", "reorderItemDown": "Преместване надолу", "reorderItemLeft": "Преместване наляво", "reorderItemRight": "Преместване надясно", "expandedIconTapHint": "Свиване", "collapsedIconTapHint": "Разгъване", "remainingTextFieldCharacterCountOne": "Остава 1 знак", "remainingTextFieldCharacterCountOther": "Остават $remainingCount знака", "refreshIndicatorSemanticLabel": "Опресняване", "moreButtonTooltip": "Още", "dateSeparator": ".", "dateHelpText": "дд.мм.гггг", "selectYearSemanticsLabel": "Избиране на година", "unspecifiedDate": "Дата", "unspecifiedDateRange": "Период от време", "dateInputLabel": "Въвеждане на дата", "dateRangeStartLabel": "Начална дата", "dateRangeEndLabel": "Крайна дата", "dateRangeStartDateSemanticLabel": "Начална дата: $fullDate", "dateRangeEndDateSemanticLabel": "Крайна дата: $fullDate", "invalidDateFormatLabel": "Невалиден формат.", "invalidDateRangeLabel": "Невалиден период от време.", "dateOutOfRangeLabel": "Извън валидния период от време.", "saveButtonLabel": "Запазване", "datePickerHelpText": "Избиране на дата", "dateRangePickerHelpText": "Избиране на период от време", "calendarModeButtonLabel": "Превключване към календара", "inputDateModeButtonLabel": "Превключване към въвеждане", "timePickerDialHelpText": "Избиране на час", "timePickerInputHelpText": "Въведете час", "timePickerHourLabel": "Час", "timePickerMinuteLabel": "Минута", "invalidTimeLabel": "Въведете валиден час", "dialModeButtonLabel": "Превключване към режим за избор на циферблат", "inputTimeModeButtonLabel": "Превключване към режим за въвеждане на текст", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 лиценз", "licensesPackageDetailTextOther": "$licenseCount лиценза", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Power", "keyboardKeyPowerOff": "Power Off", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Space", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Меню на лентата с менюта", "currentDateLabel": "Днес", "scrimLabel": "Скрим", "bottomSheetLabel": "Долен лист", "scrimOnTapHint": "Затваряне на $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "докоснете два пъти за свиване", "expansionTileCollapsedHint": "докоснете два пъти за разгъване", "expansionTileExpandedTapHint": "Свиване", "expansionTileCollapsedTapHint": "Разгъване за още подробности", "expandedHint": "Свито", "collapsedHint": "Разгънато", "menuDismissLabel": "Отхвърляне на менюто", "lookUpButtonLabel": "Look Up", "searchWebButtonLabel": "Търсене в мрежата", "shareButtonLabel": "Споделяне...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_bg.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_bg.arb", "repo_id": "flutter", "token_count": 3376 }
718
{ "searchWebButtonLabel": "Search Web", "shareButtonLabel": "Share...", "scanTextButtonLabel": "Scan text", "lookUpButtonLabel": "Look up", "menuDismissLabel": "Dismiss menu", "expansionTileExpandedHint": "double-tap to collapse", "expansionTileCollapsedHint": "double-tap to expand", "expansionTileExpandedTapHint": "Collapse", "expansionTileCollapsedTapHint": "Expand for more details", "expandedHint": "Collapsed", "collapsedHint": "Expanded", "scrimLabel": "Scrim", "bottomSheetLabel": "Bottom sheet", "scrimOnTapHint": "Close $modalRouteContentName", "currentDateLabel": "Today", "keyboardKeyShift": "Shift", "menuBarMenuLabel": "Menu bar menu", "keyboardKeyNumpad8": "Num 8", "keyboardKeyChannelDown": "Channel down", "keyboardKeyBackspace": "Backspace", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyInsert": "Insert", "keyboardKeyHome": "Home", "keyboardKeyEnd": "End", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyFn": "Fn", "keyboardKeyEscape": "Esc", "keyboardKeyEject": "Eject", "keyboardKeyDelete": "Del", "keyboardKeyControl": "Ctrl", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyChannelUp": "Channel up", "keyboardKeyCapsLock": "Caps lock", "keyboardKeySelect": "Select", "keyboardKeyAltGraph": "AltGr", "keyboardKeyAlt": "Alt", "keyboardKeyMeta": "Meta", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "keyboardKeyNumLock": "Num lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyPageDown": "PgDown", "keyboardKeySpace": "Space", "keyboardKeyNumpad3": "Num 3", "keyboardKeyScrollLock": "Scroll lock", "keyboardKeyNumpad9": "Num 9", "keyboardKeyPrintScreen": "Print screen", "keyboardKeyPowerOff": "Power off", "keyboardKeyPower": "Power", "keyboardKeyPageUp": "PgUp", "keyboardKeyNumpadEnter": "Num enter", "inputTimeModeButtonLabel": "Switch to text input mode", "timePickerDialHelpText": "Select time", "timePickerHourLabel": "Hour", "timePickerMinuteLabel": "Minute", "invalidTimeLabel": "Enter a valid time", "dialModeButtonLabel": "Switch to dial picker mode", "timePickerInputHelpText": "Enter time", "dateSeparator": "/", "dateInputLabel": "Enter date", "calendarModeButtonLabel": "Switch to calendar", "dateRangePickerHelpText": "Select range", "datePickerHelpText": "Select date", "saveButtonLabel": "Save", "dateOutOfRangeLabel": "Out of range.", "invalidDateRangeLabel": "Invalid range.", "invalidDateFormatLabel": "Invalid format.", "dateRangeEndDateSemanticLabel": "End date $fullDate", "dateRangeStartDateSemanticLabel": "Start date $fullDate", "dateRangeEndLabel": "End date", "dateRangeStartLabel": "Start date", "inputDateModeButtonLabel": "Switch to input", "unspecifiedDateRange": "Date range", "unspecifiedDate": "Date", "selectYearSemanticsLabel": "Select year", "dateHelpText": "dd/mm/yyyy", "moreButtonTooltip": "More", "scriptCategory": "English-like", "timeOfDayFormat": "h:mm a", "openAppDrawerTooltip": "Open navigation menu", "backButtonTooltip": "Back", "closeButtonTooltip": "Close", "deleteButtonTooltip": "Delete", "nextMonthTooltip": "Next month", "previousMonthTooltip": "Previous month", "nextPageTooltip": "Next page", "previousPageTooltip": "Previous page", "firstPageTooltip": "First page", "lastPageTooltip": "Last page", "showMenuTooltip": "Show menu", "aboutListTileTitle": "About $applicationName", "licensesPageTitle": "Licences", "licensesPackageDetailTextZero": "No licences", "licensesPackageDetailTextOne": "1 licence", "licensesPackageDetailTextOther": "$licenseCount licences", "pageRowsInfoTitle": "$firstRow–$lastRow of $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow of about $rowCount", "rowsPerPageTitle": "Rows per page:", "tabLabel": "Tab $tabIndex of $tabCount", "selectedRowCountTitleOne": "1 item selected", "selectedRowCountTitleOther": "$selectedRowCount items selected", "cancelButtonLabel": "Cancel", "closeButtonLabel": "Close", "continueButtonLabel": "Continue", "copyButtonLabel": "Copy", "cutButtonLabel": "Cut", "okButtonLabel": "OK", "pasteButtonLabel": "Paste", "selectAllButtonLabel": "Select all", "viewLicensesButtonLabel": "View licences", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Select hours", "timePickerMinuteModeAnnouncement": "Select minutes", "modalBarrierDismissLabel": "Dismiss", "signedInLabel": "Signed in", "hideAccountsLabel": "Hide accounts", "showAccountsLabel": "Show accounts", "drawerLabel": "Navigation menu", "popupMenuLabel": "Pop-up menu", "dialogLabel": "Dialogue", "alertDialogLabel": "Alert", "searchFieldLabel": "Search", "reorderItemToStart": "Move to the start", "reorderItemToEnd": "Move to the end", "reorderItemUp": "Move up", "reorderItemDown": "Move down", "reorderItemLeft": "Move to the left", "reorderItemRight": "Move to the right", "expandedIconTapHint": "Collapse", "collapsedIconTapHint": "Expand", "remainingTextFieldCharacterCountOne": "1 character remaining", "remainingTextFieldCharacterCountOther": "$remainingCount characters remaining", "refreshIndicatorSemanticLabel": "Refresh" }
flutter/packages/flutter_localizations/lib/src/l10n/material_en_NZ.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_en_NZ.arb", "repo_id": "flutter", "token_count": 1979 }
719
{ "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "Чабыттоо менюсун ачуу", "backButtonTooltip": "Артка", "closeButtonTooltip": "Жабуу", "deleteButtonTooltip": "Жок кылуу", "nextMonthTooltip": "Кийинки ай", "previousMonthTooltip": "Мурунку ай", "nextPageTooltip": "Кийинки бет", "previousPageTooltip": "Мурунку бет", "firstPageTooltip": "Биринчи бет", "lastPageTooltip": "Акыркы бет", "showMenuTooltip": "Менюну көрсөтүү", "aboutListTileTitle": "$applicationName каналы жөнүндө", "licensesPageTitle": "Уруксаттамалар", "pageRowsInfoTitle": "$rowCount ичинен $firstRow–$lastRow", "pageRowsInfoTitleApproximate": "Болжол менен $rowCount ичинен $firstRow–$lastRow", "rowsPerPageTitle": "Бир беттеги саптардын саны:", "tabLabel": "$tabCount кыналма ичинен $tabIndex", "selectedRowCountTitleOne": "1 нерсе тандалды", "selectedRowCountTitleOther": "$selectedRowCount нерсе тандалды", "cancelButtonLabel": "Токтотуу", "closeButtonLabel": "Жабуу", "continueButtonLabel": "Улантуу", "copyButtonLabel": "Көчүрүү", "cutButtonLabel": "Кесүү", "scanTextButtonLabel": "Текстти скандоо", "okButtonLabel": "Макул", "pasteButtonLabel": "Чаптоо", "selectAllButtonLabel": "Баарын тандоо", "viewLicensesButtonLabel": "Уруксаттамаларды көрүү", "anteMeridiemAbbreviation": "түшкө чейин", "postMeridiemAbbreviation": "түштөн кийин", "timePickerHourModeAnnouncement": "Саатты тандаңыз", "timePickerMinuteModeAnnouncement": "Мүнөттөрдү тандаңыз", "modalBarrierDismissLabel": "Жабуу", "signedInLabel": "Аккаунтуңузга кирдиңиз", "hideAccountsLabel": "Аккаунттарды жашыруу", "showAccountsLabel": "Аккаунттарды көрсөтүү", "drawerLabel": "Чабыттоо менюсу", "popupMenuLabel": "Калкып чыгуучу меню", "dialogLabel": "Диалог", "alertDialogLabel": "Эскертүү", "searchFieldLabel": "Издөө", "reorderItemToStart": "Башына жылдыруу", "reorderItemToEnd": "Аягына жылдыруу", "reorderItemUp": "Жогору жылдыруу", "reorderItemDown": "Төмөн жылдыруу", "reorderItemLeft": "Солго жылдыруу", "reorderItemRight": "Оңго жылдыруу", "expandedIconTapHint": "Жыйыштыруу", "collapsedIconTapHint": "Жайып көрсөтүү", "remainingTextFieldCharacterCountOne": "1 белги калды", "remainingTextFieldCharacterCountOther": "$remainingCount белги калды", "refreshIndicatorSemanticLabel": "Жаңыртуу", "moreButtonTooltip": "Дагы", "dateSeparator": ".", "dateHelpText": "кк.аа.жжжж", "selectYearSemanticsLabel": "Жылды тандоо", "unspecifiedDate": "Күн", "unspecifiedDateRange": "Даталар диапазону", "dateInputLabel": "Күндү киргизүү", "dateRangeStartLabel": "Баштоо күнү", "dateRangeEndLabel": "Качан аяктайт", "dateRangeStartDateSemanticLabel": "Баштоо күнү $fullDate", "dateRangeEndDateSemanticLabel": "Качан аяктайт $fullDate", "invalidDateFormatLabel": "Туура эмес формат.", "invalidDateRangeLabel": "Жараксыз диапазон.", "dateOutOfRangeLabel": "Аракет чегинен тышкары.", "saveButtonLabel": "Сактоо", "datePickerHelpText": "Күндү тандоо", "dateRangePickerHelpText": "Даталар диапазонун тандоо", "calendarModeButtonLabel": "Жылнаамага которулуңуз", "inputDateModeButtonLabel": "Терип киргизүү режимине которулуңуз", "timePickerDialHelpText": "Убакытты тандоо", "timePickerInputHelpText": "Убакытты киргизүү", "timePickerHourLabel": "Саат", "timePickerMinuteLabel": "Мүнөт", "invalidTimeLabel": "Убакытты туура көрсөтүңүз", "dialModeButtonLabel": "Терүүнү тандагыч режимине которулуу", "inputTimeModeButtonLabel": "Текст киргизүү режимине которулуу", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 уруксаттама", "licensesPackageDetailTextOther": "$licenseCount уруксаттама", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Мета", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Power", "keyboardKeyPowerOff": "Power Off", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Тандоо", "keyboardKeySpace": "Боштук", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Меню тилкеси менюсу", "currentDateLabel": "Бүгүн", "scrimLabel": "Кенеп", "bottomSheetLabel": "Ылдыйкы экран", "scrimOnTapHint": "$modalRouteContentName жабуу", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "жыйыштыруу үчүн эки жолу таптаңыз", "expansionTileCollapsedHint": "жайып көрсөтүү үчүн эки жолу таптаңыз", "expansionTileExpandedTapHint": "Жыйыштыруу", "expansionTileCollapsedTapHint": "Толук маалымат алуу үчүн жайып көрүңүз", "expandedHint": "Жыйыштырылды", "collapsedHint": "Жайылып көрсөтүлдү", "menuDismissLabel": "Менюну жабуу", "lookUpButtonLabel": "Издөө", "searchWebButtonLabel": "Интернеттен издөө", "shareButtonLabel": "Бөлүшүү…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_ky.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ky.arb", "repo_id": "flutter", "token_count": 3434 }
720
{ "licensesPackageDetailTextFew": "$licenseCount licencje", "licensesPackageDetailTextMany": "$licenseCount licencji", "remainingTextFieldCharacterCountFew": "Pozostały $remainingCount znaki", "remainingTextFieldCharacterCountMany": "Pozostało $remainingCount znaków", "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "selectedRowCountTitleFew": "$selectedRowCount wybrane elementy", "selectedRowCountTitleMany": "$selectedRowCount wybranych elementów", "openAppDrawerTooltip": "Otwórz menu nawigacyjne", "backButtonTooltip": "Wstecz", "closeButtonTooltip": "Zamknij", "deleteButtonTooltip": "Usuń", "nextMonthTooltip": "Następny miesiąc", "previousMonthTooltip": "Poprzedni miesiąc", "nextPageTooltip": "Następna strona", "previousPageTooltip": "Poprzednia strona", "firstPageTooltip": "Pierwsza strona", "lastPageTooltip": "Ostatnia strona", "showMenuTooltip": "Pokaż menu", "aboutListTileTitle": "$applicationName – informacje", "licensesPageTitle": "Licencje", "pageRowsInfoTitle": "$firstRow–$lastRow z $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow z około $rowCount", "rowsPerPageTitle": "Wiersze na stronie:", "tabLabel": "Karta $tabIndex z $tabCount", "selectedRowCountTitleOne": "1 wybrany element", "selectedRowCountTitleOther": "$selectedRowCount wybranych elementów", "cancelButtonLabel": "Anuluj", "closeButtonLabel": "Zamknij", "continueButtonLabel": "Dalej", "copyButtonLabel": "Kopiuj", "cutButtonLabel": "Wytnij", "scanTextButtonLabel": "Skanuj tekst", "okButtonLabel": "OK", "pasteButtonLabel": "Wklej", "selectAllButtonLabel": "Zaznacz wszystko", "viewLicensesButtonLabel": "Wyświetl licencje", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Wybierz godziny", "timePickerMinuteModeAnnouncement": "Wybierz minuty", "signedInLabel": "Zalogowani użytkownicy", "hideAccountsLabel": "Ukryj konta", "showAccountsLabel": "Pokaż konta", "modalBarrierDismissLabel": "Zamknij", "drawerLabel": "Menu nawigacyjne", "popupMenuLabel": "Menu kontekstowe", "dialogLabel": "Okno dialogowe", "alertDialogLabel": "Alert", "searchFieldLabel": "Szukaj", "reorderItemToStart": "Przenieś na początek", "reorderItemToEnd": "Przenieś na koniec", "reorderItemUp": "Przenieś w górę", "reorderItemDown": "Przenieś w dół", "reorderItemLeft": "Przenieś w lewo", "reorderItemRight": "Przenieś w prawo", "expandedIconTapHint": "Zwiń", "collapsedIconTapHint": "Rozwiń", "remainingTextFieldCharacterCountOne": "Jeszcze 1 znak", "remainingTextFieldCharacterCountOther": "Pozostało $remainingCount znaków", "refreshIndicatorSemanticLabel": "Odśwież", "moreButtonTooltip": "Więcej", "dateSeparator": ".", "dateHelpText": "dd.mm.rrrr", "selectYearSemanticsLabel": "Wybierz rok", "unspecifiedDate": "Data", "unspecifiedDateRange": "Zakres dat", "dateInputLabel": "Wpisz datę", "dateRangeStartLabel": "Data rozpoczęcia", "dateRangeEndLabel": "Data zakończenia", "dateRangeStartDateSemanticLabel": "Data rozpoczęcia: $fullDate", "dateRangeEndDateSemanticLabel": "Data zakończenia: $fullDate", "invalidDateFormatLabel": "Nieprawidłowy format.", "invalidDateRangeLabel": "Nieprawidłowy zakres.", "dateOutOfRangeLabel": "Poza zakresem.", "saveButtonLabel": "Zapisz", "datePickerHelpText": "Wybierz datę", "dateRangePickerHelpText": "Wybierz zakres", "calendarModeButtonLabel": "Przełącz na kalendarz", "inputDateModeButtonLabel": "Przełącz na wpisywanie", "timePickerDialHelpText": "Wybierz godzinę", "timePickerInputHelpText": "Wpisz godzinę", "timePickerHourLabel": "Godzina", "timePickerMinuteLabel": "Minuta", "invalidTimeLabel": "Wpisz prawidłową godzinę", "dialModeButtonLabel": "Włącz tryb selektora", "inputTimeModeButtonLabel": "Włącz tryb wprowadzania tekstu", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licencja", "licensesPackageDetailTextOther": "$licenseCount licencji", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Poprzedni kanał", "keyboardKeyChannelUp": "Następny kanał", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Wysuń", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDn", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Zasilanie", "keyboardKeyPowerOff": "Wyłącz zasilanie", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Spacja", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Pasek menu", "currentDateLabel": "Dziś", "scrimLabel": "Siatka", "bottomSheetLabel": "Plansza dolna", "scrimOnTapHint": "Zamknij: $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "kliknij dwukrotnie, aby zwinąć", "expansionTileCollapsedHint": "kliknij dwukrotnie, aby rozwinąć", "expansionTileExpandedTapHint": "Zwiń", "expansionTileCollapsedTapHint": "Rozwiń, aby wyświetlić więcej informacji", "expandedHint": "Zwinięto", "collapsedHint": "Rozwinięto", "menuDismissLabel": "Zamknij menu", "lookUpButtonLabel": "Sprawdź", "searchWebButtonLabel": "Szukaj w internecie", "shareButtonLabel": "Udostępnij…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_pl.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_pl.arb", "repo_id": "flutter", "token_count": 2621 }
721
{ "scriptCategory": "tall", "timeOfDayFormat": "ah:mm", "openAppDrawerTooltip": "เปิดเมนูการนำทาง", "backButtonTooltip": "กลับ", "closeButtonTooltip": "ปิด", "deleteButtonTooltip": "ลบ", "nextMonthTooltip": "เดือนหน้า", "previousMonthTooltip": "เดือนที่แล้ว", "nextPageTooltip": "หน้าถัดไป", "previousPageTooltip": "หน้าก่อน", "firstPageTooltip": "หน้าแรก", "lastPageTooltip": "หน้าสุดท้าย", "showMenuTooltip": "แสดงเมนู", "aboutListTileTitle": "เกี่ยวกับ $applicationName", "licensesPageTitle": "ใบอนุญาต", "pageRowsInfoTitle": "$firstRow-$lastRow จาก $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow จากประมาณ $rowCount", "rowsPerPageTitle": "แถวต่อหน้า:", "tabLabel": "แท็บที่ $tabIndex จาก $tabCount", "selectedRowCountTitleOne": "เลือกแล้ว 1 รายการ", "selectedRowCountTitleOther": "เลือกแล้ว $selectedRowCount รายการ", "cancelButtonLabel": "ยกเลิก", "closeButtonLabel": "ปิด", "continueButtonLabel": "ต่อไป", "copyButtonLabel": "คัดลอก", "cutButtonLabel": "ตัด", "scanTextButtonLabel": "สแกนข้อความ", "okButtonLabel": "ตกลง", "pasteButtonLabel": "วาง", "selectAllButtonLabel": "เลือกทั้งหมด", "viewLicensesButtonLabel": "ดูใบอนุญาต", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "เลือกชั่วโมง", "timePickerMinuteModeAnnouncement": "เลือกนาที", "signedInLabel": "ลงชื่อเข้าใช้", "hideAccountsLabel": "ซ่อนบัญชี", "showAccountsLabel": "แสดงบัญชี", "modalBarrierDismissLabel": "ปิด", "drawerLabel": "เมนูการนำทาง", "popupMenuLabel": "เมนูป๊อปอัป", "dialogLabel": "กล่องโต้ตอบ", "alertDialogLabel": "การแจ้งเตือน", "searchFieldLabel": "ค้นหา", "reorderItemToStart": "ย้ายไปต้นรายการ", "reorderItemToEnd": "ย้ายไปท้ายรายการ", "reorderItemUp": "ย้ายขึ้น", "reorderItemDown": "ย้ายลง", "reorderItemLeft": "ย้ายไปทางซ้าย", "reorderItemRight": "ย้ายไปทางขวา", "expandedIconTapHint": "ยุบ", "collapsedIconTapHint": "ขยาย", "remainingTextFieldCharacterCountOne": "เหลือ 1 อักขระ", "remainingTextFieldCharacterCountOther": "เหลือ $remainingCount อักขระ", "refreshIndicatorSemanticLabel": "รีเฟรช", "moreButtonTooltip": "เพิ่มเติม", "dateSeparator": "/", "dateHelpText": "ดด/วว/ปปปป", "selectYearSemanticsLabel": "เลือกปี", "unspecifiedDate": "วันที่", "unspecifiedDateRange": "ช่วงวันที่", "dateInputLabel": "ป้อนวันที่", "dateRangeStartLabel": "วันที่เริ่มต้น", "dateRangeEndLabel": "วันที่สิ้นสุด", "dateRangeStartDateSemanticLabel": "วันที่เริ่มต้น $fullDate", "dateRangeEndDateSemanticLabel": "วันที่สิ้นสุด $fullDate", "invalidDateFormatLabel": "รูปแบบไม่ถูกต้อง", "invalidDateRangeLabel": "ช่วงไม่ถูกต้อง", "dateOutOfRangeLabel": "ไม่อยู่ในช่วง", "saveButtonLabel": "บันทึก", "datePickerHelpText": "เลือกวันที่", "dateRangePickerHelpText": "เลือกช่วง", "calendarModeButtonLabel": "เปลี่ยนเป็นปฏิทิน", "inputDateModeButtonLabel": "เปลี่ยนเป็นโหมดป้อนข้อความ", "timePickerDialHelpText": "เลือกเวลา", "timePickerInputHelpText": "ป้อนเวลา", "timePickerHourLabel": "ชั่วโมง", "timePickerMinuteLabel": "นาที", "invalidTimeLabel": "ป้อนเวลาที่ถูกต้อง", "dialModeButtonLabel": "สลับไปใช้โหมดเครื่องมือเลือกแบบหมุน", "inputTimeModeButtonLabel": "สลับไปใช้โหมดป้อนข้อมูลข้อความ", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "ใบอนุญาต 1 ใบ", "licensesPackageDetailTextOther": "ใบอนุญาต $licenseCount ใบ", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "เลข 1", "keyboardKeyNumpad2": "เลข 2", "keyboardKeyNumpad3": "เลข 3", "keyboardKeyNumpad4": "เลข 4", "keyboardKeyNumpad5": "เลข 5", "keyboardKeyNumpad6": "เลข 6", "keyboardKeyNumpad7": "เลข 7", "keyboardKeyNumpad8": "เลข 8", "keyboardKeyNumpad9": "เลข 9", "keyboardKeyNumpad0": "เลข 0", "keyboardKeyNumpadAdd": "เลข +", "keyboardKeyNumpadComma": "เลข ,", "keyboardKeyNumpadDecimal": "เลข .", "keyboardKeyNumpadDivide": "เลข /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "เลข =", "keyboardKeyNumpadMultiply": "เลข *", "keyboardKeyNumpadParenLeft": "เลข (", "keyboardKeyNumpadParenRight": "เลข )", "keyboardKeyNumpadSubtract": "เลข -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "เปิด/ปิด", "keyboardKeyPowerOff": "ปิดเครื่อง", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Space", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "เมนูในแถบเมนู", "currentDateLabel": "วันนี้", "scrimLabel": "Scrim", "bottomSheetLabel": "Bottom Sheet", "scrimOnTapHint": "ปิด $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "แตะสองครั้งเพื่อยุบ", "expansionTileCollapsedHint": "แตะสองครั้งเพื่อขยาย", "expansionTileExpandedTapHint": "ยุบ", "expansionTileCollapsedTapHint": "ขยายเพื่อดูรายละเอียดเพิ่มเติม", "expandedHint": "ยุบ", "collapsedHint": "ขยาย", "menuDismissLabel": "ปิดเมนู", "lookUpButtonLabel": "ค้นหา", "searchWebButtonLabel": "ค้นหาบนอินเทอร์เน็ต", "shareButtonLabel": "แชร์...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_th.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_th.arb", "repo_id": "flutter", "token_count": 3785 }
722
{ "reorderItemToStart": "Перамясціць у пачатак", "reorderItemToEnd": "Перамясціць у канец", "reorderItemUp": "Перамясціць уверх", "reorderItemDown": "Перамясціць уніз", "reorderItemLeft": "Перамясціць улева", "reorderItemRight": "Перамясціць управа" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_be.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_be.arb", "repo_id": "flutter", "token_count": 204 }
723
{ "reorderItemToStart": "Mover ao inicio", "reorderItemToEnd": "Mover ao final", "reorderItemUp": "Mover cara arriba", "reorderItemDown": "Mover cara abaixo", "reorderItemLeft": "Mover cara á esquerda", "reorderItemRight": "Mover cara á dereita" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_gl.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_gl.arb", "repo_id": "flutter", "token_count": 109 }
724
{ "reorderItemToStart": "시작으로 이동", "reorderItemToEnd": "끝으로 이동", "reorderItemUp": "위로 이동", "reorderItemDown": "아래로 이동", "reorderItemLeft": "왼쪽으로 이동", "reorderItemRight": "오른쪽으로 이동" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_ko.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ko.arb", "repo_id": "flutter", "token_count": 165 }
725
{ "reorderItemToStart": "ਸ਼ੁਰੂ ਵਿੱਚ ਲਿਜਾਓ", "reorderItemToEnd": "ਅੰਤ ਵਿੱਚ ਲਿਜਾਓ", "reorderItemUp": "ਉੱਪਰ ਲਿਜਾਓ", "reorderItemDown": "ਹੇਠਾਂ ਲਿਜਾਓ", "reorderItemLeft": "ਖੱਬੇ ਲਿਜਾਓ", "reorderItemRight": "ਸੱਜੇ ਲਿਜਾਓ" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_pa.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_pa.arb", "repo_id": "flutter", "token_count": 190 }
726
{ "reorderItemToStart": "ప్రారంభానికి తరలించండి", "reorderItemToEnd": "చివరకు తరలించండి", "reorderItemUp": "పైకి జరపండి", "reorderItemDown": "కిందికు జరుపు", "reorderItemLeft": "ఎడమవైపుగా జరపండి", "reorderItemRight": "కుడివైపుగా జరపండి" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_te.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_te.arb", "repo_id": "flutter", "token_count": 339 }
727
// 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_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Material3 - Nested Localizations', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( // Creates the outer Localizations widget. theme: ThemeData(useMaterial3: true), home: ListView( children: <Widget>[ const LocalizationTracker(key: ValueKey<String>('outer')), Localizations( locale: const Locale('zh', 'CN'), delegates: GlobalMaterialLocalizations.delegates, child: const LocalizationTracker(key: ValueKey<String>('inner')), ), ], ), )); // Most localized aspects of the TextTheme text styles are the same for the default US local and // for Chinese for Material3. The baselines for all text styles differ. final LocalizationTrackerState outerTracker = tester.state(find.byKey(const ValueKey<String>('outer'), skipOffstage: false)); expect(outerTracker.textBaseline, TextBaseline.alphabetic); final LocalizationTrackerState innerTracker = tester.state(find.byKey(const ValueKey<String>('inner'), skipOffstage: false)); expect(innerTracker.textBaseline, TextBaseline.ideographic); }); testWidgets('Material2 - Nested Localizations', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( // Creates the outer Localizations widget. theme: ThemeData(useMaterial3: false), home: ListView( children: <Widget>[ const LocalizationTracker(key: ValueKey<String>('outer')), Localizations( locale: const Locale('zh', 'CN'), delegates: GlobalMaterialLocalizations.delegates, child: const LocalizationTracker(key: ValueKey<String>('inner')), ), ], ), )); // Most localized aspects of the TextTheme text styles are the same for the default US local and // for Chinese for Material2. The baselines for all text styles differ. final LocalizationTrackerState outerTracker = tester.state(find.byKey(const ValueKey<String>('outer'), skipOffstage: false)); expect(outerTracker.textBaseline, TextBaseline.alphabetic); final LocalizationTrackerState innerTracker = tester.state(find.byKey(const ValueKey<String>('inner'), skipOffstage: false)); expect(innerTracker.textBaseline, TextBaseline.ideographic); }); testWidgets('Localizations is compatible with ChangeNotifier.dispose() called during didChangeDependencies', (WidgetTester tester) async { // PageView calls ScrollPosition.dispose() during didChangeDependencies. await tester.pumpWidget( MaterialApp( supportedLocales: const <Locale>[ Locale('en', 'US'), Locale('es', 'ES'), ], localizationsDelegates: <LocalizationsDelegate<dynamic>>[ _DummyLocalizationsDelegate(), ...GlobalMaterialLocalizations.delegates, ], home: PageView(), ) ); await tester.binding.setLocale('es', 'US'); await tester.pump(); await tester.pumpWidget(Container()); }); testWidgets('Locale without countryCode', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/16782 await tester.pumpWidget( MaterialApp( localizationsDelegates: GlobalMaterialLocalizations.delegates, supportedLocales: const <Locale>[ Locale('es', 'ES'), Locale('zh'), ], home: Container(), ) ); await tester.binding.setLocale('zh', ''); await tester.pump(); await tester.binding.setLocale('es', 'US'); await tester.pump(); }); } /// A localizations delegate that does not contain any useful data, and is only /// used to trigger didChangeDependencies upon locale change. class _DummyLocalizationsDelegate extends LocalizationsDelegate<DummyLocalizations> { @override Future<DummyLocalizations> load(Locale locale) async => DummyLocalizations(); @override bool isSupported(Locale locale) => true; @override bool shouldReload(_DummyLocalizationsDelegate old) => true; } class DummyLocalizations { } class LocalizationTracker extends StatefulWidget { const LocalizationTracker({super.key}); @override State<StatefulWidget> createState() => LocalizationTrackerState(); } class LocalizationTrackerState extends State<LocalizationTracker> { late TextBaseline textBaseline; @override Widget build(BuildContext context) { textBaseline = Theme.of(context).textTheme.bodySmall!.textBaseline!; return Container(); } }
flutter/packages/flutter_localizations/test/basics_test.dart/0
{ "file_path": "flutter/packages/flutter_localizations/test/basics_test.dart", "repo_id": "flutter", "token_count": 1662 }
728
# 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. # For details regarding the *Flutter Fix* feature, see # https://flutter.dev/docs/development/tools/flutter-fix # Please add new fixes to the top of the file, separated by one blank line # from other fixes. In a comment, include a link to the PR where the change # requiring the fix was made. # Every fix must be tested. See the # flutter/packages/flutter_test/test_fixes/README.md file for instructions # on testing these data driven fixes. # For documentation about this file format, see # https://dart.dev/go/data-driven-fixes. # * Fixes in this file are for AnimationSheetBuilder from the flutter_test/animation_sheet.dart file. * version: 1 transforms: # Changes made in https://github.com/flutter/flutter/pull/83337 # The related deprecation for `sheetSize` doesn't have a fix because there # isn't an alternative API, it's being removed completely. - title: 'Migrate to collate' date: 2023-03-29 element: uris: [ 'flutter_test.dart' ] method: 'display' inClass: 'AnimationSheetBuilder' changes: - kind: 'rename' newName: 'collate' - kind: 'removeParameter' name: 'key' - kind: 'addParameter' index: 0 name: 'cellsPerRow' style: 'required_positional' argumentValue: expression: '1'
flutter/packages/flutter_test/lib/fix_data/fix_flutter_test/fix_animation_sheet_builder.yaml/0
{ "file_path": "flutter/packages/flutter_test/lib/fix_data/fix_flutter_test/fix_animation_sheet_builder.yaml", "repo_id": "flutter", "token_count": 506 }
729
// 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 'dart:async'; import 'dart:ui' as ui; import 'package:clock/clock.dart'; import 'package:fake_async/fake_async.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:matcher/expect.dart' show fail; import 'package:stack_trace/stack_trace.dart' as stack_trace; import 'package:test_api/scaffolding.dart' as test_package show Timeout; import 'package:vector_math/vector_math_64.dart'; import '_binding_io.dart' if (dart.library.html) '_binding_web.dart' as binding; import 'goldens.dart'; import 'platform.dart'; import 'restoration.dart'; import 'stack_manipulation.dart'; import 'test_async_utils.dart'; import 'test_default_binary_messenger.dart'; import 'test_exception_reporter.dart'; import 'test_text_input.dart'; import 'window.dart'; /// Phases that can be reached by [WidgetTester.pumpWidget] and /// [TestWidgetsFlutterBinding.pump]. /// /// See [WidgetsBinding.drawFrame] for a more detailed description of some of /// these phases. enum EnginePhase { /// The build phase in the widgets library. See [BuildOwner.buildScope]. build, /// The layout phase in the rendering library. See [PipelineOwner.flushLayout]. layout, /// The compositing bits update phase in the rendering library. See /// [PipelineOwner.flushCompositingBits]. compositingBits, /// The paint phase in the rendering library. See [PipelineOwner.flushPaint]. paint, /// The compositing phase in the rendering library. See /// [RenderView.compositeFrame]. This is the phase in which data is sent to /// the GPU. If semantics are not enabled, then this is the last phase. composite, /// The semantics building phase in the rendering library. See /// [PipelineOwner.flushSemantics]. flushSemantics, /// The final phase in the rendering library, wherein semantics information is /// sent to the embedder. See [SemanticsOwner.sendSemanticsUpdate]. sendSemanticsUpdate, } /// Signature of callbacks used to intercept messages on a given channel. /// /// See [TestDefaultBinaryMessenger.setMockDecodedMessageHandler] for more details. typedef _MockMessageHandler = Future<void> Function(Object?); /// Parts of the system that can generate pointer events that reach the test /// binding. /// /// This is used to identify how to handle events in the /// [LiveTestWidgetsFlutterBinding]. See /// [TestWidgetsFlutterBinding.dispatchEvent]. enum TestBindingEventSource { /// The pointer event came from the test framework itself, e.g. from a /// [TestGesture] created by [WidgetTester.startGesture]. test, /// The pointer event came from the system, presumably as a result of the user /// interactive directly with the device while the test was running. device, } const Size _kDefaultTestViewportSize = Size(800.0, 600.0); /// Overrides the [ServicesBinding]'s binary messenger logic to use /// [TestDefaultBinaryMessenger]. /// /// Test bindings that are used by tests that mock message handlers for plugins /// should mix in this binding to enable the use of the /// [TestDefaultBinaryMessenger] APIs. mixin TestDefaultBinaryMessengerBinding on BindingBase, ServicesBinding { @override void initInstances() { super.initInstances(); _instance = this; } /// The current [TestDefaultBinaryMessengerBinding], if one has been created. static TestDefaultBinaryMessengerBinding get instance => BindingBase.checkInstance(_instance); static TestDefaultBinaryMessengerBinding? _instance; @override TestDefaultBinaryMessenger get defaultBinaryMessenger => super.defaultBinaryMessenger as TestDefaultBinaryMessenger; @override TestDefaultBinaryMessenger createBinaryMessenger() { Future<ByteData?> keyboardHandler(ByteData? message) async { return const StandardMethodCodec().encodeSuccessEnvelope(<int, int>{}); } return TestDefaultBinaryMessenger( super.createBinaryMessenger(), outboundHandlers: <String, MessageHandler>{'flutter/keyboard': keyboardHandler}, ); } } /// Accessibility announcement data passed to [SemanticsService.announce] captured in a test. /// /// This class is intended to be used by the testing API to store the announcements /// in a structured form so that tests can verify announcement details. The fields /// of this class correspond to parameters of the [SemanticsService.announce] method. /// /// See also: /// /// * [WidgetTester.takeAnnouncements], which is the test API that uses this class. class CapturedAccessibilityAnnouncement { const CapturedAccessibilityAnnouncement._( this.message, this.textDirection, this.assertiveness, ); /// The accessibility message announced by the framework. final String message; /// The direction in which the text of the [message] flows. final TextDirection textDirection; /// Determines the assertiveness level of the accessibility announcement. final Assertiveness assertiveness; } // Examples can assume: // late TestWidgetsFlutterBinding binding; // late Size someSize; /// Base class for bindings used by widgets library tests. /// /// The [ensureInitialized] method creates (if necessary) and returns an /// instance of the appropriate subclass. (If one is already created, it returns /// that one, even if it's not the one that it would normally create. This /// allows tests to force the use of [LiveTestWidgetsFlutterBinding] even in a /// normal unit test environment, e.g. to test that binding.) /// /// When using these bindings, certain features are disabled. For /// example, [timeDilation] is reset to 1.0 on initialization. /// /// In non-browser tests, the binding overrides `HttpClient` creation with a /// fake client that always returns a status code of 400. This is to prevent /// tests from making network calls, which could introduce flakiness. A test /// that actually needs to make a network call should provide its own /// `HttpClient` to the code making the call, so that it can appropriately mock /// or fake responses. /// /// ### Coordinate spaces /// /// [TestWidgetsFlutterBinding] might be run on devices of different screen /// sizes, while the testing widget is still told the same size to ensure /// consistent results. Consequently, code that deals with positions (such as /// pointer events or painting) must distinguish between two coordinate spaces: /// /// * The _local coordinate space_ is the one used by the testing widget /// (typically an 800 by 600 window, but can be altered by [setSurfaceSize]). /// * The _global coordinate space_ is the one used by the device. /// /// Positions can be transformed between coordinate spaces with [localToGlobal] /// and [globalToLocal]. abstract class TestWidgetsFlutterBinding extends BindingBase with SchedulerBinding, ServicesBinding, GestureBinding, SemanticsBinding, RendererBinding, PaintingBinding, WidgetsBinding, TestDefaultBinaryMessengerBinding { /// Constructor for [TestWidgetsFlutterBinding]. /// /// This constructor overrides the [debugPrint] global hook to point to /// [debugPrintOverride], which can be overridden by subclasses. TestWidgetsFlutterBinding() : platformDispatcher = TestPlatformDispatcher( platformDispatcher: PlatformDispatcher.instance, ) { platformDispatcher.defaultRouteNameTestValue = '/'; debugPrint = debugPrintOverride; debugDisableShadows = disableShadows; } /// Deprecated. Will be removed in a future version of Flutter. /// /// This property has been deprecated to prepare for Flutter's upcoming /// support for multiple views and multiple windows. /// /// This represents a combination of a [TestPlatformDispatcher] and a singular /// [TestFlutterView]. Platform-specific test values can be set through /// [WidgetTester.platformDispatcher] instead. When testing individual widgets /// or applications using [WidgetTester.pumpWidget], view-specific test values /// can be set through [WidgetTester.view]. If multiple views are defined, the /// appropriate view can be found using [WidgetTester.viewOf] if a sub-view /// is needed. /// /// See also: /// /// * [WidgetTester.platformDispatcher] for changing platform-specific values /// for testing. /// * [WidgetTester.view] and [WidgetTester.viewOf] for changing view-specific /// values for testing. /// * [BindingBase.window] for guidance dealing with this property outside of /// a testing context. @Deprecated( 'Use WidgetTester.platformDispatcher or WidgetTester.view instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override late final TestWindow window; @override final TestPlatformDispatcher platformDispatcher; @override TestRestorationManager get restorationManager { _restorationManager ??= createRestorationManager(); return _restorationManager!; } TestRestorationManager? _restorationManager; /// Called by the test framework at the beginning of a widget test to /// prepare the binding for the next test. /// /// If [registerTestTextInput] returns true when this method is called, /// the [testTextInput] is configured to simulate the keyboard. void reset() { _restorationManager?.dispose(); _restorationManager = null; platformDispatcher.defaultRouteNameTestValue = '/'; resetGestureBinding(); testTextInput.reset(); if (registerTestTextInput) { _testTextInput.register(); } CustomSemanticsAction.resetForTests(); // ignore: invalid_use_of_visible_for_testing_member } @override TestRestorationManager createRestorationManager() { return TestRestorationManager(); } /// The value to set [debugPrint] to while tests are running. /// /// This can be used to redirect console output from the framework, or to /// change the behavior of [debugPrint]. For example, /// [AutomatedTestWidgetsFlutterBinding] uses it to make [debugPrint] /// synchronous, disabling its normal throttling behavior. /// /// It is also used by some other parts of the test framework (e.g. /// [WidgetTester.printToConsole]) to ensure that messages from the /// test framework are displayed to the developer rather than logged /// by whatever code is overriding [debugPrint]. DebugPrintCallback get debugPrintOverride => debugPrint; /// The value to set [debugDisableShadows] to while tests are running. /// /// This can be used to reduce the likelihood of golden file tests being /// flaky, because shadow rendering is not always deterministic. The /// [AutomatedTestWidgetsFlutterBinding] sets this to true, so that all tests /// always run with shadows disabled. @protected bool get disableShadows => false; /// Determines whether the Dart [HttpClient] class should be overridden to /// always return a failure response. /// /// By default, this value is true, so that unit tests will not become flaky /// due to intermittent network errors. The value may be overridden by a /// binding intended for use in integration tests that do end to end /// application testing, including working with real network responses. @protected bool get overrideHttpClient => true; /// Determines whether the binding automatically registers [testTextInput] as /// a fake keyboard implementation. /// /// Unit tests make use of this to mock out text input communication for /// widgets. An integration test would set this to false, to test real IME /// or keyboard input. /// /// [TestTextInput.isRegistered] reports whether the text input mock is /// registered or not. /// /// Some of the properties and methods on [testTextInput] are only valid if /// [registerTestTextInput] returns true when a test starts. If those /// members are accessed when using a binding that sets this flag to false, /// they will throw. /// /// If this property returns true when a test ends, the [testTextInput] is /// unregistered. /// /// This property should not change the value it returns during the lifetime /// of the binding. Changing the value of this property risks very confusing /// behavior as the [TestTextInput] may be inconsistently registered or /// unregistered. @protected bool get registerTestTextInput => true; /// Delay for `duration` of time. /// /// In the automated test environment ([AutomatedTestWidgetsFlutterBinding], /// typically used in `flutter test`), this advances the fake [clock] for the /// period. /// /// In the live test environment ([LiveTestWidgetsFlutterBinding], typically /// used for `flutter run` and for [e2e](https://pub.dev/packages/e2e)), it is /// equivalent to [Future.delayed]. Future<void> delayed(Duration duration); /// The current [TestWidgetsFlutterBinding], if one has been created. /// /// Provides access to the features exposed by this binding. The binding must /// be initialized before using this getter; this is typically done by calling /// [testWidgets] or [TestWidgetsFlutterBinding.ensureInitialized]. static TestWidgetsFlutterBinding get instance => BindingBase.checkInstance(_instance); static TestWidgetsFlutterBinding? _instance; /// Creates and initializes the binding. This function is /// idempotent; calling it a second time will just return the /// previously-created instance. /// /// This function will use [AutomatedTestWidgetsFlutterBinding] if /// the test was run using `flutter test`, and /// [LiveTestWidgetsFlutterBinding] otherwise (e.g. if it was run /// using `flutter run`). This is determined by looking at the /// environment variables for a variable called `FLUTTER_TEST`. /// /// If `FLUTTER_TEST` is set with a value of 'true', then this test was /// invoked by `flutter test`. If `FLUTTER_TEST` is not set, or if it is set /// to 'false', then this test was invoked by `flutter run`. /// /// Browser environments do not currently support the /// [LiveTestWidgetsFlutterBinding], so this function will always set up an /// [AutomatedTestWidgetsFlutterBinding] when run in a web browser. /// /// The parameter `environment` is used to test the test framework /// itself by checking how it reacts to different environment /// variable values, and should not be used outside of this context. /// /// If a [TestWidgetsFlutterBinding] subclass was explicitly initialized /// before calling [ensureInitialized], then that version of the binding is /// returned regardless of the logic described above. This allows tests to /// force a specific test binding to be used. /// /// This is called automatically by [testWidgets]. static TestWidgetsFlutterBinding ensureInitialized([@visibleForTesting Map<String, String>? environment]) { return _instance ?? binding.ensureInitialized(environment); } @override void initInstances() { // This is initialized here because it's needed for the `super.initInstances` // call. It can't be handled as a ctor initializer because it's dependent // on `platformDispatcher`. It can't be handled in the ctor itself because // the base class ctor is called first and calls `initInstances`. window = TestWindow.fromPlatformDispatcher(platformDispatcher: platformDispatcher); super.initInstances(); _instance = this; timeDilation = 1.0; // just in case the developer has artificially changed it for development if (overrideHttpClient) { binding.setupHttpOverrides(); } _testTextInput = TestTextInput(onCleared: _resetFocusedEditable); } @override // ignore: must_call_super void initLicenses() { // Do not include any licenses, because we're a test, and the LICENSE file // doesn't get generated for tests. } @override bool debugCheckZone(String entryPoint) { // We skip all the zone checks in tests because the test framework makes heavy use // of zones and so the zones never quite match the way the framework expects. return true; } /// Whether there is currently a test executing. bool get inTest; /// The number of outstanding microtasks in the queue. int get microtaskCount; /// The default test timeout for tests when using this binding. /// /// This controls the default for the `timeout` argument on [testWidgets]. It /// is 10 minutes for [AutomatedTestWidgetsFlutterBinding] (tests running /// using `flutter test`), and unlimited for tests using /// [LiveTestWidgetsFlutterBinding] (tests running using `flutter run`). test_package.Timeout get defaultTestTimeout; /// The current time. /// /// In the automated test environment (`flutter test`), this is a fake clock /// that begins in January 2015 at the start of the test and advances each /// time [pump] is called with a non-zero duration. /// /// In the live testing environment (`flutter run`), this object shows the /// actual current wall-clock time. Clock get clock; @override SamplingClock? get debugSamplingClock => _TestSamplingClock(clock); /// Triggers a frame sequence (build/layout/paint/etc), /// then flushes microtasks. /// /// If duration is set, then advances the clock by that much first. /// Doing this flushes microtasks. /// /// The supplied EnginePhase is the final phase reached during the pump pass; /// if not supplied, the whole pass is executed. /// /// See also [LiveTestWidgetsFlutterBindingFramePolicy], which affects how /// this method works when the test is run with `flutter run`. Future<void> pump([ Duration? duration, EnginePhase newPhase = EnginePhase.sendSemanticsUpdate ]); /// Runs a `callback` that performs real asynchronous work. /// /// This is intended for callers who need to call asynchronous methods where /// the methods spawn isolates or OS threads and thus cannot be executed /// synchronously by calling [pump]. /// /// The `callback` must return a [Future] that completes to a value of type /// `T`. /// /// If `callback` completes successfully, this will return the future /// returned by `callback`. /// /// If `callback` completes with an error, the error will be caught by the /// Flutter framework and made available via [takeException], and this method /// will return a future that completes with `null`. /// /// Re-entrant calls to this method are not allowed; callers of this method /// are required to wait for the returned future to complete before calling /// this method again. Attempts to do otherwise will result in a /// [TestFailure] error being thrown. Future<T?> runAsync<T>(Future<T> Function() callback); /// Artificially calls dispatchLocalesChanged on the Widget binding, /// then flushes microtasks. /// /// Passes only one single Locale. Use [setLocales] to pass a full preferred /// locales list. Future<void> setLocale(String languageCode, String countryCode) { return TestAsyncUtils.guard<void>(() async { assert(inTest); final Locale locale = Locale(languageCode, countryCode == '' ? null : countryCode); dispatchLocalesChanged(<Locale>[locale]); }); } /// Artificially calls dispatchLocalesChanged on the Widget binding, /// then flushes microtasks. Future<void> setLocales(List<Locale> locales) { return TestAsyncUtils.guard<void>(() async { assert(inTest); dispatchLocalesChanged(locales); }); } @override Future<ui.AppExitResponse> exitApplication(ui.AppExitType exitType, [int exitCode = 0]) async { switch (exitType) { case ui.AppExitType.cancelable: // The test framework shouldn't actually exit when requested. return ui.AppExitResponse.cancel; case ui.AppExitType.required: throw FlutterError('Unexpected application exit request while running test'); } } /// Re-attempts the initialization of the lifecycle state after providing /// test values in [TestPlatformDispatcher.initialLifecycleStateTestValue]. void readTestInitialLifecycleStateFromNativeWindow() { readInitialLifecycleStateFromNativeWindow(); } Size? _surfaceSize; /// Artificially changes the logical size of [WidgetTester.view] to the /// specified size, then flushes microtasks. /// /// Set to null to use the default surface size. /// /// To avoid affecting other tests by leaking state, a test that /// uses this method should always reset the surface size to the default. /// For example, using `addTearDown`: /// ```dart /// await binding.setSurfaceSize(someSize); /// addTearDown(() => binding.setSurfaceSize(null)); /// ``` /// /// This method only affects the size of the [WidgetTester.view]. It does not /// affect the size of any other views. Instead of this method, consider /// setting [TestFlutterView.physicalSize], which works for any view, /// including [WidgetTester.view]. // TODO(pdblasi-google): Deprecate this. https://github.com/flutter/flutter/issues/123881 Future<void> setSurfaceSize(Size? size) { return TestAsyncUtils.guard<void>(() async { assert(inTest); if (_surfaceSize == size) { return; } _surfaceSize = size; handleMetricsChanged(); }); } @override void addRenderView(RenderView view) { _insideAddRenderView = true; try { super.addRenderView(view); } finally { _insideAddRenderView = false; } } bool _insideAddRenderView = false; @override ViewConfiguration createViewConfigurationFor(RenderView renderView) { if (_insideAddRenderView && renderView.hasConfiguration && renderView.configuration is TestViewConfiguration && renderView == this.renderView) { // If a test has reached out to the now deprecated renderView property to set a custom TestViewConfiguration // we are not replacing it. This is to maintain backwards compatibility with how things worked prior to the // deprecation of that property. // TODO(goderbauer): Remove this "if" when the deprecated renderView property is removed. return renderView.configuration; } final FlutterView view = renderView.flutterView; if (_surfaceSize != null && view == platformDispatcher.implicitView) { final BoxConstraints constraints = BoxConstraints.tight(_surfaceSize!); return ViewConfiguration( logicalConstraints: constraints, physicalConstraints: constraints * view.devicePixelRatio, devicePixelRatio: view.devicePixelRatio, ); } return super.createViewConfigurationFor(renderView); } /// Acts as if the application went idle. /// /// Runs all remaining microtasks, including those scheduled as a result of /// running them, until there are no more microtasks scheduled. Then, runs any /// previously scheduled timers with zero time, and completes the returned future. /// /// May result in an infinite loop or run out of memory if microtasks continue /// to recursively schedule new microtasks. Will not run any timers scheduled /// after this method was invoked, even if they are zero-time timers. Future<void> idle() { return TestAsyncUtils.guard<void>(() { final Completer<void> completer = Completer<void>(); Timer.run(() { completer.complete(); }); return completer.future; }); } /// Convert the given point from the global coordinate space of the provided /// [RenderView] to its local one. /// /// This method operates in logical pixels for both coordinate spaces. It does /// not apply the device pixel ratio (used to translate to/from physical /// pixels). /// /// For definitions for coordinate spaces, see [TestWidgetsFlutterBinding]. Offset globalToLocal(Offset point, RenderView view) => point; /// Convert the given point from the local coordinate space to the global /// coordinate space of the [RenderView]. /// /// This method operates in logical pixels for both coordinate spaces. It does /// not apply the device pixel ratio to translate to physical pixels. /// /// For definitions for coordinate spaces, see [TestWidgetsFlutterBinding]. Offset localToGlobal(Offset point, RenderView view) => point; /// The source of the current pointer event. /// /// The [pointerEventSource] is set as the `source` parameter of /// [handlePointerEventForSource] and can be used in the immediate enclosing /// [dispatchEvent]. /// /// When [handlePointerEvent] is called directly, [pointerEventSource] /// is [TestBindingEventSource.device]. /// /// This means that pointer events triggered by the [WidgetController] (e.g. /// via [WidgetController.tap]) will result in actual interactions with the /// UI, but other pointer events such as those from physical taps will be /// dropped. See also [shouldPropagateDevicePointerEvents] if this is /// undesired. TestBindingEventSource get pointerEventSource => _pointerEventSource; TestBindingEventSource _pointerEventSource = TestBindingEventSource.device; /// Whether pointer events from [TestBindingEventSource.device] will be /// propagated to the framework, or dropped. /// /// Setting this can be useful to interact with the app in some other way /// besides through the [WidgetController], such as with `adb shell input tap` /// on Android. /// /// See also [pointerEventSource]. bool shouldPropagateDevicePointerEvents = false; /// Dispatch an event to the targets found by a hit test on its position, /// and remember its source as [pointerEventSource]. /// /// This method sets [pointerEventSource] to `source`, forwards the call to /// [handlePointerEvent], then resets [pointerEventSource] to the previous /// value. /// /// If `source` is [TestBindingEventSource.device], then the `event` is based /// in the global coordinate space (for definitions for coordinate spaces, /// see [TestWidgetsFlutterBinding]) and the event is likely triggered by the /// user physically interacting with the screen during a live test on a real /// device (see [LiveTestWidgetsFlutterBinding]). /// /// If `source` is [TestBindingEventSource.test], then the `event` is based /// in the local coordinate space and the event is likely triggered by /// programmatically simulated pointer events, such as: /// /// * [WidgetController.tap] and alike methods, as well as directly using /// [TestGesture]. They are usually used in /// [AutomatedTestWidgetsFlutterBinding] but sometimes in live tests too. /// * [WidgetController.timedDrag] and alike methods. They are usually used /// in macrobenchmarks. void handlePointerEventForSource( PointerEvent event, { TestBindingEventSource source = TestBindingEventSource.device, }) { withPointerEventSource(source, () => handlePointerEvent(event)); } /// Sets [pointerEventSource] to `source`, runs `task`, then resets `source` /// to the previous value. @protected void withPointerEventSource(TestBindingEventSource source, VoidCallback task) { final TestBindingEventSource previousSource = _pointerEventSource; _pointerEventSource = source; try { task(); } finally { _pointerEventSource = previousSource; } } /// A stub for the system's onscreen keyboard. Callers must set the /// [focusedEditable] before using this value. TestTextInput get testTextInput => _testTextInput; late TestTextInput _testTextInput; /// The [State] of the current [EditableText] client of the onscreen keyboard. /// /// Setting this property to a new value causes the given [EditableTextState] /// to focus itself and request the keyboard to establish a /// [TextInputConnection]. /// /// Callers must pump an additional frame after setting this property to /// complete the focus change. /// /// Instead of setting this directly, consider using /// [WidgetTester.showKeyboard]. // // TODO(ianh): We should just remove this property and move the call to // requestKeyboard to the WidgetTester.showKeyboard method. EditableTextState? get focusedEditable => _focusedEditable; EditableTextState? _focusedEditable; set focusedEditable(EditableTextState? value) { if (_focusedEditable != value) { _focusedEditable = value; value?.requestKeyboard(); } } void _resetFocusedEditable() { _focusedEditable = null; } /// Returns the exception most recently caught by the Flutter framework. /// /// Call this if you expect an exception during a test. If an exception is /// thrown and this is not called, then the exception is rethrown when /// the [testWidgets] call completes. /// /// If two exceptions are thrown in a row without the first one being /// acknowledged with a call to this method, then when the second exception is /// thrown, they are both dumped to the console and then the second is /// rethrown from the exception handler. This will likely result in the /// framework entering a highly unstable state and everything collapsing. /// /// It's safe to call this when there's no pending exception; it will return /// null in that case. dynamic takeException() { assert(inTest); final dynamic result = _pendingExceptionDetails?.exception; _pendingExceptionDetails = null; return result; } FlutterExceptionHandler? _oldExceptionHandler; late StackTraceDemangler _oldStackTraceDemangler; FlutterErrorDetails? _pendingExceptionDetails; _MockMessageHandler? _announcementHandler; List<CapturedAccessibilityAnnouncement> _announcements = <CapturedAccessibilityAnnouncement>[]; /// {@template flutter.flutter_test.TakeAccessibilityAnnouncements} /// Returns a list of all the accessibility announcements made by the Flutter /// framework since the last time this function was called. /// /// It's safe to call this when there hasn't been any announcements; it will return /// an empty list in that case. /// {@endtemplate} List<CapturedAccessibilityAnnouncement> takeAnnouncements() { assert(inTest); final List<CapturedAccessibilityAnnouncement> announcements = _announcements; _announcements = <CapturedAccessibilityAnnouncement>[]; return announcements; } static const TextStyle _messageStyle = TextStyle( color: Color(0xFF917FFF), fontSize: 40.0, ); static const Widget _preTestMessage = Center( child: Text( 'Test starting...', style: _messageStyle, textDirection: TextDirection.ltr, ), ); static const Widget _postTestMessage = Center( child: Text( 'Test finished.', style: _messageStyle, textDirection: TextDirection.ltr, ), ); /// Whether to include the output of debugDumpApp() when reporting /// test failures. bool showAppDumpInErrors = false; /// Call the testBody inside a [FakeAsync] scope on which [pump] can /// advance time. /// /// Returns a future which completes when the test has run. /// /// Called by the [testWidgets] and [benchmarkWidgets] functions to /// run a test. /// /// The `invariantTester` argument is called after the `testBody`'s [Future] /// completes. If it throws, then the test is marked as failed. /// /// The `description` is used by the [LiveTestWidgetsFlutterBinding] to /// show a label on the screen during the test. The description comes from /// the value passed to [testWidgets]. Future<void> runTest( Future<void> Function() testBody, VoidCallback invariantTester, { String description = '', }); /// This is called during test execution before and after the body has been /// executed. /// /// It's used by [AutomatedTestWidgetsFlutterBinding] to drain the microtasks /// before the final [pump] that happens during test cleanup. void asyncBarrier() { TestAsyncUtils.verifyAllScopesClosed(); } Zone? _parentZone; VoidCallback _createTestCompletionHandler(String testDescription, Completer<void> completer) { return () { // This can get called twice, in the case of a Future without listeners failing, and then // our main future completing. assert(Zone.current == _parentZone); if (_pendingExceptionDetails != null) { debugPrint = debugPrintOverride; // just in case the test overrides it -- otherwise we won't see the error! reportTestException(_pendingExceptionDetails!, testDescription); _pendingExceptionDetails = null; } if (!completer.isCompleted) { completer.complete(); } }; } /// Called when the framework catches an exception, even if that exception is /// being handled by [takeException]. /// /// This is called when there is no pending exception; if multiple exceptions /// are thrown and [takeException] isn't used, then subsequent exceptions are /// logged to the console regardless (and the test will fail). @protected void reportExceptionNoticed(FlutterErrorDetails exception) { // By default we do nothing. // The LiveTestWidgetsFlutterBinding overrides this to report the exception to the console. } Future<void> _handleAnnouncementMessage(Object? mockMessage) async { final Map<Object?, Object?> message = mockMessage! as Map<Object?, Object?>; if (message['type'] == 'announce') { final Map<Object?, Object?> data = message['data']! as Map<Object?, Object?>; final String dataMessage = data['message'].toString(); final TextDirection textDirection = TextDirection.values[data['textDirection']! as int]; final int assertivenessLevel = (data['assertiveness'] as int?) ?? 0; final Assertiveness assertiveness = Assertiveness.values[assertivenessLevel]; final CapturedAccessibilityAnnouncement announcement = CapturedAccessibilityAnnouncement._( dataMessage, textDirection, assertiveness); _announcements.add(announcement); } } Future<void> _runTest( Future<void> Function() testBody, VoidCallback invariantTester, String description, ) { assert(inTest); // Set the handler only if there is currently none. if (TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .checkMockMessageHandler(SystemChannels.accessibility.name, null)) { _announcementHandler = _handleAnnouncementMessage; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockDecodedMessageHandler<dynamic>( SystemChannels.accessibility, _announcementHandler); } _oldExceptionHandler = FlutterError.onError; _oldStackTraceDemangler = FlutterError.demangleStackTrace; int exceptionCount = 0; // number of un-taken exceptions FlutterError.onError = (FlutterErrorDetails details) { if (_pendingExceptionDetails != null) { debugPrint = debugPrintOverride; // just in case the test overrides it -- otherwise we won't see the errors! if (exceptionCount == 0) { exceptionCount = 2; FlutterError.dumpErrorToConsole(_pendingExceptionDetails!, forceReport: true); } else { exceptionCount += 1; } FlutterError.dumpErrorToConsole(details, forceReport: true); _pendingExceptionDetails = FlutterErrorDetails( exception: 'Multiple exceptions ($exceptionCount) were detected during the running of the current test, and at least one was unexpected.', library: 'Flutter test framework', ); } else { reportExceptionNoticed(details); // mostly this is just a hook for the LiveTestWidgetsFlutterBinding _pendingExceptionDetails = details; } }; FlutterError.demangleStackTrace = (StackTrace stack) { // package:stack_trace uses ZoneSpecification.errorCallback to add useful // information to stack traces, meaning Trace and Chain classes can be // present. Because these StackTrace implementations do not follow the // format the framework expects, we convert them to a vm trace here. if (stack is stack_trace.Trace) { return stack.vmTrace; } if (stack is stack_trace.Chain) { return stack.toTrace().vmTrace; } return stack; }; final Completer<void> testCompleter = Completer<void>(); final VoidCallback testCompletionHandler = _createTestCompletionHandler(description, testCompleter); void handleUncaughtError(Object exception, StackTrace stack) { if (testCompleter.isCompleted) { // Well this is not a good sign. // Ideally, once the test has failed we would stop getting errors from the test. // However, if someone tries hard enough they could get in a state where this happens. // If we silently dropped these errors on the ground, nobody would ever know. So instead // we raise them and fail the test after it has already completed. debugPrint = debugPrintOverride; // just in case the test overrides it -- otherwise we won't see the error! reportTestException(FlutterErrorDetails( exception: exception, stack: stack, context: ErrorDescription('running a test (but after the test had completed)'), library: 'Flutter test framework', ), description); return; } // This is where test failures, e.g. those in expect(), will end up. // Specifically, runUnaryGuarded() will call this synchronously and // return our return value if _runTestBody fails synchronously (which it // won't, so this never happens), and Future will call this when the // Future completes with an error and it would otherwise call listeners // if the listener is in a different zone (which it would be for the // `whenComplete` handler below), or if the Future completes with an // error and the future has no listeners at all. // // This handler further calls the onError handler above, which sets // _pendingExceptionDetails. Nothing gets printed as a result of that // call unless we already had an exception pending, because in general // we want people to be able to cause the framework to report exceptions // and then use takeException to verify that they were really caught. // Now, if we actually get here, this isn't going to be one of those // cases. We only get here if the test has actually failed. So, once // we've carefully reported it, we then immediately end the test by // calling the testCompletionHandler in the _parentZone. // // We have to manually call testCompletionHandler because if the Future // library calls us, it is maybe _instead_ of calling a registered // listener from a different zone. In our case, that would be instead of // calling the whenComplete() listener below. // // We have to call it in the parent zone because if we called it in // _this_ zone, the test framework would find this zone was the current // zone and helpfully throw the error in this zone, causing us to be // directly called again. DiagnosticsNode treeDump; try { treeDump = rootElement?.toDiagnosticsNode() ?? DiagnosticsNode.message('<no tree>'); // We try to stringify the tree dump here (though we immediately discard the result) because // we want to make sure that if it can't be serialized, we replace it with a message that // says the tree could not be serialized. Otherwise, the real exception might get obscured // by side-effects of the underlying issues causing the tree dumping code to flail. treeDump.toStringDeep(); } catch (exception) { treeDump = DiagnosticsNode.message('<additional error caught while dumping tree: $exception>', level: DiagnosticLevel.error); } final List<DiagnosticsNode> omittedFrames = <DiagnosticsNode>[]; final int stackLinesToOmit = reportExpectCall(stack, omittedFrames); FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, context: ErrorDescription('running a test'), library: 'Flutter test framework', stackFilter: (Iterable<String> frames) { return FlutterError.defaultStackFilter(frames.skip(stackLinesToOmit)); }, informationCollector: () sync* { if (stackLinesToOmit > 0) { yield* omittedFrames; } if (showAppDumpInErrors) { yield DiagnosticsProperty<DiagnosticsNode>('At the time of the failure, the widget tree looked as follows', treeDump, linePrefix: '# ', style: DiagnosticsTreeStyle.flat); } if (description.isNotEmpty) { yield DiagnosticsProperty<String>('The test description was', description, style: DiagnosticsTreeStyle.errorProperty); } }, )); assert(_parentZone != null); assert(_pendingExceptionDetails != null, 'A test overrode FlutterError.onError but either failed to return it to its original state, or had unexpected additional errors that it could not handle. Typically, this is caused by using expect() before restoring FlutterError.onError.'); _parentZone!.run<void>(testCompletionHandler); } final ZoneSpecification errorHandlingZoneSpecification = ZoneSpecification( handleUncaughtError: (Zone self, ZoneDelegate parent, Zone zone, Object exception, StackTrace stack) { handleUncaughtError(exception, stack); } ); _parentZone = Zone.current; final Zone testZone = _parentZone!.fork(specification: errorHandlingZoneSpecification); testZone.runBinary<Future<void>, Future<void> Function(), VoidCallback>(_runTestBody, testBody, invariantTester) .whenComplete(testCompletionHandler); return testCompleter.future; } Future<void> _runTestBody(Future<void> Function() testBody, VoidCallback invariantTester) async { assert(inTest); // So that we can assert that it remains the same after the test finishes. _beforeTestCheckIntrinsicSizes = debugCheckIntrinsicSizes; runApp(Container(key: UniqueKey(), child: _preTestMessage)); // Reset the tree to a known state. await pump(); // Pretend that the first frame produced in the test body is the first frame // sent to the engine. resetFirstFrameSent(); final bool autoUpdateGoldensBeforeTest = autoUpdateGoldenFiles && !isBrowser; final TestExceptionReporter reportTestExceptionBeforeTest = reportTestException; final ErrorWidgetBuilder errorWidgetBuilderBeforeTest = ErrorWidget.builder; final bool shouldPropagateDevicePointerEventsBeforeTest = shouldPropagateDevicePointerEvents; // run the test await testBody(); asyncBarrier(); // drains the microtasks in `flutter test` mode (when using AutomatedTestWidgetsFlutterBinding) if (_pendingExceptionDetails == null) { // We only try to clean up and verify invariants if we didn't already // fail. If we got an exception already, then we instead leave everything // alone so that we don't cause more spurious errors. runApp(Container(key: UniqueKey(), child: _postTestMessage)); // Unmount any remaining widgets. await pump(); if (registerTestTextInput) { _testTextInput.unregister(); } invariantTester(); _verifyAutoUpdateGoldensUnset(autoUpdateGoldensBeforeTest && !isBrowser); _verifyReportTestExceptionUnset(reportTestExceptionBeforeTest); _verifyErrorWidgetBuilderUnset(errorWidgetBuilderBeforeTest); _verifyShouldPropagateDevicePointerEventsUnset(shouldPropagateDevicePointerEventsBeforeTest); _verifyInvariants(); } assert(inTest); asyncBarrier(); // When using AutomatedTestWidgetsFlutterBinding, this flushes the microtasks. } late bool _beforeTestCheckIntrinsicSizes; void _verifyInvariants() { assert(debugAssertNoTransientCallbacks( 'An animation is still running even after the widget tree was disposed.' )); assert(debugAssertNoPendingPerformanceModeRequests( 'A performance mode was requested and not disposed by a test.' )); assert(debugAssertNoTimeDilation( 'The timeDilation was changed and not reset by the test.' )); assert(debugAssertAllFoundationVarsUnset( 'The value of a foundation debug variable was changed by the test.', debugPrintOverride: debugPrintOverride, )); assert(debugAssertAllGesturesVarsUnset( 'The value of a gestures debug variable was changed by the test.', )); assert(debugAssertAllPaintingVarsUnset( 'The value of a painting debug variable was changed by the test.', debugDisableShadowsOverride: disableShadows, )); assert(debugAssertAllRenderVarsUnset( 'The value of a rendering debug variable was changed by the test.', debugCheckIntrinsicSizesOverride: _beforeTestCheckIntrinsicSizes, )); assert(debugAssertAllWidgetVarsUnset( 'The value of a widget debug variable was changed by the test.', )); assert(debugAssertAllSchedulerVarsUnset( 'The value of a scheduler debug variable was changed by the test.', )); assert(debugAssertAllServicesVarsUnset( 'The value of a services debug variable was changed by the test.', )); } void _verifyAutoUpdateGoldensUnset(bool valueBeforeTest) { assert(() { if (autoUpdateGoldenFiles != valueBeforeTest) { FlutterError.reportError(FlutterErrorDetails( exception: FlutterError( 'The value of autoUpdateGoldenFiles was changed by the test.', ), stack: StackTrace.current, library: 'Flutter test framework', )); } return true; }()); } void _verifyReportTestExceptionUnset(TestExceptionReporter valueBeforeTest) { assert(() { if (reportTestException != valueBeforeTest) { // We can't report this error to their modified reporter because we // can't be guaranteed that their reporter will cause the test to fail. // So we reset the error reporter to its initial value and then report // this error. reportTestException = valueBeforeTest; FlutterError.reportError(FlutterErrorDetails( exception: FlutterError( 'The value of reportTestException was changed by the test.', ), stack: StackTrace.current, library: 'Flutter test framework', )); } return true; }()); } void _verifyErrorWidgetBuilderUnset(ErrorWidgetBuilder valueBeforeTest) { assert(() { if (ErrorWidget.builder != valueBeforeTest) { FlutterError.reportError(FlutterErrorDetails( exception: FlutterError( 'The value of ErrorWidget.builder was changed by the test.', ), stack: StackTrace.current, library: 'Flutter test framework', )); } return true; }()); } void _verifyShouldPropagateDevicePointerEventsUnset(bool valueBeforeTest) { assert(() { if (shouldPropagateDevicePointerEvents != valueBeforeTest) { FlutterError.reportError(FlutterErrorDetails( exception: FlutterError( 'The value of shouldPropagateDevicePointerEvents was changed by the test.', ), stack: StackTrace.current, library: 'Flutter test framework', )); } return true; }()); } /// Called by the [testWidgets] function after a test is executed. void postTest() { assert(inTest); FlutterError.onError = _oldExceptionHandler; FlutterError.demangleStackTrace = _oldStackTraceDemangler; _pendingExceptionDetails = null; _parentZone = null; buildOwner!.focusManager.dispose(); if (TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .checkMockMessageHandler( SystemChannels.accessibility.name, _announcementHandler)) { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockDecodedMessageHandler(SystemChannels.accessibility, null); _announcementHandler = null; } _announcements = <CapturedAccessibilityAnnouncement>[]; ServicesBinding.instance.keyEventManager.keyMessageHandler = null; buildOwner!.focusManager = FocusManager()..registerGlobalHandlers(); // Disabling the warning because @visibleForTesting doesn't take the testing // framework itself into account, but we don't want it visible outside of // tests. // ignore: invalid_use_of_visible_for_testing_member RawKeyboard.instance.clearKeysPressed(); // ignore: invalid_use_of_visible_for_testing_member HardwareKeyboard.instance.clearState(); // ignore: invalid_use_of_visible_for_testing_member keyEventManager.clearState(); // ignore: invalid_use_of_visible_for_testing_member RendererBinding.instance.initMouseTracker(); assert(ServicesBinding.instance == WidgetsBinding.instance); // ignore: invalid_use_of_visible_for_testing_member ServicesBinding.instance.resetInternalState(); } } /// A variant of [TestWidgetsFlutterBinding] for executing tests typically /// the `flutter test` environment, unless it is an integration test. /// /// When doing integration test, [LiveTestWidgetsFlutterBinding] is utilized /// instead. /// /// This binding controls time, allowing tests to verify long /// animation sequences without having to execute them in real time. /// /// This class assumes it is always run in debug mode (since tests are always /// run in debug mode). /// /// See [TestWidgetsFlutterBinding] for a list of mixins that must be /// provided by the binding active while the test framework is /// running. class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { @override void initInstances() { super.initInstances(); _instance = this; binding.mockFlutterAssets(); } /// The current [AutomatedTestWidgetsFlutterBinding], if one has been created. /// /// The binding must be initialized before using this getter. If you /// need the binding to be constructed before calling [testWidgets], /// you can ensure a binding has been constructed by calling the /// [TestWidgetsFlutterBinding.ensureInitialized] function. static AutomatedTestWidgetsFlutterBinding get instance => BindingBase.checkInstance(_instance); static AutomatedTestWidgetsFlutterBinding? _instance; /// Returns an instance of the binding that implements /// [AutomatedTestWidgetsFlutterBinding]. If no binding has yet been /// initialized, the a new instance is created. /// /// Generally, there is no need to call this method. Use /// [TestWidgetsFlutterBinding.ensureInitialized] instead, as it /// will select the correct test binding implementation /// automatically. static AutomatedTestWidgetsFlutterBinding ensureInitialized() { if (AutomatedTestWidgetsFlutterBinding._instance == null) { AutomatedTestWidgetsFlutterBinding(); } return AutomatedTestWidgetsFlutterBinding.instance; } FakeAsync? _currentFakeAsync; // set in runTest; cleared in postTest Completer<void>? _pendingAsyncTasks; @override Clock get clock { assert(inTest); return _clock!; } Clock? _clock; @override DebugPrintCallback get debugPrintOverride => debugPrintSynchronously; @override bool get disableShadows => true; /// The value of [defaultTestTimeout] can be set to `None` to enable debugging /// flutter tests where we would not want to timeout the test. This is /// expected to be used by test tooling which can detect debug mode. @override test_package.Timeout defaultTestTimeout = const test_package.Timeout(Duration(minutes: 10)); @override bool get inTest => _currentFakeAsync != null; @override int get microtaskCount => _currentFakeAsync!.microtaskCount; @override Future<void> pump([ Duration? duration, EnginePhase newPhase = EnginePhase.sendSemanticsUpdate ]) { return TestAsyncUtils.guard<void>(() { assert(inTest); assert(_clock != null); if (duration != null) { _currentFakeAsync!.elapse(duration); } _phase = newPhase; if (hasScheduledFrame) { _currentFakeAsync!.flushMicrotasks(); handleBeginFrame(Duration( microseconds: _clock!.now().microsecondsSinceEpoch, )); _currentFakeAsync!.flushMicrotasks(); handleDrawFrame(); } _currentFakeAsync!.flushMicrotasks(); return Future<void>.value(); }); } @override Future<T?> runAsync<T>(Future<T> Function() callback) { assert(() { if (_pendingAsyncTasks == null) { return true; } fail( 'Reentrant call to runAsync() denied.\n' 'runAsync() was called, then before its future completed, it ' 'was called again. You must wait for the first returned future ' 'to complete before calling runAsync() again.' ); }()); final Zone realAsyncZone = Zone.current.fork( specification: ZoneSpecification( scheduleMicrotask: (Zone self, ZoneDelegate parent, Zone zone, void Function() f) { Zone.root.scheduleMicrotask(f); }, createTimer: (Zone self, ZoneDelegate parent, Zone zone, Duration duration, void Function() f) { return Zone.root.createTimer(duration, f); }, createPeriodicTimer: (Zone self, ZoneDelegate parent, Zone zone, Duration period, void Function(Timer timer) f) { return Zone.root.createPeriodicTimer(period, f); }, ), ); return realAsyncZone.run<Future<T?>>(() { final Completer<T?> result = Completer<T?>(); _pendingAsyncTasks = Completer<void>(); try { callback().then(result.complete).catchError( (Object exception, StackTrace stack) { FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'Flutter test framework', context: ErrorDescription('while running async test code'), informationCollector: () { return <DiagnosticsNode>[ ErrorHint('The exception was caught asynchronously.'), ]; }, )); result.complete(null); }, ); } catch (exception, stack) { FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'Flutter test framework', context: ErrorDescription('while running async test code'), informationCollector: () { return <DiagnosticsNode>[ ErrorHint('The exception was caught synchronously.'), ]; }, )); result.complete(null); } result.future.whenComplete(() { _pendingAsyncTasks!.complete(); _pendingAsyncTasks = null; }); return result.future; }); } @override void ensureFrameCallbacksRegistered() { // Leave PlatformDispatcher alone, do nothing. assert(platformDispatcher.onDrawFrame == null); assert(platformDispatcher.onBeginFrame == null); } @override void scheduleWarmUpFrame() { // We override the default version of this so that the application-startup warm-up frame // does not schedule timers which we might never get around to running. assert(inTest); handleBeginFrame(null); _currentFakeAsync!.flushMicrotasks(); handleDrawFrame(); _currentFakeAsync!.flushMicrotasks(); } @override void scheduleAttachRootWidget(Widget rootWidget) { // We override the default version of this so that the application-startup widget tree // build does not schedule timers which we might never get around to running. assert(inTest); attachRootWidget(rootWidget); _currentFakeAsync!.flushMicrotasks(); } @override Future<void> idle() { assert(inTest); final Future<void> result = super.idle(); _currentFakeAsync!.elapse(Duration.zero); return result; } int _firstFrameDeferredCount = 0; bool _firstFrameSent = false; @override bool get sendFramesToEngine => _firstFrameSent || _firstFrameDeferredCount == 0; @override void deferFirstFrame() { assert(_firstFrameDeferredCount >= 0); _firstFrameDeferredCount += 1; } @override void allowFirstFrame() { assert(_firstFrameDeferredCount > 0); _firstFrameDeferredCount -= 1; // Unlike in RendererBinding.allowFirstFrame we do not force a frame here // to give the test full control over frame scheduling. } @override void resetFirstFrameSent() { _firstFrameSent = false; } EnginePhase _phase = EnginePhase.sendSemanticsUpdate; // Cloned from RendererBinding.drawFrame() but with early-exit semantics. @override void drawFrame() { assert(inTest); try { debugBuildingDirtyElements = true; buildOwner!.buildScope(rootElement!); if (_phase != EnginePhase.build) { rootPipelineOwner.flushLayout(); if (_phase != EnginePhase.layout) { rootPipelineOwner.flushCompositingBits(); if (_phase != EnginePhase.compositingBits) { rootPipelineOwner.flushPaint(); if (_phase != EnginePhase.paint && sendFramesToEngine) { _firstFrameSent = true; for (final RenderView renderView in renderViews) { renderView.compositeFrame(); // this sends the bits to the GPU } if (_phase != EnginePhase.composite) { rootPipelineOwner.flushSemantics(); // this sends the semantics to the OS. assert(_phase == EnginePhase.flushSemantics || _phase == EnginePhase.sendSemanticsUpdate); } } } } } buildOwner!.finalizeTree(); } finally { debugBuildingDirtyElements = false; } } @override Future<void> delayed(Duration duration) { assert(_currentFakeAsync != null); _currentFakeAsync!.elapse(duration); return Future<void>.value(); } /// Simulates the synchronous passage of time, resulting from blocking or /// expensive calls. void elapseBlocking(Duration duration) { _currentFakeAsync!.elapseBlocking(duration); } @override Future<void> runTest( Future<void> Function() testBody, VoidCallback invariantTester, { String description = '', }) { assert(!inTest); assert(_currentFakeAsync == null); assert(_clock == null); final FakeAsync fakeAsync = FakeAsync(); _currentFakeAsync = fakeAsync; // reset in postTest _clock = fakeAsync.getClock(DateTime.utc(2015)); late Future<void> testBodyResult; fakeAsync.run((FakeAsync localFakeAsync) { assert(fakeAsync == _currentFakeAsync); assert(fakeAsync == localFakeAsync); testBodyResult = _runTest(testBody, invariantTester, description); assert(inTest); }); return Future<void>.microtask(() async { // testBodyResult is a Future that was created in the Zone of the // fakeAsync. This means that if we await it here, it will register a // microtask to handle the future _in the fake async zone_. We avoid this // by calling '.then' in the current zone. While flushing the microtasks // of the fake-zone below, the new future will be completed and can then // be used without fakeAsync. final Future<void> resultFuture = testBodyResult.then<void>((_) { // Do nothing. }); // Resolve interplay between fake async and real async calls. fakeAsync.flushMicrotasks(); while (_pendingAsyncTasks != null) { await _pendingAsyncTasks!.future; fakeAsync.flushMicrotasks(); } return resultFuture; }); } @override void asyncBarrier() { assert(_currentFakeAsync != null); _currentFakeAsync!.flushMicrotasks(); super.asyncBarrier(); } @override void _verifyInvariants() { super._verifyInvariants(); assert(inTest); bool timersPending = false; if (_currentFakeAsync!.periodicTimerCount != 0 || _currentFakeAsync!.nonPeriodicTimerCount != 0) { debugPrint('Pending timers:'); for (final FakeTimer timer in _currentFakeAsync!.pendingTimers) { debugPrint( 'Timer (duration: ${timer.duration}, ' 'periodic: ${timer.isPeriodic}), created:'); debugPrintStack(stackTrace: timer.creationStackTrace); debugPrint(''); } timersPending = true; } assert(!timersPending, 'A Timer is still pending even after the widget tree was disposed.'); assert(_currentFakeAsync!.microtaskCount == 0); // Shouldn't be possible. } @override void postTest() { super.postTest(); assert(_currentFakeAsync != null); assert(_clock != null); _clock = null; _currentFakeAsync = null; } } /// Available policies for how a [LiveTestWidgetsFlutterBinding] should paint /// frames. /// /// These values are set on the binding's /// [LiveTestWidgetsFlutterBinding.framePolicy] property. /// /// {@template flutter.flutter_test.LiveTestWidgetsFlutterBindingFramePolicy} /// The default is [LiveTestWidgetsFlutterBindingFramePolicy.fadePointers]. /// Setting this to anything other than /// [LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps] results in pumping /// extra frames, which might involve calling builders more, or calling paint /// callbacks more, etc, and might interfere with the test. If you know that /// your test won't be affected by this, you can set the policy to /// [LiveTestWidgetsFlutterBindingFramePolicy.fullyLive] or /// [LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive] in that particular /// file. /// /// To set a value while still allowing the test file to work as a normal test, /// add the following code to your test file at the top of your /// `void main() { }` function, before calls to [testWidgets]: /// /// ```dart /// TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); /// if (binding is LiveTestWidgetsFlutterBinding) { /// binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps; /// } /// ``` /// {@endtemplate} enum LiveTestWidgetsFlutterBindingFramePolicy { /// Strictly show only frames that are explicitly pumped. /// /// This most closely matches the [AutomatedTestWidgetsFlutterBinding] /// (the default binding for `flutter test`) behavior. onlyPumps, /// Show pumped frames, and additionally schedule and run frames to fade /// out the pointer crosshairs and other debugging information shown by /// the binding. /// /// This will schedule frames when pumped or when there has been some /// activity with [TestPointer]s. /// /// This can result in additional frames being pumped beyond those that /// the test itself requests, which can cause differences in behavior. fadePointers, /// Show every frame that the framework requests, even if the frames are not /// explicitly pumped. /// /// The major difference between [fullyLive] and [benchmarkLive] is the latter /// ignores frame requests by [WidgetTester.pump]. /// /// This can help with orienting the developer when looking at /// heavily-animated situations, and will almost certainly result in /// additional frames being pumped beyond those that the test itself requests, /// which can cause differences in behavior. fullyLive, /// Ignore any request to schedule a frame. /// /// This is intended to be used by benchmarks (hence the name) that drive the /// pipeline directly. It tells the binding to entirely ignore requests for a /// frame to be scheduled, while still allowing frames that are pumped /// directly to run (either by using [WidgetTester.pumpBenchmark] or invoking /// [PlatformDispatcher.onBeginFrame] and [PlatformDispatcher.onDrawFrame]). /// /// This allows all frame requests from the engine to be serviced, and allows /// all frame requests that are artificially triggered to be serviced, but /// ignores [SchedulerBinding.scheduleFrame] requests from the framework. /// Therefore animation won't run for this mode because the framework /// generates an animation by requesting new frames. /// /// The [SchedulerBinding.hasScheduledFrame] property will never be true in /// this mode. This can cause unexpected effects. For instance, /// [WidgetTester.pumpAndSettle] does not function in this mode, as it relies /// on the [SchedulerBinding.hasScheduledFrame] property to determine when the /// application has "settled". benchmark, /// Ignore any request from pump but respect other requests to schedule a /// frame. /// /// This is used for running the test on a device, where scheduling of new /// frames respects what the engine and the device needed. /// /// Compared to [fullyLive] this policy ignores the frame requests from /// [WidgetTester.pump] so that frame scheduling mimics that of the real /// environment, and avoids waiting for an artificially pumped frame. (For /// example, when driving the test in methods like /// [WidgetTester.handlePointerEventRecord] or [WidgetTester.fling].) /// /// This policy differs from [benchmark] in that it can be used for capturing /// animation frames requested by the framework. benchmarkLive, } /// A variant of [TestWidgetsFlutterBinding] for executing tests /// on a device, typically via `flutter run`, or via integration tests. /// This is intended to allow interactive test development. /// /// This is not the way to run a remote-control test. To run a test on /// a device from a development computer, see the [flutter_driver] /// package and the `flutter drive` command. /// /// When running tests using `flutter run`, consider adding the /// `--use-test-fonts` argument so that the fonts used match those used under /// `flutter test`. (This forces all text to use the "Ahem" font, which is a /// font that covers ASCII characters and gives them all the appearance of a /// square whose size equals the font size.) /// /// This binding overrides the default [SchedulerBinding] behavior to ensure /// that tests work in the same way in this environment as they would under the /// [AutomatedTestWidgetsFlutterBinding]. To override this (and see intermediate /// frames that the test does not explicitly trigger), set [framePolicy] to /// [LiveTestWidgetsFlutterBindingFramePolicy.fullyLive]. (This is likely to /// make tests fail, though, especially if e.g. they test how many times a /// particular widget was built.) The default behavior is to show pumped frames /// and a few additional frames when pointers are triggered (to animate the /// pointer crosshairs). /// /// This binding does not support the [EnginePhase] argument to /// [pump]. (There would be no point setting it to a value that /// doesn't trigger a paint, since then you could not see anything /// anyway.) /// /// See [TestWidgetsFlutterBinding] for a list of mixins that must be /// provided by the binding active while the test framework is /// running. class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { @override void initInstances() { super.initInstances(); _instance = this; RenderView.debugAddPaintCallback(_handleRenderViewPaint); } /// The current [LiveTestWidgetsFlutterBinding], if one has been created. /// /// The binding must be initialized before using this getter. If you /// need the binding to be constructed before calling [testWidgets], /// you can ensure a binding has been constructed by calling the /// [TestWidgetsFlutterBinding.ensureInitialized] function. static LiveTestWidgetsFlutterBinding get instance => BindingBase.checkInstance(_instance); static LiveTestWidgetsFlutterBinding? _instance; /// Returns an instance of the binding that implements /// [LiveTestWidgetsFlutterBinding]. If no binding has yet been /// initialized, the a new instance is created. /// /// Generally, there is no need to call this method. Use /// [TestWidgetsFlutterBinding.ensureInitialized] instead, as it /// will select the correct test binding implementation /// automatically. static LiveTestWidgetsFlutterBinding ensureInitialized() { if (LiveTestWidgetsFlutterBinding._instance == null) { LiveTestWidgetsFlutterBinding(); } return LiveTestWidgetsFlutterBinding.instance; } @override bool get inTest => _inTest; bool _inTest = false; @override Clock get clock => const Clock(); @override int get microtaskCount { // The Dart SDK doesn't report this number. assert(false, 'microtaskCount cannot be reported when running in real time'); return -1; } @override test_package.Timeout get defaultTestTimeout => test_package.Timeout.none; Completer<void>? _pendingFrame; bool _expectingFrame = false; bool _expectingFrameToReassemble = false; bool _viewNeedsPaint = false; bool _runningAsyncTasks = false; /// The strategy for [pump]ing and requesting new frames. /// /// The policy decides whether [pump] (with a duration) pumps a single frame /// (as would happen in a normal test environment using /// [AutomatedTestWidgetsFlutterBinding]), or pumps every frame that the /// system requests during an asynchronous pause (as would normally happen /// when running an application with [WidgetsFlutterBinding]). /// /// {@macro flutter.flutter_test.LiveTestWidgetsFlutterBindingFramePolicy} /// /// See [LiveTestWidgetsFlutterBindingFramePolicy]. LiveTestWidgetsFlutterBindingFramePolicy framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fadePointers; @override Future<void> delayed(Duration duration) { return Future<void>.delayed(duration); } @override void scheduleFrame() { if (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark) { // In benchmark mode, don't actually schedule any engine frames. return; } super.scheduleFrame(); } @override void scheduleForcedFrame() { if (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark) { // In benchmark mode, don't actually schedule any engine frames. return; } super.scheduleForcedFrame(); } @override Future<void> reassembleApplication() { _expectingFrameToReassemble = true; return super.reassembleApplication(); } bool? _doDrawThisFrame; @override void handleBeginFrame(Duration? rawTimeStamp) { assert(_doDrawThisFrame == null); if (_expectingFrame || _expectingFrameToReassemble || (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.fullyLive) || (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive) || (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark) || (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.fadePointers && _viewNeedsPaint)) { _doDrawThisFrame = true; super.handleBeginFrame(rawTimeStamp); } else { _doDrawThisFrame = false; } } @override void handleDrawFrame() { assert(_doDrawThisFrame != null); if (_doDrawThisFrame!) { super.handleDrawFrame(); } _doDrawThisFrame = null; _viewNeedsPaint = false; _expectingFrameToReassemble = false; if (_expectingFrame) { // set during pump assert(_pendingFrame != null); _pendingFrame!.complete(); // unlocks the test API _pendingFrame = null; _expectingFrame = false; } else if (framePolicy != LiveTestWidgetsFlutterBindingFramePolicy.benchmark) { platformDispatcher.scheduleFrame(); } } void _markViewsNeedPaint([int? viewId]) { _viewNeedsPaint = true; final Iterable<RenderView> toMark = viewId == null ? renderViews : renderViews.where((RenderView renderView) => renderView.flutterView.viewId == viewId); for (final RenderView renderView in toMark) { renderView.markNeedsPaint(); } } TextPainter? _label; static const TextStyle _labelStyle = TextStyle( fontFamily: 'sans-serif', fontSize: 10.0, ); void _setDescription(String value) { if (value.isEmpty) { _label = null; return; } // TODO(ianh): Figure out if the test name is actually RTL. _label ??= TextPainter(textAlign: TextAlign.left, textDirection: TextDirection.ltr); _label!.text = TextSpan(text: value, style: _labelStyle); _label!.layout(); _markViewsNeedPaint(); } final Expando<Map<int, _LiveTestPointerRecord>> _renderViewToPointerIdToPointerRecord = Expando<Map<int, _LiveTestPointerRecord>>(); void _handleRenderViewPaint(PaintingContext context, Offset offset, RenderView renderView) { assert(offset == Offset.zero); final Map<int, _LiveTestPointerRecord>? pointerIdToRecord = _renderViewToPointerIdToPointerRecord[renderView]; if (pointerIdToRecord != null && pointerIdToRecord.isNotEmpty) { final double radius = renderView.size.shortestSide * 0.05; final Path path = Path() ..addOval(Rect.fromCircle(center: Offset.zero, radius: radius)) ..moveTo(0.0, -radius * 2.0) ..lineTo(0.0, radius * 2.0) ..moveTo(-radius * 2.0, 0.0) ..lineTo(radius * 2.0, 0.0); final Canvas canvas = context.canvas; final Paint paint = Paint() ..strokeWidth = radius / 10.0 ..style = PaintingStyle.stroke; bool dirty = false; for (final _LiveTestPointerRecord record in pointerIdToRecord.values) { paint.color = record.color.withOpacity(record.decay < 0 ? (record.decay / (_kPointerDecay - 1)) : 1.0); canvas.drawPath(path.shift(record.position), paint); if (record.decay < 0) { dirty = true; } record.decay += 1; } pointerIdToRecord .keys .where((int pointer) => pointerIdToRecord[pointer]!.decay == 0) .toList() .forEach(pointerIdToRecord.remove); if (dirty) { scheduleMicrotask(() { _markViewsNeedPaint(renderView.flutterView.viewId); }); } } _label?.paint(context.canvas, offset - const Offset(0.0, 10.0)); } /// An object to which real device events should be routed. /// /// Normally, device events are silently dropped. However, if this property is /// set to a non-null value, then the events will be routed to its /// [HitTestDispatcher.dispatchEvent] method instead, unless /// [shouldPropagateDevicePointerEvents] is true. /// /// Events dispatched by [TestGesture] are not affected by this. HitTestDispatcher? deviceEventDispatcher; /// Dispatch an event to the targets found by a hit test on its position. /// /// If the [pointerEventSource] is [TestBindingEventSource.test], then /// the event is forwarded to [GestureBinding.dispatchEvent] as usual; /// additionally, down pointers are painted on the screen. /// /// If the [pointerEventSource] is [TestBindingEventSource.device], then /// the event, after being transformed to the local coordinate system, is /// forwarded to [deviceEventDispatcher]. @override void handlePointerEvent(PointerEvent event) { switch (pointerEventSource) { case TestBindingEventSource.test: RenderView? target; for (final RenderView renderView in renderViews) { if (renderView.flutterView.viewId == event.viewId) { target = renderView; break; } } if (target != null) { final _LiveTestPointerRecord? record = _renderViewToPointerIdToPointerRecord[target]?[event.pointer]; if (record != null) { record.position = event.position; if (!event.down) { record.decay = _kPointerDecay; } _markViewsNeedPaint(event.viewId); } else if (event.down) { _renderViewToPointerIdToPointerRecord[target] ??= <int, _LiveTestPointerRecord>{}; _renderViewToPointerIdToPointerRecord[target]![event.pointer] = _LiveTestPointerRecord( event.pointer, event.position, ); _markViewsNeedPaint(event.viewId); } } super.handlePointerEvent(event); case TestBindingEventSource.device: if (shouldPropagateDevicePointerEvents) { super.handlePointerEvent(event); break; } if (deviceEventDispatcher != null) { // The pointer events received with this source has a global position // (see [handlePointerEventForSource]). Transform it to the local // coordinate space used by the testing widgets. final RenderView renderView = renderViews.firstWhere((RenderView r) => r.flutterView.viewId == event.viewId); final PointerEvent localEvent = event.copyWith(position: globalToLocal(event.position, renderView)); withPointerEventSource(TestBindingEventSource.device, () => super.handlePointerEvent(localEvent) ); } } } @override void dispatchEvent(PointerEvent event, HitTestResult? hitTestResult) { switch (pointerEventSource) { case TestBindingEventSource.test: super.dispatchEvent(event, hitTestResult); case TestBindingEventSource.device: assert(hitTestResult != null || event is PointerAddedEvent || event is PointerRemovedEvent); if (shouldPropagateDevicePointerEvents) { super.dispatchEvent(event, hitTestResult); break; } assert(deviceEventDispatcher != null); if (hitTestResult != null) { deviceEventDispatcher!.dispatchEvent(event, hitTestResult); } } } @override Future<void> pump([ Duration? duration, EnginePhase newPhase = EnginePhase.sendSemanticsUpdate ]) { assert(newPhase == EnginePhase.sendSemanticsUpdate); assert(inTest); assert(!_expectingFrame); assert(_pendingFrame == null); if (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive) { // Ignore all pumps and just wait. return delayed(duration ?? Duration.zero); } return TestAsyncUtils.guard<void>(() { if (duration != null) { Timer(duration, () { _expectingFrame = true; scheduleFrame(); }); } else { _expectingFrame = true; scheduleFrame(); } _pendingFrame = Completer<void>(); return _pendingFrame!.future; }); } @override Future<T?> runAsync<T>(Future<T> Function() callback) async { assert(() { if (!_runningAsyncTasks) { return true; } fail( 'Reentrant call to runAsync() denied.\n' 'runAsync() was called, then before its future completed, it ' 'was called again. You must wait for the first returned future ' 'to complete before calling runAsync() again.' ); }()); _runningAsyncTasks = true; try { return await callback(); } catch (error, stack) { FlutterError.reportError(FlutterErrorDetails( exception: error, stack: stack, library: 'Flutter test framework', context: ErrorSummary('while running async test code'), )); return null; } finally { _runningAsyncTasks = false; } } @override Future<void> runTest( Future<void> Function() testBody, VoidCallback invariantTester, { String description = '', }) { assert(!inTest); _inTest = true; _setDescription(description); return _runTest(testBody, invariantTester, description); } @override void reportExceptionNoticed(FlutterErrorDetails exception) { final DebugPrintCallback testPrint = debugPrint; debugPrint = debugPrintOverride; debugPrint('(The following exception is now available via WidgetTester.takeException:)'); FlutterError.dumpErrorToConsole(exception, forceReport: true); debugPrint( '(If WidgetTester.takeException is called, the above exception will be ignored. ' 'If it is not, then the above exception will be dumped when another exception is ' 'caught by the framework or when the test ends, whichever happens first, and then ' 'the test will fail due to having not caught or expected the exception.)' ); debugPrint = testPrint; } @override void postTest() { super.postTest(); assert(!_expectingFrame); assert(_pendingFrame == null); _inTest = false; } @override ViewConfiguration createViewConfigurationFor(RenderView renderView) { final FlutterView view = renderView.flutterView; if (view == platformDispatcher.implicitView) { return TestViewConfiguration.fromView( size: _surfaceSize ?? _kDefaultTestViewportSize, view: view, ); } final double devicePixelRatio = view.devicePixelRatio; return TestViewConfiguration.fromView( size: view.physicalSize / devicePixelRatio, view: view, ); } @override Offset globalToLocal(Offset point, RenderView view) { // The method is expected to translate the given point expressed in logical // pixels in the global coordinate space to the local coordinate space (also // expressed in logical pixels). // The inverted transform translates from the global coordinate space in // physical pixels to the local coordinate space in logical pixels. final Matrix4 transform = view.configuration.toMatrix(); final double det = transform.invert(); assert(det != 0.0); // In order to use the transform, we need to translate the point first into // the physical coordinate space by applying the device pixel ratio. return MatrixUtils.transformPoint( transform, point * view.configuration.devicePixelRatio, ); } @override Offset localToGlobal(Offset point, RenderView view) { // The method is expected to translate the given point expressed in logical // pixels in the local coordinate space to the global coordinate space (also // expressed in logical pixels). // The transform translates from the local coordinate space in logical // pixels to the global coordinate space in physical pixels. final Matrix4 transform = view.configuration.toMatrix(); final Offset pointInPhysicalPixels = MatrixUtils.transformPoint(transform, point); // We need to apply the device pixel ratio to get back to logical pixels. return pointInPhysicalPixels / view.configuration.devicePixelRatio; } } /// A [ViewConfiguration] that pretends the display is of a particular size (in /// logical pixels). /// /// The resulting ViewConfiguration maps the given size onto the actual display /// using the [BoxFit.contain] algorithm. class TestViewConfiguration extends ViewConfiguration { /// Deprecated. Will be removed in a future version of Flutter. /// /// This property has been deprecated to prepare for Flutter's upcoming /// support for multiple views and multiple windows. /// /// Use [TestViewConfiguration.fromView] instead. @Deprecated( 'Use TestViewConfiguration.fromView instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.7.0-32.0.pre.' ) factory TestViewConfiguration({ Size size = _kDefaultTestViewportSize, ui.FlutterView? window, }) { return TestViewConfiguration.fromView(size: size, view: window ?? ui.window); } /// Creates a [TestViewConfiguration] with the given size and view. /// /// The [size] defaults to 800x600. TestViewConfiguration.fromView({required ui.FlutterView view, Size size = _kDefaultTestViewportSize}) : _paintMatrix = _getMatrix(size, view.devicePixelRatio, view), _physicalSize = view.physicalSize, super( devicePixelRatio: view.devicePixelRatio, logicalConstraints: BoxConstraints.tight(size), physicalConstraints: BoxConstraints.tight(size) * view.devicePixelRatio, ); static Matrix4 _getMatrix(Size size, double devicePixelRatio, ui.FlutterView window) { final double inverseRatio = devicePixelRatio / window.devicePixelRatio; final double actualWidth = window.physicalSize.width * inverseRatio; final double actualHeight = window.physicalSize.height * inverseRatio; final double desiredWidth = size.width; final double desiredHeight = size.height; double scale, shiftX, shiftY; if ((actualWidth / actualHeight) > (desiredWidth / desiredHeight)) { scale = actualHeight / desiredHeight; shiftX = (actualWidth - desiredWidth * scale) / 2.0; shiftY = 0.0; } else { scale = actualWidth / desiredWidth; shiftX = 0.0; shiftY = (actualHeight - desiredHeight * scale) / 2.0; } final Matrix4 matrix = Matrix4.compose( Vector3(shiftX, shiftY, 0.0), // translation Quaternion.identity(), // rotation Vector3(scale, scale, 1.0), // scale ); return matrix; } final Matrix4 _paintMatrix; @override Matrix4 toMatrix() => _paintMatrix.clone(); final Size _physicalSize; @override Size toPhysicalSize(Size logicalSize) => _physicalSize; @override String toString() => 'TestViewConfiguration'; } class _TestSamplingClock implements SamplingClock { _TestSamplingClock(this._clock); @override DateTime now() => _clock.now(); @override Stopwatch stopwatch() => _clock.stopwatch(); final Clock _clock; } const int _kPointerDecay = -2; class _LiveTestPointerRecord { _LiveTestPointerRecord( this.pointer, this.position, ) : color = HSVColor.fromAHSV(0.8, (35.0 * pointer) % 360.0, 1.0, 1.0).toColor(), decay = 1; final int pointer; final Color color; Offset position; int decay; // >0 means down, <0 means up, increases by one each time, removed at 0 }
flutter/packages/flutter_test/lib/src/binding.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/binding.dart", "repo_id": "flutter", "token_count": 27475 }
730
// 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 'dart:async'; import 'package:flutter/foundation.dart'; class _AsyncScope { _AsyncScope(this.creationStack, this.zone); final StackTrace creationStack; final Zone zone; } // Examples can assume: // late WidgetTester tester; /// Utility class for all the async APIs in the `flutter_test` library. /// /// This class provides checking for asynchronous APIs, allowing the library to /// verify that all the asynchronous APIs are properly `await`ed before calling /// another. /// /// For example, it prevents this kind of code: /// /// ```dart /// tester.pump(); // forgot to call "await"! /// tester.pump(); /// ``` /// /// ...by detecting, in the second call to `pump`, that it should actually be: /// /// ```dart /// await tester.pump(); /// await tester.pump(); /// ``` /// /// It does this while still allowing nested calls, e.g. so that you can /// call [expect] from inside callbacks. /// /// You can use this in your own test functions, if you have some asynchronous /// functions that must be used with "await". Wrap the contents of the function /// in a call to TestAsyncUtils.guard(), as follows: /// /// ```dart /// Future<void> myTestFunction() => TestAsyncUtils.guard(() async { /// // ... /// }); /// ``` abstract final class TestAsyncUtils { static const String _className = 'TestAsyncUtils'; static final List<_AsyncScope> _scopeStack = <_AsyncScope>[]; /// Calls the given callback in a new async scope. The callback argument is /// the asynchronous body of the calling method. The calling method is said to /// be "guarded". Nested calls to guarded methods from within the body of this /// one are fine, but calls to other guarded methods from outside the body of /// this one before this one has finished will throw an exception. /// /// This method first calls [guardSync]. static Future<T> guard<T>(Future<T> Function() body) { guardSync(); final Zone zone = Zone.current.fork( zoneValues: <dynamic, dynamic>{ _scopeStack: true, // so we can recognize this as our own zone } ); final _AsyncScope scope = _AsyncScope(StackTrace.current, zone); _scopeStack.add(scope); final Future<T> result = scope.zone.run<Future<T>>(body); late T resultValue; // This is set when the body of work completes with a result value. Future<T> completionHandler(dynamic error, StackTrace? stack) { assert(_scopeStack.isNotEmpty); assert(_scopeStack.contains(scope)); bool leaked = false; _AsyncScope closedScope; final List<DiagnosticsNode> information = <DiagnosticsNode>[]; while (_scopeStack.isNotEmpty) { closedScope = _scopeStack.removeLast(); if (closedScope == scope) { break; } if (!leaked) { information.add(ErrorSummary('Asynchronous call to guarded function leaked.')); information.add(ErrorHint('You must use "await" with all Future-returning test APIs.')); leaked = true; } final _StackEntry? originalGuarder = _findResponsibleMethod(closedScope.creationStack, 'guard', information); if (originalGuarder != null) { information.add(ErrorDescription( 'The test API method "${originalGuarder.methodName}" ' 'from class ${originalGuarder.className} ' 'was called from ${originalGuarder.callerFile} ' 'on line ${originalGuarder.callerLine}, ' 'but never completed before its parent scope closed.' )); } } if (leaked) { if (error != null) { information.add(DiagnosticsProperty<dynamic>( 'An uncaught exception may have caused the guarded function leak. The exception was', error, style: DiagnosticsTreeStyle.errorProperty, )); information.add(DiagnosticsStackTrace('The stack trace associated with this exception was', stack)); } throw FlutterError.fromParts(information); } if (error != null) { return Future<T>.error(error! as Object, stack); } return Future<T>.value(resultValue); } return result.then<T>( (T value) { resultValue = value; return completionHandler(null, null); }, onError: completionHandler, ); } static Zone? get _currentScopeZone { Zone? zone = Zone.current; while (zone != null) { if (zone[_scopeStack] == true) { return zone; } zone = zone.parent; } return null; } /// Verifies that there are no guarded methods currently pending (see [guard]). /// /// If a guarded method is currently pending, and this is not a call nested /// from inside that method's body (directly or indirectly), then this method /// will throw a detailed exception. static void guardSync() { if (_scopeStack.isEmpty) { // No scopes open, so we must be fine. return; } // Find the current TestAsyncUtils scope zone so we can see if it's the one we expect. final Zone? zone = _currentScopeZone; if (zone == _scopeStack.last.zone) { // We're still in the current scope zone. All good. return; } // If we get here, we know we've got a conflict on our hands. // We got an async barrier, but the current zone isn't the last scope that // we pushed on the stack. // Find which scope the conflict happened in, so that we know // which stack trace to report the conflict as starting from. // // For example, if we called an async method A, which ran its body in a // guarded block, and in its body it ran an async method B, which ran its // body in a guarded block, but we didn't await B, then in A's block we ran // an async method C, which ran its body in a guarded block, then we should // complain about the call to B then the call to C. BUT. If we called an async // method A, which ran its body in a guarded block, and in its body it ran // an async method B, which ran its body in a guarded block, but we didn't // await A, and then at the top level we called a method D, then we should // complain about the call to A then the call to D. // // In both examples, the scope stack would have two scopes. In the first // example, the current zone would be the zone of the _scopeStack[0] scope, // and we would want to show _scopeStack[1]'s creationStack. In the second // example, the current zone would not be in the _scopeStack, and we would // want to show _scopeStack[0]'s creationStack. int skipCount = 0; _AsyncScope candidateScope = _scopeStack.last; _AsyncScope scope; do { skipCount += 1; scope = candidateScope; if (skipCount >= _scopeStack.length) { if (zone == null) { break; } // Some people have reported reaching this point, but it's not clear // why. For now, just silently return. // TODO(ianh): If we ever get a test case that shows how we reach // this point, reduce it and report the error if there is one. return; } candidateScope = _scopeStack[_scopeStack.length - skipCount - 1]; } while (candidateScope.zone != zone); final List<DiagnosticsNode> information = <DiagnosticsNode>[ ErrorSummary('Guarded function conflict.'), ErrorHint('You must use "await" with all Future-returning test APIs.'), ]; final _StackEntry? originalGuarder = _findResponsibleMethod(scope.creationStack, 'guard', information); final _StackEntry? collidingGuarder = _findResponsibleMethod(StackTrace.current, 'guardSync', information); if (originalGuarder != null && collidingGuarder != null) { final String originalKind = originalGuarder.className == null ? 'function' : 'method'; String originalName; if (originalGuarder.className == null) { originalName = '$originalKind (${originalGuarder.methodName})'; information.add(ErrorDescription( 'The guarded "${originalGuarder.methodName}" function ' 'was called from ${originalGuarder.callerFile} ' 'on line ${originalGuarder.callerLine}.' )); } else { originalName = '$originalKind (${originalGuarder.className}.${originalGuarder.methodName})'; information.add(ErrorDescription( 'The guarded method "${originalGuarder.methodName}" ' 'from class ${originalGuarder.className} ' 'was called from ${originalGuarder.callerFile} ' 'on line ${originalGuarder.callerLine}.' )); } final String again = (originalGuarder.callerFile == collidingGuarder.callerFile) && (originalGuarder.callerLine == collidingGuarder.callerLine) ? 'again ' : ''; final String collidingKind = collidingGuarder.className == null ? 'function' : 'method'; String collidingName; if ((originalGuarder.className == collidingGuarder.className) && (originalGuarder.methodName == collidingGuarder.methodName)) { originalName = originalKind; collidingName = collidingKind; information.add(ErrorDescription( 'Then, it ' 'was called ${again}from ${collidingGuarder.callerFile} ' 'on line ${collidingGuarder.callerLine}.' )); } else if (collidingGuarder.className == null) { collidingName = '$collidingKind (${collidingGuarder.methodName})'; information.add(ErrorDescription( 'Then, the "${collidingGuarder.methodName}" function ' 'was called ${again}from ${collidingGuarder.callerFile} ' 'on line ${collidingGuarder.callerLine}.' )); } else { collidingName = '$collidingKind (${collidingGuarder.className}.${collidingGuarder.methodName})'; information.add(ErrorDescription( 'Then, the "${collidingGuarder.methodName}" method ' '${originalGuarder.className == collidingGuarder.className ? "(also from class ${collidingGuarder.className})" : "from class ${collidingGuarder.className}"} ' 'was called ${again}from ${collidingGuarder.callerFile} ' 'on line ${collidingGuarder.callerLine}.' )); } information.add(ErrorDescription( 'The first $originalName ' 'had not yet finished executing at the time that ' 'the second $collidingName ' 'was called. Since both are guarded, and the second was not a nested call inside the first, the ' 'first must complete its execution before the second can be called. Typically, this is achieved by ' 'putting an "await" statement in front of the call to the first.' )); if (collidingGuarder.className == null && collidingGuarder.methodName == 'expect') { information.add(ErrorHint( 'If you are confident that all test APIs are being called using "await", and ' 'this expect() call is not being called at the top level but is itself being ' 'called from some sort of callback registered before the ${originalGuarder.methodName} ' 'method was called, then consider using expectSync() instead.' )); } information.add(DiagnosticsStackTrace( '\nWhen the first $originalName was called, this was the stack', scope.creationStack, )); } else { information.add(DiagnosticsStackTrace( '\nWhen the first function was called, this was the stack', scope.creationStack, )); } throw FlutterError.fromParts(information); } /// Verifies that there are no guarded methods currently pending (see [guard]). /// /// This is used at the end of tests to ensure that nothing leaks out of the test. static void verifyAllScopesClosed() { if (_scopeStack.isNotEmpty) { final List<DiagnosticsNode> information = <DiagnosticsNode>[ ErrorSummary('Asynchronous call to guarded function leaked.'), ErrorHint('You must use "await" with all Future-returning test APIs.'), ]; for (final _AsyncScope scope in _scopeStack) { final _StackEntry? guarder = _findResponsibleMethod(scope.creationStack, 'guard', information); if (guarder != null) { information.add(ErrorDescription( 'The guarded method "${guarder.methodName}" ' '${guarder.className != null ? "from class ${guarder.className} " : ""}' 'was called from ${guarder.callerFile} ' 'on line ${guarder.callerLine}, ' 'but never completed before its parent scope closed.' )); } } throw FlutterError.fromParts(information); } } static bool _stripAsynchronousSuspensions(String line) { return line != '<asynchronous suspension>'; } static _StackEntry? _findResponsibleMethod(StackTrace rawStack, String method, List<DiagnosticsNode> information) { assert(method == 'guard' || method == 'guardSync'); // Web/JavaScript stack traces use a different format. if (kIsWeb) { return null; } final List<String> stack = rawStack.toString().split('\n').where(_stripAsynchronousSuspensions).toList(); assert(stack.last == ''); stack.removeLast(); final RegExp getClassPattern = RegExp(r'^#[0-9]+ +([^. ]+)'); Match? lineMatch; int index = -1; do { // skip past frames that are from this class index += 1; assert(index < stack.length); lineMatch = getClassPattern.matchAsPrefix(stack[index]); assert(lineMatch != null); lineMatch = lineMatch!; assert(lineMatch.groupCount == 1); } while (lineMatch.group(1) == _className); // try to parse the stack to find the interesting frame if (index < stack.length) { final RegExp guardPattern = RegExp(r'^#[0-9]+ +(?:([^. ]+)\.)?([^. ]+)'); final Match? guardMatch = guardPattern.matchAsPrefix(stack[index]); // find the class that called us if (guardMatch != null) { assert(guardMatch.groupCount == 2); final String? guardClass = guardMatch.group(1); // might be null final String? guardMethod = guardMatch.group(2); while (index < stack.length) { // find the last stack frame that called the class that called us lineMatch = getClassPattern.matchAsPrefix(stack[index]); if (lineMatch != null) { assert(lineMatch.groupCount == 1); if (lineMatch.group(1) == (guardClass ?? guardMethod)) { index += 1; continue; } } break; } if (index < stack.length) { final RegExp callerPattern = RegExp(r'^#[0-9]+ .* \((.+?):([0-9]+)(?::[0-9]+)?\)$'); final Match? callerMatch = callerPattern.matchAsPrefix(stack[index]); // extract the caller's info if (callerMatch != null) { assert(callerMatch.groupCount == 2); final String? callerFile = callerMatch.group(1); final String? callerLine = callerMatch.group(2); return _StackEntry(guardClass, guardMethod, callerFile, callerLine); } else { // One reason you might get here is if the guarding method was called directly from // a 'dart:' API, like from the Future/microtask mechanism, because dart: URLs in the // stack trace don't have a column number and so don't match the regexp above. information.add(ErrorSummary('(Unable to parse the stack frame of the method that called the method that called $_className.$method(). The stack may be incomplete or bogus.)')); information.add(ErrorDescription(stack[index])); } } else { information.add(ErrorSummary('(Unable to find the stack frame of the method that called the method that called $_className.$method(). The stack may be incomplete or bogus.)')); } } else { information.add(ErrorSummary('(Unable to parse the stack frame of the method that called $_className.$method(). The stack may be incomplete or bogus.)')); information.add(ErrorDescription(stack[index])); } } else { information.add(ErrorSummary('(Unable to find the method that called $_className.$method(). The stack may be incomplete or bogus.)')); } return null; } } class _StackEntry { const _StackEntry(this.className, this.methodName, this.callerFile, this.callerLine); final String? className; final String? methodName; final String? callerFile; final String? callerLine; }
flutter/packages/flutter_test/lib/src/test_async_utils.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/test_async_utils.dart", "repo_id": "flutter", "token_count": 6091 }
731
// 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 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stack_trace/stack_trace.dart' as stack_trace; Future<void> main() async { test('demangles stacks', () async { // Test that the tester bindings unmangle stacks that come in as // package:stack_trace types. // Uses runTest directly so that the test does not get hung up waiting for // the error reporter to be reset to the original one. final Completer<FlutterErrorDetails> errorCompleter = Completer<FlutterErrorDetails>(); final TestExceptionReporter oldReporter = reportTestException; reportTestException = (FlutterErrorDetails details, String testDescription) { errorCompleter.complete(details); reportTestException = oldReporter; }; final AutomatedTestWidgetsFlutterBinding binding = AutomatedTestWidgetsFlutterBinding(); await binding.runTest(() async { final Completer<String> completer = Completer<String>(); completer.future.then( (String value) {}, onError: (Object error, StackTrace stack) { assert(stack is stack_trace.Chain); FlutterError.reportError(FlutterErrorDetails( exception: error, stack: stack, )); } ); completer.completeError(const CustomException()); }, () { }); final FlutterErrorDetails details = await errorCompleter.future; expect(details, isNotNull); expect(details.exception, isA<CustomException>()); reportTestException = oldReporter; }); } class CustomException implements Exception { const CustomException(); }
flutter/packages/flutter_test/test/bindings_async_gap_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/bindings_async_gap_test.dart", "repo_id": "flutter", "token_count": 610 }
732
// 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 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; const List<Widget> fooBarTexts = <Text>[ Text('foo', textDirection: TextDirection.ltr), Text('bar', textDirection: TextDirection.ltr), ]; void main() { group('image', () { testWidgets('finds Image widgets', (WidgetTester tester) async { await tester .pumpWidget(_boilerplate(Image(image: FileImage(File('test'))))); expect(find.image(FileImage(File('test'))), findsOneWidget); }); testWidgets('finds Button widgets with Image', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(ElevatedButton( onPressed: null, child: Image(image: FileImage(File('test'))), ))); expect(find.widgetWithImage(ElevatedButton, FileImage(File('test'))), findsOneWidget); }); }); group('text', () { testWidgets('finds Text widgets', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate( const Text('test'), )); expect(find.text('test'), findsOneWidget); }); testWidgets('finds Text.rich widgets', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(const Text.rich( TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'e'), TextSpan(text: 'st'), ], ), ))); expect(find.text('test'), findsOneWidget); }); group('findRichText', () { testWidgets('finds RichText widgets when enabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(RichText( text: const TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'est'), ], ), ))); expect(find.text('test', findRichText: true), findsOneWidget); }); testWidgets('finds Text widgets once when enabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(const Text('test2'))); expect(find.text('test2', findRichText: true), findsOneWidget); }); testWidgets('does not find RichText widgets when disabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(RichText( text: const TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'est'), ], ), ))); expect(find.text('test'), findsNothing); }); testWidgets( 'does not find Text and RichText separated by semantics widgets twice', (WidgetTester tester) async { // If rich: true found both Text and RichText, this would find two widgets. await tester.pumpWidget(_boilerplate( const Text('test', semanticsLabel: 'foo'), )); expect(find.text('test'), findsOneWidget); }); testWidgets('finds Text.rich widgets when enabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(const Text.rich( TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'est'), TextSpan(text: '3'), ], ), ))); expect(find.text('test3', findRichText: true), findsOneWidget); }); testWidgets('finds Text.rich widgets when disabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(const Text.rich( TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'est'), TextSpan(text: '3'), ], ), ))); expect(find.text('test3'), findsOneWidget); }); }); }); group('textContaining', () { testWidgets('finds Text widgets', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate( const Text('this is a test'), )); expect(find.textContaining(RegExp(r'test')), findsOneWidget); expect(find.textContaining('test'), findsOneWidget); expect(find.textContaining('a'), findsOneWidget); expect(find.textContaining('s'), findsOneWidget); }); testWidgets('finds Text.rich widgets', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(const Text.rich( TextSpan( text: 'this', children: <TextSpan>[ TextSpan(text: 'is'), TextSpan(text: 'a'), TextSpan(text: 'test'), ], ), ))); expect(find.textContaining(RegExp(r'isatest')), findsOneWidget); expect(find.textContaining('isatest'), findsOneWidget); }); testWidgets('finds EditableText widgets', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Scaffold( body: _boilerplate(TextField( controller: TextEditingController()..text = 'this is test', )), ), )); expect(find.textContaining(RegExp(r'test')), findsOneWidget); expect(find.textContaining('test'), findsOneWidget); }); group('findRichText', () { testWidgets('finds RichText widgets when enabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(RichText( text: const TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'est'), ], ), ))); expect(find.textContaining('te', findRichText: true), findsOneWidget); }); testWidgets('finds Text widgets once when enabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(const Text('test2'))); expect(find.textContaining('tes', findRichText: true), findsOneWidget); }); testWidgets('does not find RichText widgets when disabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(RichText( text: const TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'est'), ], ), ))); expect(find.textContaining('te'), findsNothing); }); testWidgets( 'does not find Text and RichText separated by semantics widgets twice', (WidgetTester tester) async { // If rich: true found both Text and RichText, this would find two widgets. await tester.pumpWidget(_boilerplate( const Text('test', semanticsLabel: 'foo'), )); expect(find.textContaining('tes'), findsOneWidget); }); testWidgets('finds Text.rich widgets when enabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(const Text.rich( TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'est'), TextSpan(text: '3'), ], ), ))); expect(find.textContaining('t3', findRichText: true), findsOneWidget); }); testWidgets('finds Text.rich widgets when disabled', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate(const Text.rich( TextSpan( text: 't', children: <TextSpan>[ TextSpan(text: 'est'), TextSpan(text: '3'), ], ), ))); expect(find.textContaining('t3'), findsOneWidget); }); }); }); group('semantics', () { testWidgets('Throws StateError if semantics are not enabled', (WidgetTester tester) async { expect(() => find.bySemanticsLabel('Add'), throwsStateError); }, semanticsEnabled: false); testWidgets('finds Semantically labeled widgets', (WidgetTester tester) async { final SemanticsHandle semanticsHandle = tester.ensureSemantics(); await tester.pumpWidget(_boilerplate( Semantics( label: 'Add', button: true, child: const TextButton( onPressed: null, child: Text('+'), ), ), )); expect(find.bySemanticsLabel('Add'), findsOneWidget); semanticsHandle.dispose(); }); testWidgets('finds Semantically labeled widgets by RegExp', (WidgetTester tester) async { final SemanticsHandle semanticsHandle = tester.ensureSemantics(); await tester.pumpWidget(_boilerplate( Semantics( container: true, child: const Row(children: <Widget>[ Text('Hello'), Text('World'), ]), ), )); expect(find.bySemanticsLabel('Hello'), findsNothing); expect(find.bySemanticsLabel(RegExp(r'^Hello')), findsOneWidget); semanticsHandle.dispose(); }); testWidgets('finds Semantically labeled widgets without explicit Semantics', (WidgetTester tester) async { final SemanticsHandle semanticsHandle = tester.ensureSemantics(); await tester .pumpWidget(_boilerplate(const SimpleCustomSemanticsWidget('Foo'))); expect(find.bySemanticsLabel('Foo'), findsOneWidget); semanticsHandle.dispose(); }); }); group('hitTestable', () { testWidgets('excludes non-hit-testable widgets', (WidgetTester tester) async { await tester.pumpWidget( _boilerplate(IndexedStack( sizing: StackFit.expand, children: <Widget>[ GestureDetector( key: const ValueKey<int>(0), behavior: HitTestBehavior.opaque, onTap: () {}, child: const SizedBox.expand(), ), GestureDetector( key: const ValueKey<int>(1), behavior: HitTestBehavior.opaque, onTap: () {}, child: const SizedBox.expand(), ), ], )), ); expect(find.byType(GestureDetector), findsOneWidget); expect(find.byType(GestureDetector, skipOffstage: false), findsNWidgets(2)); final Finder hitTestable = find.byType(GestureDetector, skipOffstage: false).hitTestable(); expect(hitTestable, findsOneWidget); expect(tester.widget(hitTestable).key, const ValueKey<int>(0)); }); }); group('text range finders', () { testWidgets('basic text span test', (WidgetTester tester) async { await tester.pumpWidget( _boilerplate(const IndexedStack( sizing: StackFit.expand, children: <Widget>[ Text.rich(TextSpan( text: 'sub', children: <InlineSpan>[ TextSpan(text: 'stringsub'), TextSpan(text: 'stringsub'), TextSpan(text: 'stringsub'), ], )), Text('substringsub'), ], )), ); expect(find.textRange.ofSubstring('substringsub'), findsExactly(2)); // Pattern skips overlapping matches. expect(find.textRange.ofSubstring('substringsub').first.evaluate().single.textRange, const TextRange(start: 0, end: 12)); expect(find.textRange.ofSubstring('substringsub').last.evaluate().single.textRange, const TextRange(start: 18, end: 30)); expect( find.textRange.ofSubstring('substringsub').first.evaluate().single.renderObject, find.textRange.ofSubstring('substringsub').last.evaluate().single.renderObject, ); expect(find.textRange.ofSubstring('substringsub', skipOffstage: false), findsExactly(3)); }); testWidgets('basic text span test', (WidgetTester tester) async { await tester.pumpWidget( _boilerplate(const IndexedStack( sizing: StackFit.expand, children: <Widget>[ Text.rich(TextSpan( text: 'sub', children: <InlineSpan>[ TextSpan(text: 'stringsub'), TextSpan(text: 'stringsub'), TextSpan(text: 'stringsub'), ], )), Text('substringsub'), ], )), ); expect(find.textRange.ofSubstring('substringsub'), findsExactly(2)); // Pattern skips overlapping matches. expect(find.textRange.ofSubstring('substringsub').first.evaluate().single.textRange, const TextRange(start: 0, end: 12)); expect(find.textRange.ofSubstring('substringsub').last.evaluate().single.textRange, const TextRange(start: 18, end: 30)); expect( find.textRange.ofSubstring('substringsub').first.evaluate().single.renderObject, find.textRange.ofSubstring('substringsub').last.evaluate().single.renderObject, ); expect(find.textRange.ofSubstring('substringsub', skipOffstage: false), findsExactly(3)); }); testWidgets('descendentOf', (WidgetTester tester) async { await tester.pumpWidget( _boilerplate( const Column( children: <Widget>[ Text.rich(TextSpan(text: 'text')), Text.rich(TextSpan(text: 'text')), ], ), ), ); expect(find.textRange.ofSubstring('text'), findsExactly(2)); expect(find.textRange.ofSubstring('text', descendentOf: find.text('text').first), findsOne); }); testWidgets('finds only static text for now', (WidgetTester tester) async { await tester.pumpWidget( _boilerplate( EditableText( controller: TextEditingController(text: 'text'), focusNode: FocusNode(), style: const TextStyle(), cursorColor: const Color(0x00000000), backgroundCursorColor: const Color(0x00000000), ) ), ); expect(find.textRange.ofSubstring('text'), findsNothing); }); }); testWidgets('ChainedFinders chain properly', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); await tester.pumpWidget( _boilerplate(Column( children: <Widget>[ Container( key: key1, child: const Text('1'), ), const Text('2'), ], )), ); // Get the text back. By correctly chaining the descendant finder's // candidates, it should find 1 instead of 2. If the _LastFinder wasn't // correctly chained after the descendant's candidates, the last element // with a Text widget would have been 2. final Text text = find .descendant( of: find.byKey(key1), matching: find.byType(Text), ) .last .evaluate() .single .widget as Text; expect(text.data, '1'); }); testWidgets('finds multiple subtypes', (WidgetTester tester) async { await tester.pumpWidget(_boilerplate( Row(children: <Widget>[ const Column(children: <Widget>[ Text('Hello'), Text('World'), ]), Column(children: <Widget>[ Image(image: FileImage(File('test'))), ]), const Column(children: <Widget>[ SimpleGenericWidget<int>(child: Text('one')), SimpleGenericWidget<double>(child: Text('pi')), SimpleGenericWidget<String>(child: Text('two')), ]), ]), )); expect(find.bySubtype<Row>(), findsOneWidget); expect(find.bySubtype<Column>(), findsNWidgets(3)); // Finds both rows and columns. expect(find.bySubtype<Flex>(), findsNWidgets(4)); // Finds only the requested generic subtypes. expect(find.bySubtype<SimpleGenericWidget<int>>(), findsOneWidget); expect(find.bySubtype<SimpleGenericWidget<num>>(), findsNWidgets(2)); expect(find.bySubtype<SimpleGenericWidget<Object>>(), findsNWidgets(3)); // Finds all widgets. final int totalWidgetCount = find.byWidgetPredicate((_) => true).evaluate().length; expect(find.bySubtype<Widget>(), findsNWidgets(totalWidgetCount)); }); group('find.byElementPredicate', () { testWidgets('fails with a custom description in the message', (WidgetTester tester) async { await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr)); const String customDescription = 'custom description'; late TestFailure failure; try { expect(find.byElementPredicate((_) => false, description: customDescription), findsOneWidget); } on TestFailure catch (e) { failure = e; } expect(failure, isNotNull); expect(failure.message, contains('Actual: _ElementPredicateWidgetFinder:<Found 0 widgets with $customDescription')); }); }); group('find.byWidgetPredicate', () { testWidgets('fails with a custom description in the message', (WidgetTester tester) async { await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr)); const String customDescription = 'custom description'; late TestFailure failure; try { expect(find.byWidgetPredicate((_) => false, description: customDescription), findsOneWidget); } on TestFailure catch (e) { failure = e; } expect(failure, isNotNull); expect(failure.message, contains('Actual: _WidgetPredicateWidgetFinder:<Found 0 widgets with $customDescription')); }); }); group('find.descendant', () { testWidgets('finds one descendant', (WidgetTester tester) async { await tester.pumpWidget(const Row( textDirection: TextDirection.ltr, children: <Widget>[ Column(children: fooBarTexts), ], )); expect(find.descendant( of: find.widgetWithText(Row, 'foo'), matching: find.text('bar'), ), findsOneWidget); }); testWidgets('finds two descendants with different ancestors', (WidgetTester tester) async { await tester.pumpWidget(const Row( textDirection: TextDirection.ltr, children: <Widget>[ Column(children: fooBarTexts), Column(children: fooBarTexts), ], )); expect(find.descendant( of: find.widgetWithText(Column, 'foo'), matching: find.text('bar'), ), findsNWidgets(2)); }); testWidgets('fails with a descriptive message', (WidgetTester tester) async { await tester.pumpWidget(const Row( textDirection: TextDirection.ltr, children: <Widget>[ Column(children: <Text>[Text('foo', textDirection: TextDirection.ltr)]), Text('bar', textDirection: TextDirection.ltr), ], )); late TestFailure failure; try { expect(find.descendant( of: find.widgetWithText(Column, 'foo'), matching: find.text('bar'), ), findsOneWidget); } on TestFailure catch (e) { failure = e; } expect(failure, isNotNull); expect( failure.message, contains( 'Actual: _DescendantWidgetFinder:<Found 0 widgets with text "bar" descending from widgets with type "Column" that are ancestors of widgets with text "foo"', ), ); }); }); group('find.ancestor', () { testWidgets('finds one ancestor', (WidgetTester tester) async { await tester.pumpWidget(const Row( textDirection: TextDirection.ltr, children: <Widget>[ Column(children: fooBarTexts), ], )); expect(find.ancestor( of: find.text('bar'), matching: find.widgetWithText(Row, 'foo'), ), findsOneWidget); }); testWidgets('finds two matching ancestors, one descendant', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Row( children: <Widget>[ Row(children: fooBarTexts), ], ), ), ); expect(find.ancestor( of: find.text('bar'), matching: find.byType(Row), ), findsNWidgets(2)); }); testWidgets('fails with a descriptive message', (WidgetTester tester) async { await tester.pumpWidget(const Row( textDirection: TextDirection.ltr, children: <Widget>[ Column(children: <Text>[Text('foo', textDirection: TextDirection.ltr)]), Text('bar', textDirection: TextDirection.ltr), ], )); late TestFailure failure; try { expect(find.ancestor( of: find.text('bar'), matching: find.widgetWithText(Column, 'foo'), ), findsOneWidget); } on TestFailure catch (e) { failure = e; } expect(failure, isNotNull); expect( failure.message, contains( 'Actual: _AncestorWidgetFinder:<Found 0 widgets with type "Column" that are ancestors of widgets with text "foo" that are ancestors of widgets with text "bar"', ), ); }); testWidgets('Root not matched by default', (WidgetTester tester) async { await tester.pumpWidget(const Row( textDirection: TextDirection.ltr, children: <Widget>[ Column(children: fooBarTexts), ], )); expect(find.ancestor( of: find.byType(Column), matching: find.widgetWithText(Column, 'foo'), ), findsNothing); }); testWidgets('Match the root', (WidgetTester tester) async { await tester.pumpWidget(const Row( textDirection: TextDirection.ltr, children: <Widget>[ Column(children: fooBarTexts), ], )); expect(find.descendant( of: find.byType(Column), matching: find.widgetWithText(Column, 'foo'), matchRoot: true, ), findsOneWidget); }); testWidgets('is fast in deep tree', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: _deepWidgetTree( depth: 1000, child: Row( children: <Widget>[ _deepWidgetTree( depth: 1000, child: const Column(children: fooBarTexts), ), ], ), ), ), ); expect(find.ancestor( of: find.text('bar'), matching: find.byType(Row), ), findsOneWidget); }); }); group('CommonSemanticsFinders', () { final Widget semanticsTree = _boilerplate( Semantics( container: true, header: true, readOnly: true, onCopy: () {}, onLongPress: () {}, value: 'value1', hint: 'hint1', label: 'label1', child: Semantics( container: true, textField: true, onSetText: (_) { }, onPaste: () { }, onLongPress: () { }, value: 'value2', hint: 'hint2', label: 'label2', child: Semantics( container: true, readOnly: true, onCopy: () {}, value: 'value3', hint: 'hint3', label: 'label3', child: Semantics( container: true, readOnly: true, onLongPress: () { }, value: 'value4', hint: 'hint4', label: 'label4', child: Semantics( container: true, onLongPress: () { }, onCopy: () {}, value: 'value5', hint: 'hint5', label: 'label5' ), ), ) ), ), ); group('ancestor', () { testWidgets('finds matching ancestor nodes', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final FinderBase<SemanticsNode> finder = find.semantics.ancestor( of: find.semantics.byLabel('label4'), matching: find.semantics.byAction(SemanticsAction.copy), ); expect(finder, findsExactly(2)); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final FinderBase<SemanticsNode> finder = find.semantics.ancestor( of: find.semantics.byLabel('label4'), matching: find.semantics.byAction(SemanticsAction.copy), ); try { expect(finder, findsExactly(3)); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _AncestorSemanticsFinder:<Found 2 SemanticsNodes with action "SemanticsAction.copy" that are ancestors of SemanticsNodes with label "label4"')); }); }); group('descendant', () { testWidgets('finds matching descendant nodes', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final FinderBase<SemanticsNode> finder = find.semantics.descendant( of: find.semantics.byLabel('label4'), matching: find.semantics.byAction(SemanticsAction.copy), ); expect(finder, findsOne); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final FinderBase<SemanticsNode> finder = find.semantics.descendant( of: find.semantics.byLabel('label4'), matching: find.semantics.byAction(SemanticsAction.copy), ); try { expect(finder, findsNothing); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _DescendantSemanticsFinder:<Found 1 SemanticsNode with action "SemanticsAction.copy" descending from SemanticsNode with label "label4"')); }); }); group('byPredicate', () { testWidgets('finds nodes matching given predicate', (WidgetTester tester) async { final RegExp replaceRegExp = RegExp(r'^[^\d]+'); await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byPredicate( (SemanticsNode node) { final int labelNum = int.tryParse(node.label.replaceAll(replaceRegExp, '')) ?? -1; return labelNum > 1; }, ); expect(finder, findsExactly(4)); }); testWidgets('fails with default message', (WidgetTester tester) async { late TestFailure failure; final RegExp replaceRegExp = RegExp(r'^[^\d]+'); await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byPredicate( (SemanticsNode node) { final int labelNum = int.tryParse(node.label.replaceAll(replaceRegExp, '')) ?? -1; return labelNum > 1; }, ); try { expect(finder, findsExactly(5)); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _PredicateSemanticsFinder:<Found 4 matching semantics predicate')); }); testWidgets('fails with given message', (WidgetTester tester) async { late TestFailure failure; const String expected = 'custom error message'; final RegExp replaceRegExp = RegExp(r'^[^\d]+'); await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byPredicate( (SemanticsNode node) { final int labelNum = int.tryParse(node.label.replaceAll(replaceRegExp, '')) ?? -1; return labelNum > 1; }, describeMatch: (_) => expected, ); try { expect(finder, findsExactly(5)); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains(expected)); }); }); group('byLabel', () { testWidgets('finds nodes with matching label using String', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byLabel('label3'); expect(finder, findsOne); expect(finder.found.first.label, 'label3'); }); testWidgets('finds nodes with matching label using RegEx', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byLabel(RegExp('^label.*')); expect(finder, findsExactly(5)); expect(finder.found.every((SemanticsNode node) => node.label.startsWith('label')), isTrue); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byLabel('label3'); try { expect(finder, findsNothing); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _PredicateSemanticsFinder:<Found 1 SemanticsNode with label "label3"')); }); }); group('byValue', () { testWidgets('finds nodes with matching value using String', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byValue('value3'); expect(finder, findsOne); expect(finder.found.first.value, 'value3'); }); testWidgets('finds nodes with matching value using RegEx', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byValue(RegExp('^value.*')); expect(finder, findsExactly(5)); expect(finder.found.every((SemanticsNode node) => node.value.startsWith('value')), isTrue); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byValue('value3'); try { expect(finder, findsNothing); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _PredicateSemanticsFinder:<Found 1 SemanticsNode with value "value3"')); }); }); group('byHint', () { testWidgets('finds nodes with matching hint using String', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byHint('hint3'); expect(finder, findsOne); expect(finder.found.first.hint, 'hint3'); }); testWidgets('finds nodes with matching hint using RegEx', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byHint(RegExp('^hint.*')); expect(finder, findsExactly(5)); expect(finder.found.every((SemanticsNode node) => node.hint.startsWith('hint')), isTrue); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byHint('hint3'); try { expect(finder, findsNothing); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _PredicateSemanticsFinder:<Found 1 SemanticsNode with hint "hint3"')); }); }); group('byAction', () { testWidgets('finds nodes with matching action', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byAction(SemanticsAction.copy); expect(finder, findsExactly(3)); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byAction(SemanticsAction.copy); try { expect(finder, findsExactly(4)); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _PredicateSemanticsFinder:<Found 3 SemanticsNodes with action "SemanticsAction.copy"')); }); }); group('byAnyAction', () { testWidgets('finds nodes with any matching actions', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byAnyAction(<SemanticsAction>[ SemanticsAction.paste, SemanticsAction.longPress, ]); expect(finder, findsExactly(4)); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byAnyAction(<SemanticsAction>[ SemanticsAction.paste, SemanticsAction.longPress, ]); try { expect(finder, findsExactly(5)); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _PredicateSemanticsFinder:<Found 4 SemanticsNodes with any of the following actions: [SemanticsAction.paste, SemanticsAction.longPress]:')); }); }); group('byFlag', () { testWidgets('finds nodes with matching flag', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byFlag(SemanticsFlag.isReadOnly); expect(finder, findsExactly(3)); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byFlag(SemanticsFlag.isReadOnly); try { expect(finder, findsExactly(4)); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('_PredicateSemanticsFinder:<Found 3 SemanticsNodes with flag "SemanticsFlag.isReadOnly":')); }); }); group('byAnyFlag', () { testWidgets('finds nodes with any matching flag', (WidgetTester tester) async { await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byAnyFlag(<SemanticsFlag>[ SemanticsFlag.isHeader, SemanticsFlag.isTextField, ]); expect(finder, findsExactly(2)); }); testWidgets('fails with descriptive message', (WidgetTester tester) async { late TestFailure failure; await tester.pumpWidget(semanticsTree); final SemanticsFinder finder = find.semantics.byAnyFlag(<SemanticsFlag>[ SemanticsFlag.isHeader, SemanticsFlag.isTextField, ]); try { expect(finder, findsExactly(3)); } on TestFailure catch (e) { failure = e; } expect(failure.message, contains('Actual: _PredicateSemanticsFinder:<Found 2 SemanticsNodes with any of the following flags: [SemanticsFlag.isHeader, SemanticsFlag.isTextField]:')); }); }); group('scrollable', () { testWidgets('can find node that can scroll up', (WidgetTester tester) async { final ScrollController controller = ScrollController(); await tester.pumpWidget(MaterialApp( home: SingleChildScrollView( controller: controller, child: const SizedBox(width: 100, height: 1000), ), )); expect(find.semantics.scrollable(), containsSemantics( hasScrollUpAction: true, hasScrollDownAction: false, )); }); testWidgets('can find node that can scroll down', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 400); await tester.pumpWidget(MaterialApp( home: SingleChildScrollView( controller: controller, child: const SizedBox(width: 100, height: 1000), ), )); expect(find.semantics.scrollable(), containsSemantics( hasScrollUpAction: false, hasScrollDownAction: true, )); }); testWidgets('can find node that can scroll left', (WidgetTester tester) async { final ScrollController controller = ScrollController(); await tester.pumpWidget(MaterialApp( home: SingleChildScrollView( scrollDirection: Axis.horizontal, controller: controller, child: const SizedBox(width: 1000, height: 100), ), )); expect(find.semantics.scrollable(), containsSemantics( hasScrollLeftAction: true, hasScrollRightAction: false, )); }); testWidgets('can find node that can scroll right', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 200); await tester.pumpWidget(MaterialApp( home: SingleChildScrollView( scrollDirection: Axis.horizontal, controller: controller, child: const SizedBox(width: 1000, height: 100), ), )); expect(find.semantics.scrollable(), containsSemantics( hasScrollLeftAction: false, hasScrollRightAction: true, )); }); testWidgets('can exclusively find node that scrolls horizontally', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Column( children: <Widget>[ SingleChildScrollView( scrollDirection: Axis.horizontal, child: SizedBox(width: 1000, height: 100), ), Expanded( child: SingleChildScrollView( child: SizedBox(width: 100, height: 1000), ), ), ], ) )); expect(find.semantics.scrollable(axis: Axis.horizontal), findsOne); }); testWidgets('can exclusively find node that scrolls vertically', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Column( children: <Widget>[ SingleChildScrollView( scrollDirection: Axis.horizontal, child: SizedBox(width: 1000, height: 100), ), Expanded( child: SingleChildScrollView( child: SizedBox(width: 100, height: 1000), ), ), ], ) )); expect(find.semantics.scrollable(axis: Axis.vertical), findsOne); }); }); }); group('FinderBase', () { group('describeMatch', () { test('is used for Finder and results', () { const String expected = 'Fake finder describe match'; final _FakeFinder finder = _FakeFinder(describeMatchCallback: (_) { return expected; }); expect(finder.evaluate().toString(), contains(expected)); expect(finder.toString(describeSelf: true), contains(expected)); }); for (int i = 0; i < 4; i++) { test('gets expected plurality for $i when reporting results from find', () { final Plurality expected = switch (i) { 0 => Plurality.zero, 1 => Plurality.one, _ => Plurality.many, }; late final Plurality actual; final _FakeFinder finder = _FakeFinder( describeMatchCallback: (Plurality plurality) { actual = plurality; return 'Fake description'; }, findInCandidatesCallback: (_) => Iterable<String>.generate(i, (int index) => index.toString()), ); finder.evaluate().toString(); expect(actual, expected); }); test('gets expected plurality for $i when reporting results from toString', () { final Plurality expected = switch (i) { 0 => Plurality.zero, 1 => Plurality.one, _ => Plurality.many, }; late final Plurality actual; final _FakeFinder finder = _FakeFinder( describeMatchCallback: (Plurality plurality) { actual = plurality; return 'Fake description'; }, findInCandidatesCallback: (_) => Iterable<String>.generate(i, (int index) => index.toString()), ); finder.toString(); expect(actual, expected); }); test('always gets many when describing finder', () { const Plurality expected = Plurality.many; late final Plurality actual; final _FakeFinder finder = _FakeFinder( describeMatchCallback: (Plurality plurality) { actual = plurality; return 'Fake description'; }, findInCandidatesCallback: (_) => Iterable<String>.generate(i, (int index) => index.toString()), ); finder.toString(describeSelf: true); expect(actual, expected); }); } }); test('findInCandidates gets allCandidates', () { final List<String> expected = <String>['Test1', 'Test2', 'Test3', 'Test4']; late final List<String> actual; final _FakeFinder finder = _FakeFinder( allCandidatesCallback: () => expected, findInCandidatesCallback: (Iterable<String> candidates) { actual = candidates.toList(); return candidates; }, ); finder.evaluate(); expect(actual, expected); }); test('allCandidates calculated for each find', () { const int expectedCallCount = 3; int actualCallCount = 0; final _FakeFinder finder = _FakeFinder( allCandidatesCallback: () { actualCallCount++; return <String>['test']; }, ); for (int i = 0; i < expectedCallCount; i++) { finder.evaluate(); } expect(actualCallCount, expectedCallCount); }); test('allCandidates only called once while caching', () { int actualCallCount = 0; final _FakeFinder finder = _FakeFinder( allCandidatesCallback: () { actualCallCount++; return <String>['test']; }, ); finder.runCached(() { for (int i = 0; i < 5; i++) { finder.evaluate(); finder.tryEvaluate(); final FinderResult<String> _ = finder.found; } }); expect(actualCallCount, 1); }); group('tryFind', () { test('returns false if no results', () { final _FakeFinder finder = _FakeFinder( findInCandidatesCallback: (_) => <String>[], ); expect(finder.tryEvaluate(), false); }); test('returns true if results are available', () { final _FakeFinder finder = _FakeFinder( findInCandidatesCallback: (_) => <String>['Results'], ); expect(finder.tryEvaluate(), true); }); }); group('found', () { test('throws before any calls to evaluate or tryEvaluate', () { final _FakeFinder finder = _FakeFinder(); expect(finder.hasFound, false); expect(() => finder.found, throwsAssertionError); }); test('has same results as evaluate after call to evaluate', () { final _FakeFinder finder = _FakeFinder(); final FinderResult<String> expected = finder.evaluate(); expect(finder.hasFound, true); expect(finder.found, expected); }); test('has expected results after call to tryFind', () { final Iterable<String> expected = Iterable<String>.generate(10, (int i) => i.toString()); final _FakeFinder finder = _FakeFinder(findInCandidatesCallback: (_) => expected); finder.tryEvaluate(); expect(finder.hasFound, true); expect(finder.found, orderedEquals(expected)); }); }); }); } Widget _boilerplate(Widget child) { return Directionality( textDirection: TextDirection.ltr, child: child, ); } class SimpleCustomSemanticsWidget extends LeafRenderObjectWidget { const SimpleCustomSemanticsWidget(this.label, {super.key}); final String label; @override RenderObject createRenderObject(BuildContext context) => SimpleCustomSemanticsRenderObject(label); } class SimpleCustomSemanticsRenderObject extends RenderBox { SimpleCustomSemanticsRenderObject(this.label); final String label; @override bool get sizedByParent => true; @override Size computeDryLayout(BoxConstraints constraints) { return constraints.smallest; } @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); config ..label = label ..textDirection = TextDirection.ltr; } } class SimpleGenericWidget<T> extends StatelessWidget { const SimpleGenericWidget({required Widget child, super.key}) : _child = child; final Widget _child; @override Widget build(BuildContext context) { return _child; } } /// Wraps [child] in [depth] layers of [SizedBox] Widget _deepWidgetTree({required int depth, required Widget child}) { Widget tree = child; for (int i = 0; i < depth; i += 1) { tree = SizedBox(child: tree); } return tree; } class _FakeFinder extends FinderBase<String> { _FakeFinder({ this.allCandidatesCallback, this.describeMatchCallback, this.findInCandidatesCallback, }); final Iterable<String> Function()? allCandidatesCallback; final DescribeMatchCallback? describeMatchCallback; final Iterable<String> Function(Iterable<String> candidates)? findInCandidatesCallback; @override Iterable<String> get allCandidates { return allCandidatesCallback?.call() ?? <String>[ 'String 1', 'String 2', 'String 3', ]; } @override String describeMatch(Plurality plurality) { return describeMatchCallback?.call(plurality) ?? switch (plurality) { Plurality.one => 'String', Plurality.many || Plurality.zero => 'Strings', }; } @override Iterable<String> findInCandidates(Iterable<String> candidates) { return findInCandidatesCallback?.call(candidates) ?? candidates; } }
flutter/packages/flutter_test/test/finders_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/finders_test.dart", "repo_id": "flutter", "token_count": 20065 }
733
// 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 'dart:ui'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; TestWidgetsFlutterBinding retrieveTestBinding(WidgetTester tester) { final WidgetsBinding binding = tester.binding; assert(binding is TestWidgetsFlutterBinding); final TestWidgetsFlutterBinding testBinding = binding as TestWidgetsFlutterBinding; return testBinding; } void verifyPropertyFaked<TProperty>({ required WidgetTester tester, required TProperty realValue, required TProperty fakeValue, required TProperty Function() propertyRetriever, required void Function(TestWidgetsFlutterBinding, TProperty fakeValue) propertyFaker, Matcher Function(TProperty) matcher = equals, }) { TProperty propertyBeforeFaking; TProperty propertyAfterFaking; propertyBeforeFaking = propertyRetriever(); propertyFaker(retrieveTestBinding(tester), fakeValue); propertyAfterFaking = propertyRetriever(); expect( realValue == fakeValue, isFalse, reason: 'Since the real value and fake value are equal, we cannot validate ' 'that a property has been faked. Choose a different fake value to test.', ); expect(propertyBeforeFaking, matcher(realValue)); expect(propertyAfterFaking, matcher(fakeValue)); } void verifyPropertyReset<TProperty>({ required WidgetTester tester, required TProperty fakeValue, required TProperty Function() propertyRetriever, required VoidCallback propertyResetter, required ValueSetter<TProperty> propertyFaker, Matcher Function(TProperty) matcher = equals, }) { TProperty propertyBeforeFaking; TProperty propertyAfterFaking; TProperty propertyAfterReset; propertyBeforeFaking = propertyRetriever(); propertyFaker(fakeValue); propertyAfterFaking = propertyRetriever(); propertyResetter(); propertyAfterReset = propertyRetriever(); expect(propertyAfterFaking, matcher(fakeValue)); expect(propertyAfterReset, matcher(propertyBeforeFaking)); } Matcher matchesViewPadding(ViewPadding expected) => _FakeViewPaddingMatcher(expected); class _FakeViewPaddingMatcher extends Matcher { _FakeViewPaddingMatcher(this.expected); final ViewPadding expected; @override Description describe(Description description) { description.add('two ViewPadding instances match'); return description; } @override Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { assert(item is ViewPadding, 'Can only match against implementations of ViewPadding.'); final ViewPadding actual = item as ViewPadding; if (actual.left != expected.left) { mismatchDescription.add('actual.left (${actual.left}) did not match expected.left (${expected.left})'); } if (actual.top != expected.top) { mismatchDescription.add('actual.top (${actual.top}) did not match expected.top (${expected.top})'); } if (actual.right != expected.right) { mismatchDescription.add('actual.right (${actual.right}) did not match expected.right (${expected.right})'); } if (actual.bottom != expected.bottom) { mismatchDescription.add('actual.bottom (${actual.bottom}) did not match expected.bottom (${expected.bottom})'); } return mismatchDescription; } @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { assert(item is ViewPadding, 'Can only match against implementations of ViewPadding.'); final ViewPadding actual = item as ViewPadding; return actual.left == expected.left && actual.top == expected.top && actual.right == expected.right && actual.bottom == expected.bottom; } }
flutter/packages/flutter_test/test/utils/fake_and_mock_utils.dart/0
{ "file_path": "flutter/packages/flutter_test/test/utils/fake_and_mock_utils.dart", "repo_id": "flutter", "token_count": 1138 }
734
// 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 'dart:io'; void main(List<String> arguments) { File? scriptOutputStreamFile; final String? scriptOutputStreamFileEnv = Platform.environment['SCRIPT_OUTPUT_STREAM_FILE']; if (scriptOutputStreamFileEnv != null && scriptOutputStreamFileEnv.isNotEmpty) { scriptOutputStreamFile = File(scriptOutputStreamFileEnv); } Context( arguments: arguments, environment: Platform.environment, scriptOutputStreamFile: scriptOutputStreamFile, ).run(); } /// Container for script arguments and environment variables. /// /// All interactions with the platform are broken into individual methods that /// can be overridden in tests. class Context { Context({ required this.arguments, required this.environment, File? scriptOutputStreamFile, }) { if (scriptOutputStreamFile != null) { scriptOutputStream = scriptOutputStreamFile.openSync(mode: FileMode.write); } } final Map<String, String> environment; final List<String> arguments; RandomAccessFile? scriptOutputStream; void run() { if (arguments.isEmpty) { // Named entry points were introduced in Flutter v0.0.7. stderr.write( 'error: Your Xcode project is incompatible with this version of Flutter. ' 'Run "rm -rf ios/Runner.xcodeproj" and "flutter create ." to regenerate.\n'); exit(-1); } final String subCommand = arguments.first; switch (subCommand) { case 'build': buildApp(); case 'thin': // No-op, thinning is handled during the bundle asset assemble build target. break; case 'embed': embedFlutterFrameworks(); case 'embed_and_thin': // Thinning is handled during the bundle asset assemble build target, so just embed. embedFlutterFrameworks(); case 'test_vm_service_bonjour_service': // Exposed for integration testing only. addVmServiceBonjourService(); } } bool existsFile(String path) { final File file = File(path); return file.existsSync(); } /// Run given command in a synchronous subprocess. /// /// Will throw [Exception] if the exit code is not 0. ProcessResult runSync( String bin, List<String> args, { bool verbose = false, bool allowFail = false, String? workingDirectory, }) { if (verbose) { print('♦ $bin ${args.join(' ')}'); } final ProcessResult result = Process.runSync( bin, args, workingDirectory: workingDirectory, ); if (verbose) { print((result.stdout as String).trim()); } final String resultStderr = result.stderr.toString().trim(); if (resultStderr.isNotEmpty) { final StringBuffer errorOutput = StringBuffer(); if (result.exitCode != 0) { // "error:" prefix makes this show up as an Xcode compilation error. errorOutput.write('error: '); } errorOutput.write(resultStderr); echoError(errorOutput.toString()); } if (!allowFail && result.exitCode != 0) { throw Exception( 'Command "$bin ${args.join(' ')}" exited with code ${result.exitCode}', ); } return result; } /// Log message to stderr. void echoError(String message) { stderr.writeln(message); } /// Log message to stdout. void echo(String message) { stdout.write(message); } /// Exit the application with the given exit code. /// /// Exists to allow overriding in tests. Never exitApp(int code) { exit(code); } /// Return value from environment if it exists, else throw [Exception]. String environmentEnsure(String key) { final String? value = environment[key]; if (value == null) { throw Exception( 'Expected the environment variable "$key" to exist, but it was not found', ); } return value; } // When provided with a pipe by the host Flutter build process, output to the // pipe goes to stdout of the Flutter build process directly. void streamOutput(String output) { scriptOutputStream?.writeStringSync('$output\n'); } String parseFlutterBuildMode() { // Use FLUTTER_BUILD_MODE if it's set, otherwise use the Xcode build configuration name // This means that if someone wants to use an Xcode build config other than Debug/Profile/Release, // they _must_ set FLUTTER_BUILD_MODE so we know what type of artifact to build. final String? buildMode = (environment['FLUTTER_BUILD_MODE'] ?? environment['CONFIGURATION'])?.toLowerCase(); if (buildMode != null) { if (buildMode.contains('release')) { return 'release'; } if (buildMode.contains('profile')) { return 'profile'; } if (buildMode.contains('debug')) { return 'debug'; } } echoError('========================================================================'); echoError('ERROR: Unknown FLUTTER_BUILD_MODE: $buildMode.'); echoError("Valid values are 'Debug', 'Profile', or 'Release' (case insensitive)."); echoError('This is controlled by the FLUTTER_BUILD_MODE environment variable.'); echoError('If that is not set, the CONFIGURATION environment variable is used.'); echoError(''); echoError('You can fix this by either adding an appropriately named build'); echoError('configuration, or adding an appropriate value for FLUTTER_BUILD_MODE to the'); echoError('.xcconfig file for the current build configuration (${environment['CONFIGURATION']}).'); echoError('========================================================================'); exitApp(-1); } /// Copies all files from [source] to [destination]. /// /// Does not copy `.DS_Store`. /// /// If [delete], delete extraneous files from [destination]. void runRsync( String source, String destination, { List<String> extraArgs = const <String>[], bool delete = false, }) { runSync( 'rsync', <String>[ '-8', // Avoid mangling filenames with encodings that do not match the current locale. '-av', if (delete) '--delete', '--filter', '- .DS_Store', ...extraArgs, source, destination, ], ); } // Adds the App.framework as an embedded binary and the flutter_assets as // resources. void embedFlutterFrameworks() { // Embed App.framework from Flutter into the app (after creating the Frameworks directory // if it doesn't already exist). final String xcodeFrameworksDir = '${environment['TARGET_BUILD_DIR']}/${environment['FRAMEWORKS_FOLDER_PATH']}'; runSync( 'mkdir', <String>[ '-p', '--', xcodeFrameworksDir, ] ); runRsync( delete: true, '${environment['BUILT_PRODUCTS_DIR']}/App.framework', xcodeFrameworksDir, ); // Embed the actual Flutter.framework that the Flutter app expects to run against, // which could be a local build or an arch/type specific build. runRsync( delete: true, '${environment['BUILT_PRODUCTS_DIR']}/Flutter.framework', '$xcodeFrameworksDir/', ); // Copy the native assets. These do not have to be codesigned here because, // they are already codesigned in buildNativeAssetsMacOS. final String sourceRoot = environment['SOURCE_ROOT'] ?? ''; String projectPath = '$sourceRoot/..'; if (environment['FLUTTER_APPLICATION_PATH'] != null) { projectPath = environment['FLUTTER_APPLICATION_PATH']!; } final String flutterBuildDir = environment['FLUTTER_BUILD_DIR']!; final String nativeAssetsPath = '$projectPath/$flutterBuildDir/native_assets/ios/'; final bool verbose = (environment['VERBOSE_SCRIPT_LOGGING'] ?? '').isNotEmpty; if (Directory(nativeAssetsPath).existsSync()) { if (verbose) { print('♦ Copying native assets from $nativeAssetsPath.'); } runRsync( extraArgs: <String>[ '--filter', '- native_assets.yaml', ], nativeAssetsPath, xcodeFrameworksDir, ); } else if (verbose) { print("♦ No native assets to bundle. $nativeAssetsPath doesn't exist."); } addVmServiceBonjourService(); } // Add the vmService publisher Bonjour service to the produced app bundle Info.plist. void addVmServiceBonjourService() { // Skip adding Bonjour service settings when DISABLE_PORT_PUBLICATION is YES. // These settings are not needed if port publication is disabled. if (environment['DISABLE_PORT_PUBLICATION'] == 'YES') { return; } final String buildMode = parseFlutterBuildMode(); // Debug and profile only. if (buildMode == 'release') { return; } final String builtProductsPlist = '${environment['BUILT_PRODUCTS_DIR'] ?? ''}/${environment['INFOPLIST_PATH'] ?? ''}'; if (!existsFile(builtProductsPlist)) { // Very occasionally Xcode hasn't created an Info.plist when this runs. // The file will be present on re-run. echo( '${environment['INFOPLIST_PATH'] ?? ''} does not exist. Skipping ' '_dartVmService._tcp NSBonjourServices insertion. Try re-building to ' 'enable "flutter attach".'); return; } // If there are already NSBonjourServices specified by the app (uncommon), // insert the vmService service name to the existing list. ProcessResult result = runSync( 'plutil', <String>[ '-extract', 'NSBonjourServices', 'xml1', '-o', '-', builtProductsPlist, ], allowFail: true, ); if (result.exitCode == 0) { runSync( 'plutil', <String>[ '-insert', 'NSBonjourServices.0', '-string', '_dartVmService._tcp', builtProductsPlist, ], ); } else { // Otherwise, add the NSBonjourServices key and vmService service name. runSync( 'plutil', <String>[ '-insert', 'NSBonjourServices', '-json', '["_dartVmService._tcp"]', builtProductsPlist, ], ); //fi } // Don't override the local network description the Flutter app developer // specified (uncommon). This text will appear below the "Your app would // like to find and connect to devices on your local network" permissions // popup. result = runSync( 'plutil', <String>[ '-extract', 'NSLocalNetworkUsageDescription', 'xml1', '-o', '-', builtProductsPlist, ], allowFail: true, ); if (result.exitCode != 0) { runSync( 'plutil', <String>[ '-insert', 'NSLocalNetworkUsageDescription', '-string', 'Allow Flutter tools on your computer to connect and debug your application. This prompt will not appear on release builds.', builtProductsPlist, ], ); } } void buildApp() { final bool verbose = environment['VERBOSE_SCRIPT_LOGGING'] != null && environment['VERBOSE_SCRIPT_LOGGING'] != ''; final String sourceRoot = environment['SOURCE_ROOT'] ?? ''; String projectPath = '$sourceRoot/..'; if (environment['FLUTTER_APPLICATION_PATH'] != null) { projectPath = environment['FLUTTER_APPLICATION_PATH']!; } String targetPath = 'lib/main.dart'; if (environment['FLUTTER_TARGET'] != null) { targetPath = environment['FLUTTER_TARGET']!; } final String buildMode = parseFlutterBuildMode(); // Warn the user if not archiving (ACTION=install) in release mode. final String? action = environment['ACTION']; if (action == 'install' && buildMode != 'release') { echo( 'warning: Flutter archive not built in Release mode. Ensure ' 'FLUTTER_BUILD_MODE is set to release or run "flutter build ios ' '--release", then re-run Archive from Xcode.', ); } final List<String> flutterArgs = <String>[]; if (verbose) { flutterArgs.add('--verbose'); } if (environment['FLUTTER_ENGINE'] != null && environment['FLUTTER_ENGINE']!.isNotEmpty) { flutterArgs.add('--local-engine-src-path=${environment['FLUTTER_ENGINE']}'); } if (environment['LOCAL_ENGINE'] != null && environment['LOCAL_ENGINE']!.isNotEmpty) { flutterArgs.add('--local-engine=${environment['LOCAL_ENGINE']}'); } if (environment['LOCAL_ENGINE_HOST'] != null && environment['LOCAL_ENGINE_HOST']!.isNotEmpty) { flutterArgs.add('--local-engine-host=${environment['LOCAL_ENGINE_HOST']}'); } flutterArgs.addAll(<String>[ 'assemble', '--no-version-check', '--output=${environment['BUILT_PRODUCTS_DIR'] ?? ''}/', '-dTargetPlatform=ios', '-dTargetFile=$targetPath', '-dBuildMode=$buildMode', if (environment['FLAVOR'] != null) '-dFlavor=${environment['FLAVOR']}', '-dIosArchs=${environment['ARCHS'] ?? ''}', '-dSdkRoot=${environment['SDKROOT'] ?? ''}', '-dSplitDebugInfo=${environment['SPLIT_DEBUG_INFO'] ?? ''}', '-dTreeShakeIcons=${environment['TREE_SHAKE_ICONS'] ?? ''}', '-dTrackWidgetCreation=${environment['TRACK_WIDGET_CREATION'] ?? ''}', '-dDartObfuscation=${environment['DART_OBFUSCATION'] ?? ''}', '-dAction=${environment['ACTION'] ?? ''}', '-dFrontendServerStarterPath=${environment['FRONTEND_SERVER_STARTER_PATH'] ?? ''}', '--ExtraGenSnapshotOptions=${environment['EXTRA_GEN_SNAPSHOT_OPTIONS'] ?? ''}', '--DartDefines=${environment['DART_DEFINES'] ?? ''}', '--ExtraFrontEndOptions=${environment['EXTRA_FRONT_END_OPTIONS'] ?? ''}', ]); if (environment['PERFORMANCE_MEASUREMENT_FILE'] != null && environment['PERFORMANCE_MEASUREMENT_FILE']!.isNotEmpty) { flutterArgs.add('--performance-measurement-file=${environment['PERFORMANCE_MEASUREMENT_FILE']}'); } final String? expandedCodeSignIdentity = environment['EXPANDED_CODE_SIGN_IDENTITY']; if (expandedCodeSignIdentity != null && expandedCodeSignIdentity.isNotEmpty && environment['CODE_SIGNING_REQUIRED'] != 'NO') { flutterArgs.add('-dCodesignIdentity=$expandedCodeSignIdentity'); } if (environment['BUNDLE_SKSL_PATH'] != null && environment['BUNDLE_SKSL_PATH']!.isNotEmpty) { flutterArgs.add('-dBundleSkSLPath=${environment['BUNDLE_SKSL_PATH']}'); } if (environment['CODE_SIZE_DIRECTORY'] != null && environment['CODE_SIZE_DIRECTORY']!.isNotEmpty) { flutterArgs.add('-dCodeSizeDirectory=${environment['CODE_SIZE_DIRECTORY']}'); } flutterArgs.add('${buildMode}_ios_bundle_flutter_assets'); final ProcessResult result = runSync( '${environmentEnsure('FLUTTER_ROOT')}/bin/flutter', flutterArgs, verbose: verbose, allowFail: true, workingDirectory: projectPath, // equivalent of RunCommand pushd "${project_path}" ); if (result.exitCode != 0) { echoError('Failed to package $projectPath.'); exitApp(-1); } streamOutput('done'); streamOutput(' └─Compiling, linking and signing...'); echo('Project $projectPath built and packaged successfully.'); } }
flutter/packages/flutter_tools/bin/xcode_backend.dart/0
{ "file_path": "flutter/packages/flutter_tools/bin/xcode_backend.dart", "repo_id": "flutter", "token_count": 5804 }
735
include ':app' def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() def plugins = new Properties() def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') if (pluginsFile.exists()) { pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } } plugins.each { name, path -> def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() include ":$name" project(":$name").projectDir = pluginDirectory } ;EOF include ':app' def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() def plugins = new Properties() def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') if (pluginsFile.exists()) { pluginsFile.withInputStream { stream -> plugins.load(stream) } } plugins.each { name, path -> def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() include ":$name" project(":$name").projectDir = pluginDirectory } ;EOF // 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. include ':app' def localPropertiesFile = new File(rootProject.projectDir, "local.properties") def properties = new Properties() assert localPropertiesFile.exists() localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" ;EOF include ':app' def localPropertiesFile = new File(rootProject.projectDir, "local.properties") def properties = new Properties() assert localPropertiesFile.exists() localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
flutter/packages/flutter_tools/gradle/settings.gradle.legacy_versions/0
{ "file_path": "flutter/packages/flutter_tools/gradle/settings.gradle.legacy_versions", "repo_id": "flutter", "token_count": 644 }
736
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="catalog - tabbed_app_bar" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/catalog/lib/tabbed_app_bar.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___tabbed_app_bar.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___tabbed_app_bar.xml.copy.tmpl", "repo_id": "flutter", "token_count": 100 }
737
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="manual_tests - density" type="FlutterRunConfigurationType" factoryName="Flutter" singleton="false"> <option name="filePath" value="$PROJECT_DIR$/dev/manual_tests/lib/density.dart" /> <method v="2" /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___density.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___density.xml.copy.tmpl", "repo_id": "flutter", "token_count": 102 }
738
// 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 'dart:async'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../convert.dart'; import '../device.dart'; import '../emulator.dart'; import 'android_sdk.dart'; import 'android_workflow.dart'; class AndroidEmulators extends EmulatorDiscovery { AndroidEmulators({ AndroidSdk? androidSdk, required AndroidWorkflow androidWorkflow, required FileSystem fileSystem, required Logger logger, required ProcessManager processManager, }) : _androidSdk = androidSdk, _androidWorkflow = androidWorkflow, _fileSystem = fileSystem, _logger = logger, _processManager = processManager, _processUtils = ProcessUtils(logger: logger, processManager: processManager); final AndroidWorkflow _androidWorkflow; final AndroidSdk? _androidSdk; final FileSystem _fileSystem; final Logger _logger; final ProcessManager _processManager; final ProcessUtils _processUtils; @override bool get supportsPlatform => true; @override bool get canListAnything => _androidWorkflow.canListEmulators; @override bool get canLaunchAnything => _androidWorkflow.canListEmulators && _androidSdk?.getAvdManagerPath() != null; @override Future<List<Emulator>> get emulators => _getEmulatorAvds(); /// Return the list of available emulator AVDs. Future<List<AndroidEmulator>> _getEmulatorAvds() async { final String? emulatorPath = _androidSdk?.emulatorPath; if (emulatorPath == null) { return <AndroidEmulator>[]; } final String listAvdsOutput = (await _processUtils.run( <String>[emulatorPath, '-list-avds'])).stdout.trim(); final List<AndroidEmulator> emulators = <AndroidEmulator>[]; _extractEmulatorAvdInfo(listAvdsOutput, emulators); return emulators; } /// Parse the given `emulator -list-avds` output in [text], and fill out the given list /// of emulators by reading information from the relevant ini files. void _extractEmulatorAvdInfo(String text, List<AndroidEmulator> emulators) { for (final String id in text.trim().split('\n').where((String l) => l != '')) { emulators.add(_loadEmulatorInfo(id)); } } AndroidEmulator _loadEmulatorInfo(String id) { id = id.trim(); final String? avdPath = _androidSdk?.getAvdPath(); final AndroidEmulator androidEmulatorWithoutProperties = AndroidEmulator( id, processManager: _processManager, logger: _logger, androidSdk: _androidSdk, ); if (avdPath == null) { return androidEmulatorWithoutProperties; } final File iniFile = _fileSystem.file(_fileSystem.path.join(avdPath, '$id.ini')); if (!iniFile.existsSync()) { return androidEmulatorWithoutProperties; } final Map<String, String> ini = parseIniLines(iniFile.readAsLinesSync()); final String? path = ini['path']; if (path == null) { return androidEmulatorWithoutProperties; } final File configFile = _fileSystem.file(_fileSystem.path.join(path, 'config.ini')); if (!configFile.existsSync()) { return androidEmulatorWithoutProperties; } final Map<String, String> properties = parseIniLines(configFile.readAsLinesSync()); return AndroidEmulator( id, properties: properties, processManager: _processManager, logger: _logger, androidSdk: _androidSdk, ); } } class AndroidEmulator extends Emulator { AndroidEmulator(String id, { Map<String, String>? properties, required Logger logger, AndroidSdk? androidSdk, required ProcessManager processManager, }) : _properties = properties, _logger = logger, _androidSdk = androidSdk, _processUtils = ProcessUtils(logger: logger, processManager: processManager), super(id, properties != null && properties.isNotEmpty); final Map<String, String>? _properties; final Logger _logger; final ProcessUtils _processUtils; final AndroidSdk? _androidSdk; // Android Studio uses the ID with underscores replaced with spaces // for the name if displayname is not set so we do the same. @override String get name => _prop('avd.ini.displayname') ?? id.replaceAll('_', ' ').trim(); @override String? get manufacturer => _prop('hw.device.manufacturer'); @override Category get category => Category.mobile; @override PlatformType get platformType => PlatformType.android; String? _prop(String name) => _properties != null ? _properties[name] : null; @override Future<void> launch({@visibleForTesting Duration? startupDuration, bool coldBoot = false}) async { final String? emulatorPath = _androidSdk?.emulatorPath; if (emulatorPath == null) { throw Exception('Emulator is missing from the Android SDK'); } final List<String> command = <String>[ emulatorPath, '-avd', id, if (coldBoot) '-no-snapshot-load', ]; final Process process = await _processUtils.start(command); // Record output from the emulator process. final List<String> stdoutList = <String>[]; final List<String> stderrList = <String>[]; final StreamSubscription<String> stdoutSubscription = process.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen(stdoutList.add); final StreamSubscription<String> stderrSubscription = process.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen(stderrList.add); final Future<void> stdioFuture = Future.wait<void>(<Future<void>>[ stdoutSubscription.asFuture<void>(), stderrSubscription.asFuture<void>(), ]); // The emulator continues running on success, so we don't wait for the // process to complete before continuing. However, if the process fails // after the startup phase (3 seconds), then we only echo its output if // its error code is non-zero and its stderr is non-empty. bool earlyFailure = true; unawaited(process.exitCode.then((int status) async { if (status == 0) { _logger.printTrace('The Android emulator exited successfully'); return; } // Make sure the process' stdout and stderr are drained. await stdioFuture; unawaited(stdoutSubscription.cancel()); unawaited(stderrSubscription.cancel()); if (stdoutList.isNotEmpty) { _logger.printTrace('Android emulator stdout:'); stdoutList.forEach(_logger.printTrace); } if (!earlyFailure && stderrList.isEmpty) { _logger.printStatus('The Android emulator exited with code $status'); return; } final String when = earlyFailure ? 'during startup' : 'after startup'; _logger.printError('The Android emulator exited with code $status $when'); _logger.printError('Android emulator stderr:'); stderrList.forEach(_logger.printError); _logger.printError('Address these issues and try again.'); })); // Wait a few seconds for the emulator to start. await Future<void>.delayed(startupDuration ?? const Duration(seconds: 3)); earlyFailure = false; return; } } @visibleForTesting Map<String, String> parseIniLines(List<String> contents) { final Map<String, String> results = <String, String>{}; final Iterable<List<String>> properties = contents .map<String>((String l) => l.trim()) // Strip blank lines/comments .where((String l) => l != '' && !l.startsWith('#')) // Discard anything that isn't simple name=value .where((String l) => l.contains('=')) // Split into name/value .map<List<String>>((String l) => l.split('=')); for (final List<String> property in properties) { results[property[0].trim()] = property[1].trim(); } return results; }
flutter/packages/flutter_tools/lib/src/android/android_emulator.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/android_emulator.dart", "repo_id": "flutter", "token_count": 2815 }
739
// 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 '../../base/file_system.dart'; import '../../base/project_migrator.dart'; import '../../project.dart'; const String _eagerCleanTaskDeclaration = ''' task clean(type: Delete) { delete rootProject.buildDir } '''; const String _lazyCleanTaskDeclaration = ''' tasks.register("clean", Delete) { delete rootProject.buildDir } '''; /// Migrate the Gradle "clean" task to use modern, lazy declaration style. class TopLevelGradleBuildFileMigration extends ProjectMigrator { TopLevelGradleBuildFileMigration( AndroidProject project, super.logger, ) : _topLevelGradleBuildFile = project.hostAppGradleRoot.childFile('build.gradle'); final File _topLevelGradleBuildFile; @override void migrate() { if (!_topLevelGradleBuildFile.existsSync()) { logger.printTrace('Top-level Gradle build file not found, skipping migration of task "clean".'); return; } processFileLines(_topLevelGradleBuildFile); } @override String migrateFileContents(String fileContents) { final String newContents = fileContents.replaceAll( _eagerCleanTaskDeclaration, _lazyCleanTaskDeclaration, ); if (newContents != fileContents) { logger.printTrace('Migrating "clean" Gradle task to lazy declaration style.'); } return newContents; } }
flutter/packages/flutter_tools/lib/src/android/migrations/top_level_gradle_build_file_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/migrations/top_level_gradle_build_file_migration.dart", "repo_id": "flutter", "token_count": 479 }
740
// 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:crypto/crypto.dart' show md5; import 'package:meta/meta.dart'; import '../convert.dart' show json; import 'file_system.dart'; import 'logger.dart'; import 'utils.dart'; /// A tool that can be used to compute, compare, and write [Fingerprint]s for a /// set of input files and associated build settings. /// /// This class should only be used in situations where `assemble` is not appropriate, /// such as checking if Cocoapods should be run. class Fingerprinter { Fingerprinter({ required this.fingerprintPath, required Iterable<String> paths, required FileSystem fileSystem, required Logger logger, }) : _paths = paths.toList(), _logger = logger, _fileSystem = fileSystem; final String fingerprintPath; final List<String> _paths; final Logger _logger; final FileSystem _fileSystem; Fingerprint buildFingerprint() { final List<String> paths = _getPaths(); return Fingerprint.fromBuildInputs(paths, _fileSystem); } bool doesFingerprintMatch() { try { final File fingerprintFile = _fileSystem.file(fingerprintPath); if (!fingerprintFile.existsSync()) { return false; } final List<String> paths = _getPaths(); if (!paths.every(_fileSystem.isFileSync)) { return false; } final Fingerprint oldFingerprint = Fingerprint.fromJson(fingerprintFile.readAsStringSync()); final Fingerprint newFingerprint = buildFingerprint(); return oldFingerprint == newFingerprint; } on Exception catch (e) { // Log exception and continue, fingerprinting is only a performance improvement. _logger.printTrace('Fingerprint check error: $e'); } return false; } void writeFingerprint() { try { final Fingerprint fingerprint = buildFingerprint(); final File fingerprintFile = _fileSystem.file(fingerprintPath); fingerprintFile.createSync(recursive: true); fingerprintFile.writeAsStringSync(fingerprint.toJson()); } on Exception catch (e) { // Log exception and continue, fingerprinting is only a performance improvement. _logger.printTrace('Fingerprint write error: $e'); } } List<String> _getPaths() => _paths; } /// A fingerprint that uniquely identifies a set of build input files and /// properties. /// /// See [Fingerprinter]. @immutable class Fingerprint { const Fingerprint._({ Map<String, String>? checksums, }) : _checksums = checksums ?? const <String, String>{}; factory Fingerprint.fromBuildInputs(Iterable<String> inputPaths, FileSystem fileSystem) { final Iterable<File> files = inputPaths.map<File>(fileSystem.file); final Iterable<File> missingInputs = files.where((File file) => !file.existsSync()); if (missingInputs.isNotEmpty) { throw Exception('Missing input files:\n${missingInputs.join('\n')}'); } return Fingerprint._( checksums: <String, String>{ for (final File file in files) file.path: md5.convert(file.readAsBytesSync()).toString(), }, ); } /// Creates a Fingerprint from serialized JSON. /// /// Throws [Exception], if there is a version mismatch between the /// serializing framework and this framework. factory Fingerprint.fromJson(String jsonData) { final Map<String, dynamic>? content = castStringKeyedMap(json.decode(jsonData)); final Map<String, String>? files = content == null ? null : castStringKeyedMap(content['files'])?.cast<String, String>(); return Fingerprint._( checksums: files ?? <String, String>{}, ); } final Map<String, String> _checksums; String toJson() => json.encode(<String, dynamic>{ 'files': _checksums, }); @override bool operator==(Object other) { return other is Fingerprint && _equalMaps(other._checksums, _checksums); } bool _equalMaps(Map<String, String> a, Map<String, String> b) { return a.length == b.length && a.keys.every((String key) => a[key] == b[key]); } @override int get hashCode => Object.hash(Object.hashAllUnordered(_checksums.keys), Object.hashAllUnordered(_checksums.values)); @override String toString() => '{checksums: $_checksums}'; }
flutter/packages/flutter_tools/lib/src/base/fingerprint.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/fingerprint.dart", "repo_id": "flutter", "token_count": 1491 }
741
// 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:meta/meta.dart'; /// Represents the version of some piece of software. /// /// While a [Version] object has fields resembling semver, it does not /// necessarily represent a semver version. @immutable class Version implements Comparable<Version> { /// Creates a new [Version] object. /// /// A null [minor] or [patch] version is logically equivalent to 0. Using null /// for these parameters only affects the generation of [text], if no value /// for it is provided. factory Version(int major, int? minor, int? patch, {String? text}) { if (text == null) { text = '$major'; if (minor != null) { text = '$text.$minor'; } if (patch != null) { text = '$text.$patch'; } } return Version._(major, minor ?? 0, patch ?? 0, text); } /// Public constant constructor when all fields are non-null, without default value fallbacks. const Version.withText(this.major, this.minor, this.patch, this._text); Version._(this.major, this.minor, this.patch, this._text) { if (major < 0) { throw ArgumentError('Major version must be non-negative.'); } if (minor < 0) { throw ArgumentError('Minor version must be non-negative.'); } if (patch < 0) { throw ArgumentError('Patch version must be non-negative.'); } } /// Creates a new [Version] by parsing [text]. static Version? parse(String? text) { final Match? match = versionPattern.firstMatch(text ?? ''); if (match == null) { return null; } try { final int major = int.parse(match[1] ?? '0'); final int minor = int.parse(match[3] ?? '0'); final int patch = int.parse(match[5] ?? '0'); return Version._(major, minor, patch, text ?? ''); } on FormatException { return null; } } /// Returns the primary version out of a list of candidates. /// /// This is the highest-numbered stable version. static Version? primary(List<Version> versions) { Version? primary; for (final Version version in versions) { if (primary == null || (version > primary)) { primary = version; } } return primary; } /// The major version number: "1" in "1.2.3". final int major; /// The minor version number: "2" in "1.2.3". final int minor; /// The patch version number: "3" in "1.2.3". final int patch; /// The original string representation of the version number. /// /// This preserves textual artifacts like leading zeros that may be left out /// of the parsed version. final String _text; static final RegExp versionPattern = RegExp(r'^(\d+)(\.(\d+)(\.(\d+))?)?'); /// Two [Version]s are equal if their version numbers are. The version text /// is ignored. @override bool operator ==(Object other) { return other is Version && other.major == major && other.minor == minor && other.patch == patch; } @override int get hashCode => Object.hash(major, minor, patch); bool operator <(Version other) => compareTo(other) < 0; bool operator >(Version other) => compareTo(other) > 0; bool operator <=(Version other) => compareTo(other) <= 0; bool operator >=(Version other) => compareTo(other) >= 0; @override int compareTo(Version other) { if (major != other.major) { return major.compareTo(other.major); } if (minor != other.minor) { return minor.compareTo(other.minor); } return patch.compareTo(other.patch); } @override String toString() => _text; } /// Returns true if [targetVersion] is within the range [min] and [max] /// inclusive by default. /// /// [min] and [max] are evaluated by [Version.parse(text)]. /// /// Pass [inclusiveMin] = false for greater than and not equal to min. /// Pass [inclusiveMax] = false for less than and not equal to max. bool isWithinVersionRange( String targetVersion, { required String min, required String max, bool inclusiveMax = true, bool inclusiveMin = true, }) { final Version? parsedTargetVersion = Version.parse(targetVersion); final Version? minVersion = Version.parse(min); final Version? maxVersion = Version.parse(max); final bool withinMin = minVersion != null && parsedTargetVersion != null && (inclusiveMin ? parsedTargetVersion >= minVersion : parsedTargetVersion > minVersion); final bool withinMax = maxVersion != null && parsedTargetVersion != null && (inclusiveMax ? parsedTargetVersion <= maxVersion : parsedTargetVersion < maxVersion); return withinMin && withinMax; }
flutter/packages/flutter_tools/lib/src/base/version.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/version.dart", "repo_id": "flutter", "token_count": 1591 }
742
// 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:meta/meta.dart'; import 'package:mime/mime.dart' as mime; import 'package:process/process.dart'; import '../../artifacts.dart'; import '../../base/common.dart'; import '../../base/file_system.dart'; import '../../base/io.dart'; import '../../base/logger.dart'; import '../../build_info.dart'; import '../../convert.dart'; import '../../devfs.dart'; import '../build_system.dart'; List<Map<String, Object?>> _getList(Object? object, String errorMessage) { if (object is List<Object?>) { return object.cast<Map<String, Object?>>(); } throw IconTreeShakerException._(errorMessage); } /// A class that wraps the functionality of the const finder package and the /// font subset utility to tree shake unused icons from fonts. class IconTreeShaker { /// Creates a wrapper for icon font subsetting. /// /// If the `fontManifest` parameter is null, [enabled] will return false since /// there are no fonts to shake. /// /// The constructor will validate the environment and print a warning if /// font subsetting has been requested in a debug build mode. IconTreeShaker( this._environment, DevFSStringContent? fontManifest, { required ProcessManager processManager, required Logger logger, required FileSystem fileSystem, required Artifacts artifacts, required TargetPlatform targetPlatform, }) : _processManager = processManager, _logger = logger, _fs = fileSystem, _artifacts = artifacts, _fontManifest = fontManifest?.string, _targetPlatform = targetPlatform { if (_environment.defines[kIconTreeShakerFlag] == 'true' && _environment.defines[kBuildMode] == 'debug') { logger.printError('Font subsetting is not supported in debug mode. The ' '--tree-shake-icons flag will be ignored.'); } } /// The MIME types for supported font sets. static const Set<String> kTtfMimeTypes = <String>{ 'font/ttf', // based on internet search 'font/opentype', 'font/otf', 'application/x-font-opentype', 'application/x-font-otf', 'application/x-font-ttf', // based on running locally. }; /// The [Source] inputs that targets using this should depend on. /// /// See [Target.inputs]. static const List<Source> inputs = <Source>[ Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/icon_tree_shaker.dart'), Source.artifact(Artifact.constFinder), Source.artifact(Artifact.fontSubset), ]; final Environment _environment; final String? _fontManifest; Future<void>? _iconDataProcessing; Map<String, _IconTreeShakerData>? _iconData; final ProcessManager _processManager; final Logger _logger; final FileSystem _fs; final Artifacts _artifacts; final TargetPlatform _targetPlatform; /// Whether font subsetting should be used for this [Environment]. bool get enabled => _fontManifest != null && _environment.defines[kIconTreeShakerFlag] == 'true' && _environment.defines[kBuildMode] != 'debug'; // Fills the [_iconData] map. Future<void> _getIconData(Environment environment) async { if (!enabled) { return; } final File appDill = environment.buildDir.childFile('app.dill'); if (!appDill.existsSync()) { throw IconTreeShakerException._('Expected to find kernel file at ${appDill.path}, but no file found.'); } final File constFinder = _fs.file( _artifacts.getArtifactPath(Artifact.constFinder), ); final File dart = _fs.file( _artifacts.getArtifactPath(Artifact.engineDartBinary), ); final Map<String, List<int>> iconData = await _findConstants( dart, constFinder, appDill, ); final Set<String> familyKeys = iconData.keys.toSet(); final Map<String, String> fonts = await _parseFontJson( _fontManifest!, // Guarded by `enabled`. familyKeys, ); if (fonts.length != iconData.length) { environment.logger.printStatus( 'Expected to find fonts for ${iconData.keys}, but found ' '${fonts.keys}. This usually means you are referring to ' 'font families in an IconData class but not including them ' 'in the assets section of your pubspec.yaml, are missing ' 'the package that would include them, or are missing ' '"uses-material-design: true".', ); } final Map<String, _IconTreeShakerData> result = <String, _IconTreeShakerData>{}; const int kSpacePoint = 32; for (final MapEntry<String, String> entry in fonts.entries) { final List<int>? codePoints = iconData[entry.key]; if (codePoints == null) { throw IconTreeShakerException._('Expected to font code points for ${entry.key}, but none were found.'); } // Add space as an optional code point, as web uses it to measure the font height. final List<int> optionalCodePoints = _targetPlatform == TargetPlatform.web_javascript ? <int>[kSpacePoint] : <int>[]; result[entry.value] = _IconTreeShakerData( family: entry.key, relativePath: entry.value, codePoints: codePoints, optionalCodePoints: optionalCodePoints, ); } _iconData = result; } /// Calls font-subset, which transforms the [input] font file to a /// subsetted version at [outputPath]. /// /// If [enabled] is false, or the relative path is not recognized as an icon /// font used in the Flutter application, this returns false. /// If the font-subset subprocess fails, it will [throwToolExit]. /// Otherwise, it will return true. Future<bool> subsetFont({ required File input, required String outputPath, required String relativePath, }) async { if (!enabled) { return false; } if (input.lengthSync() < 12) { return false; } final String? mimeType = mime.lookupMimeType( input.path, headerBytes: await input.openRead(0, 12).first, ); if (!kTtfMimeTypes.contains(mimeType)) { return false; } await (_iconDataProcessing ??= _getIconData(_environment)); assert(_iconData != null); final _IconTreeShakerData? iconTreeShakerData = _iconData![relativePath]; if (iconTreeShakerData == null) { return false; } final File fontSubset = _fs.file( _artifacts.getArtifactPath(Artifact.fontSubset), ); if (!fontSubset.existsSync()) { throw IconTreeShakerException._('The font-subset utility is missing. Run "flutter doctor".'); } final List<String> cmd = <String>[ fontSubset.path, outputPath, input.path, ]; final Iterable<String> requiredCodePointStrings = iconTreeShakerData.codePoints .map((int codePoint) => codePoint.toString()); final Iterable<String> optionalCodePointStrings = iconTreeShakerData.optionalCodePoints .map((int codePoint) => 'optional:$codePoint'); final String codePointsString = requiredCodePointStrings .followedBy(optionalCodePointStrings).join(' '); _logger.printTrace('Running font-subset: ${cmd.join(' ')}, ' 'using codepoints $codePointsString'); final Process fontSubsetProcess = await _processManager.start(cmd); try { fontSubsetProcess.stdin.writeln(codePointsString); await fontSubsetProcess.stdin.flush(); await fontSubsetProcess.stdin.close(); } on Exception { // handled by checking the exit code. } final int code = await fontSubsetProcess.exitCode; if (code != 0) { _logger.printTrace(await utf8.decodeStream(fontSubsetProcess.stdout)); _logger.printError(await utf8.decodeStream(fontSubsetProcess.stderr)); throw IconTreeShakerException._('Font subsetting failed with exit code $code.'); } _logger.printStatus(getSubsetSummaryMessage(input, _fs.file(outputPath))); return true; } @visibleForTesting String getSubsetSummaryMessage(File inputFont, File outputFont) { final String fontName = inputFont.basename; final double inputSize = inputFont.lengthSync().toDouble(); final double outputSize = outputFont.lengthSync().toDouble(); final double reductionBytes = inputSize - outputSize; final String reductionPercentage = (reductionBytes / inputSize * 100).toStringAsFixed(1); return 'Font asset "$fontName" was tree-shaken, reducing it from ' '${inputSize.ceil()} to ${outputSize.ceil()} bytes ' '($reductionPercentage% reduction). Tree-shaking can be disabled ' 'by providing the --no-tree-shake-icons flag when building your app.'; } /// Returns a map of { fontFamily: relativePath } pairs. Future<Map<String, String>> _parseFontJson( String fontManifestData, Set<String> families, ) async { final Map<String, String> result = <String, String>{}; final List<Map<String, Object?>> fontList = _getList( json.decode(fontManifestData), 'FontManifest.json invalid: expected top level to be a list of objects.', ); for (final Map<String, Object?> map in fontList) { final Object? familyKey = map['family']; if (familyKey is! String) { throw IconTreeShakerException._( 'FontManifest.json invalid: expected the family value to be a string, ' 'got: ${map['family']}.'); } if (!families.contains(familyKey)) { continue; } final List<Map<String, Object?>> fonts = _getList( map['fonts'], 'FontManifest.json invalid: expected "fonts" to be a list of objects.', ); if (fonts.length != 1) { throw IconTreeShakerException._( 'This tool cannot process icon fonts with multiple fonts in a ' 'single family.'); } final Object? asset = fonts.first['asset']; if (asset is! String) { throw IconTreeShakerException._( 'FontManifest.json invalid: expected "asset" value to be a string, ' 'got: ${map['assets']}.'); } result[familyKey] = asset; } return result; } Future<Map<String, List<int>>> _findConstants( File dart, File constFinder, File appDill, ) async { final List<String> cmd = <String>[ dart.path, '--disable-dart-dev', constFinder.path, '--kernel-file', appDill.path, '--class-library-uri', 'package:flutter/src/widgets/icon_data.dart', '--class-name', 'IconData', '--annotation-class-name', '_StaticIconProvider', '--annotation-class-library-uri', 'package:flutter/src/widgets/icon_data.dart', ]; _logger.printTrace('Running command: ${cmd.join(' ')}'); final ProcessResult constFinderProcessResult = await _processManager.run(cmd); if (constFinderProcessResult.exitCode != 0) { throw IconTreeShakerException._('ConstFinder failure: ${constFinderProcessResult.stderr}'); } final Object? constFinderMap = json.decode(constFinderProcessResult.stdout as String); if (constFinderMap is! Map<String, Object?>) { throw IconTreeShakerException._( 'Invalid ConstFinder output: expected a top level JSON object, ' 'got $constFinderMap.'); } final _ConstFinderResult constFinderResult = _ConstFinderResult(constFinderMap); if (constFinderResult.hasNonConstantLocations) { _logger.printError('This application cannot tree shake icons fonts. ' 'It has non-constant instances of IconData at the ' 'following locations:', emphasis: true); for (final Map<String, Object?> location in constFinderResult.nonConstantLocations) { _logger.printError( '- ${location['file']}:${location['line']}:${location['column']}', indent: 2, hangingIndent: 4, ); } throwToolExit('Avoid non-constant invocations of IconData or try to ' 'build again with --no-tree-shake-icons.'); } return _parseConstFinderResult(constFinderResult); } Map<String, List<int>> _parseConstFinderResult(_ConstFinderResult constants) { final Map<String, List<int>> result = <String, List<int>>{}; for (final Map<String, Object?> iconDataMap in constants.constantInstances) { final Object? package = iconDataMap['fontPackage']; final Object? fontFamily = iconDataMap['fontFamily']; final Object? codePoint = iconDataMap['codePoint']; if ((package ?? '') is! String || // Null is ok here. fontFamily is! String || codePoint is! num) { throw IconTreeShakerException._( 'Invalid ConstFinder result. Expected "fontPackage" to be a String, ' '"fontFamily" to be a String, and "codePoint" to be an int, ' 'got: $iconDataMap.'); } final String family = fontFamily; final String key = package == null ? family : 'packages/$package/$family'; result[key] ??= <int>[]; result[key]!.add(codePoint.round()); } return result; } } class _ConstFinderResult { _ConstFinderResult(this.result); final Map<String, Object?> result; late final List<Map<String, Object?>> constantInstances = _getList( result['constantInstances'], 'Invalid ConstFinder output: Expected "constInstances" to be a list of objects.', ); late final List<Map<String, Object?>> nonConstantLocations = _getList( result['nonConstantLocations'], 'Invalid ConstFinder output: Expected "nonConstLocations" to be a list of objects', ); bool get hasNonConstantLocations => nonConstantLocations.isNotEmpty; } /// The font family name, relative path to font file, and list of code points /// the application is using. class _IconTreeShakerData { /// All parameters are required. const _IconTreeShakerData({ required this.family, required this.relativePath, required this.codePoints, required this.optionalCodePoints, }); /// The font family name, e.g. "MaterialIcons". final String family; /// The relative path to the font file. final String relativePath; /// The list of code points for the font. final List<int> codePoints; /// The list of code points to be optionally added, if they exist in the /// input font. Otherwise, the tool will silently omit them. final List<int> optionalCodePoints; @override String toString() => 'FontSubsetData($family, $relativePath, $codePoints)'; } class IconTreeShakerException implements Exception { IconTreeShakerException._(this.message); final String message; @override String toString() => 'IconTreeShakerException: $message\n\n' 'To disable icon tree shaking, pass --no-tree-shake-icons to the requested ' 'flutter build command'; }
flutter/packages/flutter_tools/lib/src/build_system/targets/icon_tree_shaker.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/icon_tree_shaker.dart", "repo_id": "flutter", "token_count": 5362 }
743
// 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:meta/meta.dart'; import 'package:process/process.dart'; import '../artifacts.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/terminal.dart'; import '../project.dart'; import '../project_validator.dart'; import '../runner/flutter_command.dart'; import 'analyze_base.dart'; import 'analyze_continuously.dart'; import 'analyze_once.dart'; import 'android_analyze.dart'; import 'ios_analyze.dart'; import 'validate_project.dart'; class AnalyzeCommand extends FlutterCommand { AnalyzeCommand({ bool verboseHelp = false, this.workingDirectory, required FileSystem fileSystem, required Platform platform, required Terminal terminal, required Logger logger, required ProcessManager processManager, required Artifacts artifacts, required List<ProjectValidator> allProjectValidators, required bool suppressAnalytics, }) : _artifacts = artifacts, _fileSystem = fileSystem, _processManager = processManager, _logger = logger, _terminal = terminal, _allProjectValidators = allProjectValidators, _platform = platform, _suppressAnalytics = suppressAnalytics { argParser.addFlag('flutter-repo', negatable: false, help: 'Include all the examples and tests from the Flutter repository.', hide: !verboseHelp); argParser.addFlag('current-package', help: 'Analyze the current project, if applicable.', defaultsTo: true); argParser.addFlag('dartdocs', negatable: false, help: '(deprecated) List every public member that is lacking documentation. ' 'This command will be removed in a future version of Flutter.', hide: !verboseHelp); argParser.addFlag('watch', help: 'Run analysis continuously, watching the filesystem for changes.', negatable: false); argParser.addOption('write', valueHelp: 'file', help: 'Also output the results to a file. This is useful with "--watch" ' 'if you want a file to always contain the latest results.'); argParser.addOption('dart-sdk', valueHelp: 'path-to-sdk', help: 'The path to the Dart SDK.', hide: !verboseHelp); argParser.addOption('protocol-traffic-log', valueHelp: 'path-to-protocol-traffic-log', help: 'The path to write the request and response protocol. This is ' 'only intended to be used for debugging the tooling.', hide: !verboseHelp); argParser.addFlag('suggestions', help: 'Show suggestions about the current flutter project.' ); argParser.addFlag('machine', negatable: false, help: 'Dumps a JSON with a subset of relevant data about the tool, project, ' 'and environment.', hide: !verboseHelp, ); // Hidden option to enable a benchmarking mode. argParser.addFlag('benchmark', negatable: false, hide: !verboseHelp, help: 'Also output the analysis time.'); usesPubOption(); // Not used by analyze --watch argParser.addFlag('congratulate', help: 'Show output even when there are no errors, warnings, hints, or lints. ' 'Ignored if "--watch" is specified.', defaultsTo: true); argParser.addFlag('preamble', defaultsTo: true, help: 'When analyzing the flutter repository, display the number of ' 'files that will be analyzed.\n' 'Ignored if "--watch" is specified.'); argParser.addFlag('fatal-infos', help: 'Treat info level issues as fatal.', defaultsTo: true); argParser.addFlag('fatal-warnings', help: 'Treat warning level issues as fatal.', defaultsTo: true); argParser.addFlag('android', negatable: false, help: 'Analyze Android sub-project. Used by internal tools only.', hide: !verboseHelp, ); argParser.addFlag('ios', negatable: false, help: 'Analyze iOS Xcode sub-project. Used by internal tools only.', hide: !verboseHelp, ); if (verboseHelp) { argParser.addSeparator('Usage: flutter analyze --android [arguments]'); } argParser.addFlag('list-build-variants', negatable: false, help: 'Print out a list of available build variants for the ' 'Android sub-project.', hide: !verboseHelp, ); argParser.addFlag('output-app-link-settings', negatable: false, help: 'Output a JSON with Android app link settings into a file. ' 'The "--build-variant" must also be set.', hide: !verboseHelp, ); argParser.addOption('build-variant', help: 'Sets the Android build variant to be analyzed.', valueHelp: 'build variant', hide: !verboseHelp, ); if (verboseHelp) { argParser.addSeparator('Usage: flutter analyze --ios [arguments]'); } argParser.addFlag('list-build-options', help: 'Print out a list of available build options for the ' 'iOS Xcode sub-project.', hide: !verboseHelp, ); argParser.addFlag('output-universal-link-settings', negatable: false, help: 'Output a JSON with iOS Xcode universal link settings into a file. ' 'The "--configuration" and "--target" must be set.', hide: !verboseHelp, ); argParser.addOption('configuration', help: 'Sets the iOS build configuration to be analyzed.', valueHelp: 'configuration', hide: !verboseHelp, ); argParser.addOption('target', help: 'Sets the iOS build target to be analyzed.', valueHelp: 'target', hide: !verboseHelp, ); } /// The working directory for testing analysis using dartanalyzer. final Directory? workingDirectory; final Artifacts _artifacts; final FileSystem _fileSystem; final Logger _logger; final Terminal _terminal; final ProcessManager _processManager; final Platform _platform; final List<ProjectValidator> _allProjectValidators; final bool _suppressAnalytics; @override String get name => 'analyze'; @override String get description => "Analyze the project's Dart code."; @override String get category => FlutterCommandCategory.project; @visibleForTesting List<ProjectValidator> allProjectValidators() => _allProjectValidators; @override bool get shouldRunPub { // If they're not analyzing the current project. if (!boolArg('current-package')) { return false; } // Or we're not in a project directory. if (!_fileSystem.file('pubspec.yaml').existsSync()) { return false; } // Don't run pub if asking for machine output. if (boolArg('machine')) { return false; } // Don't run pub if asking for android analysis. if (boolArg('android')) { return false; } return super.shouldRunPub; } @override Future<FlutterCommandResult> runCommand() async { if (boolArg('android')) { final AndroidAnalyzeOption option; final String? buildVariant; if (argResults!['list-build-variants'] as bool && argResults!['output-app-link-settings'] as bool) { throwToolExit('Only one of "--list-build-variants" or "--output-app-link-settings" can be provided'); } if (argResults!['list-build-variants'] as bool) { option = AndroidAnalyzeOption.listBuildVariant; buildVariant = null; } else if (argResults!['output-app-link-settings'] as bool) { option = AndroidAnalyzeOption.outputAppLinkSettings; buildVariant = argResults!['build-variant'] as String?; if (buildVariant == null) { throwToolExit('"--build-variant" must be provided'); } } else { throwToolExit('No argument is provided to analyze. Use -h to see available commands.'); } final Set<String> items = findDirectories(argResults!, _fileSystem); final String directoryPath; if (items.isEmpty) { // user did not specify any path directoryPath = _fileSystem.currentDirectory.path; } else if (items.length > 1) { // if the user sends more than one path throwToolExit('The Android analyze can process only one directory path'); } else { directoryPath = items.first; } await AndroidAnalyze( fileSystem: _fileSystem, option: option, userPath: directoryPath, buildVariant: buildVariant, logger: _logger, ).analyze(); } else if (boolArg('ios')) { final IOSAnalyzeOption option; final String? configuration; final String? target; if (argResults!['list-build-options'] as bool && argResults!['output-universal-link-settings'] as bool) { throwToolExit('Only one of "--list-build-options" or "--output-universal-link-settings" can be provided'); } if (argResults!['list-build-options'] as bool) { option = IOSAnalyzeOption.listBuildOptions; configuration = null; target = null; } else if (argResults!['output-universal-link-settings'] as bool) { option = IOSAnalyzeOption.outputUniversalLinkSettings; configuration = argResults!['configuration'] as String?; if (configuration == null) { throwToolExit('"--configuration" must be provided'); } target = argResults!['target'] as String?; if (target == null) { throwToolExit('"--target" must be provided'); } } else { throwToolExit('No argument is provided to analyze. Use -h to see available commands.'); } final Set<String> items = findDirectories(argResults!, _fileSystem); final String directoryPath; if (items.isEmpty) { // user did not specify any path directoryPath = _fileSystem.currentDirectory.path; } else if (items.length > 1) { // if the user sends more than one path throwToolExit('The iOS analyze can process only one directory path'); } else { directoryPath = items.first; } await IOSAnalyze( project: FlutterProject.fromDirectory(_fileSystem.directory(directoryPath)), option: option, configuration: configuration, target: target, logger: _logger, ).analyze(); } else if (boolArg('suggestions')) { final String directoryPath; if (boolArg('watch')) { throwToolExit('flag --watch is not compatible with --suggestions'); } if (workingDirectory == null) { final Set<String> items = findDirectories(argResults!, _fileSystem); if (items.isEmpty) { // user did not specify any path directoryPath = _fileSystem.currentDirectory.path; _logger.printTrace('Showing suggestions for current directory: $directoryPath'); } else if (items.length > 1) { // if the user sends more than one path throwToolExit('The suggestions flag can process only one directory path'); } else { directoryPath = items.first; } } else { directoryPath = workingDirectory!.path; } return ValidateProject( fileSystem: _fileSystem, logger: _logger, allProjectValidators: _allProjectValidators, userPath: directoryPath, processManager: _processManager, machine: boolArg('machine'), ).run(); } else if (boolArg('watch')) { await AnalyzeContinuously( argResults!, runner!.getRepoPackages(), fileSystem: _fileSystem, logger: _logger, platform: _platform, processManager: _processManager, terminal: _terminal, artifacts: _artifacts, suppressAnalytics: _suppressAnalytics, ).analyze(); } else { await AnalyzeOnce( argResults!, runner!.getRepoPackages(), workingDirectory: workingDirectory, fileSystem: _fileSystem, logger: _logger, platform: _platform, processManager: _processManager, terminal: _terminal, artifacts: _artifacts, suppressAnalytics: _suppressAnalytics, ).analyze(); } return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/analyze.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/analyze.dart", "repo_id": "flutter", "token_count": 4682 }
744
// 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:meta/meta.dart'; import '../artifacts.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../build_system/build_system.dart'; import '../build_system/targets/macos.dart'; import '../cache.dart'; import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../macos/cocoapod_utils.dart'; import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult; import '../version.dart'; import 'build_ios_framework.dart'; /// Produces a .framework for integration into a host macOS app. The .framework /// contains the Flutter engine and framework code as well as plugins. It can /// be integrated into plain Xcode projects without using or other package /// managers. class BuildMacOSFrameworkCommand extends BuildFrameworkCommand { BuildMacOSFrameworkCommand({ super.flutterVersion, required super.buildSystem, required super.verboseHelp, required super.logger, super.cache, super.platform, }); @override final String name = 'macos-framework'; @override final String description = 'Produces .xcframeworks for a Flutter project ' 'and its plugins for integration into existing, plain macOS Xcode projects.\n' 'This can only be run on macOS hosts.'; @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{ DevelopmentArtifact.macOS, }; @override Future<FlutterCommandResult> runCommand() async { final String outputArgument = stringArg('output') ?? globals.fs.path.join( globals.fs.currentDirectory.path, 'build', 'macos', 'framework', ); if (outputArgument.isEmpty) { throwToolExit('--output is required.'); } if (!project.macos.existsSync()) { throwToolExit('Project does not support macOS'); } final Directory outputDirectory = globals.fs.directory(globals.fs.path.absolute(globals.fs.path.normalize(outputArgument))); final List<BuildInfo> buildInfos = await getBuildInfos(); displayNullSafetyMode(buildInfos.first); for (final BuildInfo buildInfo in buildInfos) { globals.printStatus('Building macOS frameworks in ${buildInfo.mode.cliName} mode...'); final String xcodeBuildConfiguration = sentenceCase(buildInfo.mode.cliName); final Directory modeDirectory = outputDirectory.childDirectory(xcodeBuildConfiguration); if (modeDirectory.existsSync()) { modeDirectory.deleteSync(recursive: true); } if (boolArg('cocoapods')) { produceFlutterPodspec(buildInfo.mode, modeDirectory, force: boolArg('force')); } else { await _produceFlutterFramework(buildInfo, modeDirectory); } final Directory buildOutput = modeDirectory.childDirectory('macos'); // Build aot, create App.framework. Make XCFrameworks. await _produceAppFramework(buildInfo, modeDirectory, buildOutput); // Build and copy plugins. await processPodsIfNeeded(project.macos, getMacOSBuildDirectory(), buildInfo.mode); if (boolArg('plugins') && hasPlugins(project)) { await _producePlugins(xcodeBuildConfiguration, buildOutput, modeDirectory); } globals.logger.printStatus(' └─Moving to ${globals.fs.path.relative(modeDirectory.path)}'); // Copy the native assets. final Directory nativeAssetsDirectory = globals.fs .directory(getBuildDirectory()) .childDirectory('native_assets/macos/'); if (await nativeAssetsDirectory.exists()) { final ProcessResult rsyncResult = await globals.processManager.run(<Object>[ 'rsync', '-av', '--filter', '- .DS_Store', '--filter', '- native_assets.yaml', nativeAssetsDirectory.path, modeDirectory.path, ]); if (rsyncResult.exitCode != 0) { throwToolExit('Failed to copy native assets:\n${rsyncResult.stderr}'); } } // Delete the intermediaries since they would have been copied into our // output frameworks. if (buildOutput.existsSync()) { buildOutput.deleteSync(recursive: true); } } globals.printStatus('Frameworks written to ${outputDirectory.path}.'); if (hasPlugins(project)) { // Apps do not generate a FlutterPluginRegistrant.framework. Users will need // to copy GeneratedPluginRegistrant.swift to their project manually. final File pluginRegistrantImplementation = project.macos.pluginRegistrantImplementation; pluginRegistrantImplementation.copySync(outputDirectory.childFile(pluginRegistrantImplementation.basename).path); globals.printStatus('\nCopy ${globals.fs.path.basename(pluginRegistrantImplementation.path)} into your project.'); } return FlutterCommandResult.success(); } /// Create podspec that will download and unzip remote engine assets so host apps can leverage CocoaPods /// vendored framework caching. @visibleForTesting void produceFlutterPodspec(BuildMode mode, Directory modeDirectory, {bool force = false}) { final Status status = globals.logger.startProgress(' ├─Creating FlutterMacOS.podspec...'); try { final GitTagVersion gitTagVersion = flutterVersion.gitTagVersion; if (!force && (gitTagVersion.x == null || gitTagVersion.y == null || gitTagVersion.z == null || gitTagVersion.commits != 0)) { throwToolExit( '--cocoapods is only supported on the beta or stable channel. Detected version is ${flutterVersion.frameworkVersion}'); } // Podspecs use semantic versioning, which don't support hotfixes. // Fake out a semantic version with major.minor.(patch * 100) + hotfix. // A real increasing version is required to prompt CocoaPods to fetch // new artifacts when the source URL changes. final int minorHotfixVersion = (gitTagVersion.z ?? 0) * 100 + (gitTagVersion.hotfix ?? 0); final File license = cache.getLicenseFile(); if (!license.existsSync()) { throwToolExit('Could not find license at ${license.path}'); } final String licenseSource = license.readAsStringSync(); final String artifactsMode = mode == BuildMode.debug ? 'darwin-x64' : 'darwin-x64-${mode.cliName}'; final String podspecContents = ''' Pod::Spec.new do |s| s.name = 'FlutterMacOS' s.version = '${gitTagVersion.x}.${gitTagVersion.y}.$minorHotfixVersion' # ${flutterVersion.frameworkVersion} s.summary = 'A UI toolkit for beautiful and fast apps.' s.description = <<-DESC Flutter is Google's UI toolkit for building beautiful, fast apps for mobile, web, desktop, and embedded devices from a single codebase. This pod vends the macOS Flutter engine framework. It is compatible with application frameworks created with this version of the engine and tools. The pod version matches Flutter version major.minor.(patch * 100) + hotfix. DESC s.homepage = 'https://flutter.dev' s.license = { :type => 'BSD', :text => <<-LICENSE $licenseSource LICENSE } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => '${cache.storageBaseUrl}/flutter_infra_release/flutter/${cache.engineRevision}/$artifactsMode/FlutterMacOS.framework.zip' } s.documentation_url = 'https://flutter.dev/docs' s.osx.deployment_target = '10.14' s.vendored_frameworks = 'FlutterMacOS.framework' s.prepare_command = 'unzip FlutterMacOS.framework -d FlutterMacOS.framework' end '''; final File podspec = modeDirectory.childFile('FlutterMacOS.podspec')..createSync(recursive: true); podspec.writeAsStringSync(podspecContents); } finally { status.stop(); } } Future<void> _produceAppFramework( BuildInfo buildInfo, Directory outputBuildDirectory, Directory macosBuildOutput, ) async { final Status status = globals.logger.startProgress( ' ├─Building App.xcframework...', ); try { final Environment environment = Environment( projectDir: globals.fs.currentDirectory, outputDir: macosBuildOutput, buildDir: project.dartTool.childDirectory('flutter_build'), cacheDir: globals.cache.getRoot(), flutterRootDir: globals.fs.directory(Cache.flutterRoot), defines: <String, String>{ kTargetFile: targetFile, kTargetPlatform: getNameForTargetPlatform(TargetPlatform.darwin), kDarwinArchs: defaultMacOSArchsForEnvironment(globals.artifacts!) .map((DarwinArch e) => e.name) .join(' '), ...buildInfo.toBuildSystemEnvironment(), }, artifacts: globals.artifacts!, fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, platform: globals.platform, usage: globals.flutterUsage, analytics: globals.analytics, engineVersion: globals.artifacts!.isLocalEngine ? null : globals.flutterVersion.engineRevision, generateDartPluginRegistry: true, ); Target target; // Always build debug for simulator. if (buildInfo.isDebug) { target = const DebugMacOSBundleFlutterAssets(); } else if (buildInfo.isProfile) { target = const ProfileMacOSBundleFlutterAssets(); } else { target = const ReleaseMacOSBundleFlutterAssets(); } final BuildResult result = await buildSystem.build(target, environment); if (!result.success) { for (final ExceptionMeasurement measurement in result.exceptions.values) { globals.printError(measurement.exception.toString()); } throwToolExit('The App.xcframework build failed.'); } } finally { status.stop(); } final Directory appFramework = macosBuildOutput.childDirectory('App.framework'); await BuildFrameworkCommand.produceXCFramework( <Directory>[appFramework], 'App', outputBuildDirectory, globals.processManager, ); appFramework.deleteSync(recursive: true); } Future<void> _produceFlutterFramework( BuildInfo buildInfo, Directory modeDirectory, ) async { final Status status = globals.logger.startProgress( ' ├─Copying FlutterMacOS.xcframework...', ); final String engineCacheFlutterFrameworkDirectory = globals.artifacts!.getArtifactPath( Artifact.flutterMacOSXcframework, platform: TargetPlatform.darwin, mode: buildInfo.mode, ); final String flutterFrameworkFileName = globals.fs.path.basename( engineCacheFlutterFrameworkDirectory, ); final Directory flutterFrameworkCopy = modeDirectory.childDirectory( flutterFrameworkFileName, ); try { // Copy xcframework engine cache framework to mode directory. copyDirectory( globals.fs.directory(engineCacheFlutterFrameworkDirectory), flutterFrameworkCopy, followLinks: false, ); } finally { status.stop(); } } Future<void> _producePlugins( String xcodeBuildConfiguration, Directory buildOutput, Directory modeDirectory, ) async { final Status status = globals.logger.startProgress(' ├─Building plugins...'); try { final List<String> pluginsBuildCommand = <String>[ ...globals.xcode!.xcrunCommand(), 'xcodebuild', '-alltargets', '-sdk', 'macosx', '-configuration', xcodeBuildConfiguration, 'SYMROOT=${buildOutput.path}', 'ONLY_ACTIVE_ARCH=NO', // No device targeted, so build all valid architectures. 'BUILD_LIBRARY_FOR_DISTRIBUTION=YES', if (boolArg('static')) 'MACH_O_TYPE=staticlib', ]; final RunResult buildPluginsResult = await globals.processUtils.run( pluginsBuildCommand, workingDirectory: project.macos.hostAppRoot.childDirectory('Pods').path, ); if (buildPluginsResult.exitCode != 0) { throwToolExit('Unable to build plugin frameworks: ${buildPluginsResult.stderr}'); } final Directory buildConfiguration = buildOutput.childDirectory(xcodeBuildConfiguration); final Iterable<Directory> products = buildConfiguration.listSync(followLinks: false).whereType<Directory>(); for (final Directory builtProduct in products) { for (final FileSystemEntity podProduct in builtProduct.listSync(followLinks: false)) { final String podFrameworkName = podProduct.basename; if (globals.fs.path.extension(podFrameworkName) != '.framework') { continue; } final String binaryName = globals.fs.path.basenameWithoutExtension(podFrameworkName); await BuildFrameworkCommand.produceXCFramework( <Directory>[ podProduct as Directory, ], binaryName, modeDirectory, globals.processManager, ); } } } finally { status.stop(); } } }
flutter/packages/flutter_tools/lib/src/commands/build_macos_framework.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/build_macos_framework.dart", "repo_id": "flutter", "token_count": 5022 }
745
// 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:args/args.dart'; import '../base/common.dart'; import '../base/utils.dart'; import '../doctor_validator.dart'; import '../emulator.dart'; import '../globals.dart' as globals; import '../runner/flutter_command.dart'; class EmulatorsCommand extends FlutterCommand { EmulatorsCommand() { argParser.addOption('launch', help: 'The full or partial ID of the emulator to launch.'); argParser.addFlag('cold', help: 'Used with the "--launch" flag to cold boot the emulator instance (Android only).', negatable: false); argParser.addFlag('create', help: 'Creates a new Android emulator based on a Pixel device.', negatable: false); argParser.addOption('name', help: 'Used with the "--create" flag. Specifies a name for the emulator being created.'); } @override final String name = 'emulators'; @override final String description = 'List, launch and create emulators.'; @override final String category = FlutterCommandCategory.tools; @override final List<String> aliases = <String>['emulator']; @override Future<FlutterCommandResult> runCommand() async { if (globals.doctor!.workflows.every((Workflow w) => !w.canListEmulators)) { throwToolExit( 'Unable to find any emulator sources. Please ensure you have some\n' 'Android AVD images ${globals.platform.isMacOS ? 'or an iOS Simulator ' : ''}available.', exitCode: 1); } final ArgResults argumentResults = argResults!; if (argumentResults.wasParsed('launch')) { final bool coldBoot = argumentResults.wasParsed('cold'); await _launchEmulator(stringArg('launch')!, coldBoot: coldBoot); } else if (argumentResults.wasParsed('create')) { await _createEmulator(name: stringArg('name')); } else { final String? searchText = argumentResults.rest.isNotEmpty ? argumentResults.rest.first : null; await _listEmulators(searchText); } return FlutterCommandResult.success(); } Future<void> _launchEmulator(String id, { required bool coldBoot }) async { final List<Emulator> emulators = await emulatorManager!.getEmulatorsMatching(id); if (emulators.isEmpty) { globals.printStatus("No emulator found that matches '$id'."); } else if (emulators.length > 1) { _printEmulatorList( emulators, "More than one emulator matches '$id':", ); } else { await emulators.first.launch(coldBoot: coldBoot); } } Future<void> _createEmulator({ String? name }) async { final CreateEmulatorResult createResult = await emulatorManager!.createEmulator(name: name); if (createResult.success) { globals.printStatus("Emulator '${createResult.emulatorName}' created successfully."); } else { globals.printStatus("Failed to create emulator '${createResult.emulatorName}'.\n"); final String? error = createResult.error; if (error != null) { globals.printStatus(error.trim()); } _printAdditionalInfo(); } } Future<void> _listEmulators(String? searchText) async { final List<Emulator> emulators = searchText == null ? await emulatorManager!.getAllAvailableEmulators() : await emulatorManager!.getEmulatorsMatching(searchText); if (emulators.isEmpty) { globals.printStatus('No emulators available.'); _printAdditionalInfo(showCreateInstruction: true); } else { _printEmulatorList( emulators, '${emulators.length} available ${pluralize('emulator', emulators.length)}:', ); } } void _printEmulatorList(List<Emulator> emulators, String message) { globals.printStatus('$message\n'); Emulator.printEmulators(emulators, globals.logger); _printAdditionalInfo(showCreateInstruction: true, showRunInstruction: true); } void _printAdditionalInfo({ bool showRunInstruction = false, bool showCreateInstruction = false, }) { globals.printStatus(''); if (showRunInstruction) { globals.printStatus( "To run an emulator, run 'flutter emulators --launch <emulator id>'."); } if (showCreateInstruction) { globals.printStatus( "To create a new emulator, run 'flutter emulators --create [--name xyz]'."); } if (showRunInstruction || showCreateInstruction) { globals.printStatus(''); } // TODO(dantup): Update this link to flutter.dev if/when we have a better page. // That page can then link out to these places if required. globals.printStatus('You can find more information on managing emulators at the links below:\n' ' https://developer.android.com/studio/run/managing-avds\n' ' https://developer.android.com/studio/command-line/avdmanager'); } }
flutter/packages/flutter_tools/lib/src/commands/emulators.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/emulators.dart", "repo_id": "flutter", "token_count": 1797 }
746
// 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:meta/meta.dart'; import '../base/common.dart'; import '../base/io.dart'; import '../base/os.dart'; import '../base/process.dart'; import '../cache.dart'; import '../dart/pub.dart'; import '../globals.dart' as globals; import '../persistent_tool_state.dart'; import '../project.dart'; import '../runner/flutter_command.dart'; import '../version.dart'; import 'channel.dart'; // The official docs to install Flutter. const String _flutterInstallDocs = 'https://flutter.dev/docs/get-started/install'; class UpgradeCommand extends FlutterCommand { UpgradeCommand({ required bool verboseHelp, UpgradeCommandRunner? commandRunner, }) : _commandRunner = commandRunner ?? UpgradeCommandRunner() { argParser ..addFlag( 'force', abbr: 'f', help: 'Force upgrade the flutter branch, potentially discarding local changes.', negatable: false, ) ..addFlag( 'continue', hide: !verboseHelp, negatable: false, help: 'Trigger the second half of the upgrade flow. This should not be invoked ' 'manually. It is used re-entrantly by the standard upgrade command after ' 'the new version of Flutter is available, to hand off the upgrade process ' 'from the old version to the new version.', ) ..addOption( 'working-directory', hide: !verboseHelp, help: 'Override the upgrade working directory. ' 'This is only intended to enable integration testing of the tool itself.' // Also notably, this will override the FakeFlutterVersion if any is set! ) ..addFlag( 'verify-only', help: 'Checks for any new Flutter updates, without actually fetching them.', negatable: false, ); } final UpgradeCommandRunner _commandRunner; @override final String name = 'upgrade'; @override final String description = 'Upgrade your copy of Flutter.'; @override final String category = FlutterCommandCategory.sdk; @override bool get shouldUpdateCache => false; @override Future<FlutterCommandResult> runCommand() { _commandRunner.workingDirectory = stringArg('working-directory') ?? Cache.flutterRoot!; return _commandRunner.runCommand( force: boolArg('force'), continueFlow: boolArg('continue'), testFlow: stringArg('working-directory') != null, gitTagVersion: GitTagVersion.determine( globals.processUtils, globals.platform, workingDirectory: _commandRunner.workingDirectory, ), flutterVersion: stringArg('working-directory') == null ? globals.flutterVersion : FlutterVersion(flutterRoot: _commandRunner.workingDirectory!, fs: globals.fs), verifyOnly: boolArg('verify-only'), ); } } @visibleForTesting class UpgradeCommandRunner { String? workingDirectory; // set in runCommand() above Future<FlutterCommandResult> runCommand({ required bool force, required bool continueFlow, required bool testFlow, required GitTagVersion gitTagVersion, required FlutterVersion flutterVersion, required bool verifyOnly, }) async { if (!continueFlow) { await runCommandFirstHalf( force: force, gitTagVersion: gitTagVersion, flutterVersion: flutterVersion, testFlow: testFlow, verifyOnly: verifyOnly, ); } else { await runCommandSecondHalf(flutterVersion); } return FlutterCommandResult.success(); } Future<void> runCommandFirstHalf({ required bool force, required GitTagVersion gitTagVersion, required FlutterVersion flutterVersion, required bool testFlow, required bool verifyOnly, }) async { final FlutterVersion upstreamVersion = await fetchLatestVersion(localVersion: flutterVersion); if (flutterVersion.frameworkRevision == upstreamVersion.frameworkRevision) { globals.printStatus('Flutter is already up to date on channel ${flutterVersion.channel}'); globals.printStatus('$flutterVersion'); return; } else if (verifyOnly) { globals.printStatus('A new version of Flutter is available on channel ${flutterVersion.channel}\n'); globals.printStatus('The latest version: ${upstreamVersion.frameworkVersion} (revision ${upstreamVersion.frameworkRevisionShort})', emphasis: true); globals.printStatus('Your current version: ${flutterVersion.frameworkVersion} (revision ${flutterVersion.frameworkRevisionShort})\n'); globals.printStatus('To upgrade now, run "flutter upgrade".'); if (flutterVersion.channel == 'stable') { globals.printStatus('\nSee the announcement and release notes:'); globals.printStatus('https://flutter.dev/docs/development/tools/sdk/release-notes'); } return; } if (!force && gitTagVersion == const GitTagVersion.unknown()) { // If the commit is a recognized branch and not master, // explain that we are avoiding potential damage. if (flutterVersion.channel != 'master' && kOfficialChannels.contains(flutterVersion.channel)) { throwToolExit( 'Unknown flutter tag. Abandoning upgrade to avoid destroying local ' 'changes. It is recommended to use git directly if not working on ' 'an official channel.' ); // Otherwise explain that local changes can be lost. } else { throwToolExit( 'Unknown flutter tag. Abandoning upgrade to avoid destroying local ' 'changes. If it is okay to remove local changes, then re-run this ' 'command with "--force".' ); } } // If there are uncommitted changes we might be on the right commit but // we should still warn. if (!force && await hasUncommittedChanges()) { throwToolExit( 'Your flutter checkout has local changes that would be erased by ' 'upgrading. If you want to keep these changes, it is recommended that ' 'you stash them via "git stash" or else commit the changes to a local ' 'branch. If it is okay to remove local changes, then re-run this ' 'command with "--force".' ); } recordState(flutterVersion); await ChannelCommand.upgradeChannel(flutterVersion); globals.printStatus('Upgrading Flutter to ${upstreamVersion.frameworkVersion} from ${flutterVersion.frameworkVersion} in $workingDirectory...'); await attemptReset(upstreamVersion.frameworkRevision); if (!testFlow) { await flutterUpgradeContinue(); } } void recordState(FlutterVersion flutterVersion) { final Channel? channel = getChannelForName(flutterVersion.channel); if (channel == null) { return; } globals.persistentToolState!.updateLastActiveVersion(flutterVersion.frameworkRevision, channel); } Future<void> flutterUpgradeContinue() async { final int code = await globals.processUtils.stream( <String>[ globals.fs.path.join('bin', 'flutter'), 'upgrade', '--continue', '--no-version-check', ], workingDirectory: workingDirectory, allowReentrantFlutter: true, environment: Map<String, String>.of(globals.platform.environment), ); if (code != 0) { throwToolExit(null, exitCode: code); } } // This method should only be called if the upgrade command is invoked // re-entrantly with the `--continue` flag Future<void> runCommandSecondHalf(FlutterVersion flutterVersion) async { // Make sure the welcome message re-display is delayed until the end. final PersistentToolState persistentToolState = globals.persistentToolState!; persistentToolState.setShouldRedisplayWelcomeMessage(false); await precacheArtifacts(workingDirectory); await updatePackages(flutterVersion); await runDoctor(); // Force the welcome message to re-display following the upgrade. persistentToolState.setShouldRedisplayWelcomeMessage(true); if (globals.flutterVersion.channel == 'master' || globals.flutterVersion.channel == 'main') { globals.printStatus( '\n' 'This channel is intended for Flutter contributors. ' 'This channel is not as thoroughly tested as the "beta" and "stable" channels. ' 'We do not recommend using this channel for normal use as it more likely to contain serious regressions.\n' '\n' 'For information on contributing to Flutter, see our contributing guide:\n' ' https://github.com/flutter/flutter/blob/master/CONTRIBUTING.md\n' '\n' 'For the most up to date stable version of flutter, consider using the "beta" channel instead. ' 'The Flutter "beta" channel enjoys all the same automated testing as the "stable" channel, ' 'but is updated roughly once a month instead of once a quarter.\n' 'To change channel, run the "flutter channel beta" command.', ); } } Future<bool> hasUncommittedChanges() async { try { final RunResult result = await globals.processUtils.run( <String>['git', 'status', '-s'], throwOnError: true, workingDirectory: workingDirectory, ); return result.stdout.trim().isNotEmpty; } on ProcessException catch (error) { throwToolExit( 'The tool could not verify the status of the current flutter checkout. ' 'This might be due to git not being installed or an internal error. ' 'If it is okay to ignore potential local changes, then re-run this ' 'command with "--force".\n' 'Error: $error.' ); } } /// Returns the remote HEAD flutter version. /// /// Exits tool if HEAD isn't pointing to a branch, or there is no upstream. Future<FlutterVersion> fetchLatestVersion({ required FlutterVersion localVersion, }) async { String revision; try { // Fetch upstream branch's commits and tags await globals.processUtils.run( <String>['git', 'fetch', '--tags'], throwOnError: true, workingDirectory: workingDirectory, ); // Get the latest commit revision of the upstream final RunResult result = await globals.processUtils.run( <String>['git', 'rev-parse', '--verify', kGitTrackingUpstream], throwOnError: true, workingDirectory: workingDirectory, ); revision = result.stdout.trim(); } on Exception catch (e) { final String errorString = e.toString(); if (errorString.contains('fatal: HEAD does not point to a branch')) { throwToolExit( 'Unable to upgrade Flutter: Your Flutter checkout is currently not ' 'on a release branch.\n' 'Use "flutter channel" to switch to an official channel, and retry. ' 'Alternatively, re-install Flutter by going to $_flutterInstallDocs.' ); } else if (errorString.contains('fatal: no upstream configured for branch')) { throwToolExit( 'Unable to upgrade Flutter: The current Flutter branch/channel is ' 'not tracking any remote repository.\n' 'Re-install Flutter by going to $_flutterInstallDocs.' ); } else { throwToolExit(errorString); } } // At this point the current checkout should be on HEAD of a branch having // an upstream. Check whether this upstream is "standard". final VersionCheckError? error = VersionUpstreamValidator(version: localVersion, platform: globals.platform).run(); if (error != null) { throwToolExit( 'Unable to upgrade Flutter: ' '${error.message}\n' 'Reinstalling Flutter may fix this issue. Visit $_flutterInstallDocs ' 'for instructions.' ); } return FlutterVersion.fromRevision( flutterRoot: workingDirectory!, frameworkRevision: revision, fs: globals.fs, ); } /// Attempts a hard reset to the given revision. /// /// This is a reset instead of fast forward because if we are on a release /// branch with cherry picks, there may not be a direct fast-forward route /// to the next release. Future<void> attemptReset(String newRevision) async { try { await globals.processUtils.run( <String>['git', 'reset', '--hard', newRevision], throwOnError: true, workingDirectory: workingDirectory, ); } on ProcessException catch (e) { throwToolExit(e.message, exitCode: e.errorCode); } } /// Update the user's packages. Future<void> updatePackages(FlutterVersion flutterVersion) async { globals.printStatus(''); globals.printStatus(flutterVersion.toString()); final String? projectRoot = findProjectRoot(globals.fs); if (projectRoot != null) { globals.printStatus(''); await pub.get( context: PubContext.pubUpgrade, project: FlutterProject.fromDirectory(globals.fs.directory(projectRoot)), upgrade: true, ); } } /// Run flutter doctor in case requirements have changed. Future<void> runDoctor() async { globals.printStatus(''); globals.printStatus('Running flutter doctor...'); await globals.processUtils.stream( <String>[ globals.fs.path.join('bin', 'flutter'), '--no-version-check', 'doctor', ], workingDirectory: workingDirectory, allowReentrantFlutter: true, ); } } /// Update the engine repository and precache all artifacts. /// /// Check for and download any engine and pkg/ updates. We run the 'flutter' /// shell script reentrantly here so that it will download the updated /// Dart and so forth if necessary. Future<void> precacheArtifacts([String? workingDirectory]) async { globals.printStatus(''); globals.printStatus('Upgrading engine...'); final int code = await globals.processUtils.stream( <String>[ globals.fs.path.join('bin', 'flutter'), '--no-color', '--no-version-check', 'precache', ], allowReentrantFlutter: true, environment: Map<String, String>.of(globals.platform.environment), workingDirectory: workingDirectory, ); if (code != 0) { throwToolExit(null, exitCode: code); } }
flutter/packages/flutter_tools/lib/src/commands/upgrade.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/upgrade.dart", "repo_id": "flutter", "token_count": 5045 }
747
# Debug Adapter Protocol (DAP) This document is Flutter-specific. For information on the standard Dart DAP implementation, [see this document](https://github.com/dart-lang/sdk/blob/main/pkg/dds/tool/dap/README.md). Flutter includes support for debugging using [the Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/) as an alternative to using the [VM Service](https://github.com/dart-lang/sdk/blob/master/runtime/vm/service/service.md) directly, simplifying the integration for new editors. The debug adapters are started with the `flutter debug-adapter` command and are intended to be consumed by DAP-compliant tools such as Flutter-specific extensions for editors, or configured by users whose editors include generic configurable DAP clients. Two adapters are available: - `flutter debug_adapter` - `flutter debug_adapter --test` The standard adapter will run applications using `flutter run` while the `--test` adapter will cause scripts to be run using `flutter test` and will emit custom `dart.testNotification` events (described in the [Dart DAP documentation](https://github.com/dart-lang/sdk/blob/main/pkg/dds/tool/dap/README.md#darttestnotification)). Because in the DAP protocol the client speaks first, running this command from the terminal will result in no output (nor will the process terminate). This is expected behaviour. For details on the standard DAP functionality, see [the Debug Adapter Protocol Overview](https://microsoft.github.io/debug-adapter-protocol/) and [the Debug Adapter Protocol Specification](https://microsoft.github.io/debug-adapter-protocol/specification). Custom extensions are detailed below. ## Launch/Attach Arguments Arguments common to both `launchRequest` and `attachRequest` are: - `bool? debugExternalPackageLibraries` - whether to enable debugging for packages that are not inside the current workspace (if not supplied, defaults to `true`) - `bool? debugSdkLibraries` - whether to enable debugging for SDK libraries (if not supplied, defaults to `true`) - `bool? evaluateGettersInDebugViews` - whether to evaluate getters in expression evaluation requests (inc. hovers/watch windows) (if not supplied, defaults to `false`) - `bool? evaluateToStringInDebugViews` - whether to invoke `toString()` in expression evaluation requests (inc. hovers/watch windows) (if not supplied, defaults to `false`) - `bool? sendLogsToClient` - used to proxy all VM Service traffic back to the client in custom `dart.log` events (has performance implications, intended for troubleshooting) (if not supplied, defaults to `false`) - `List<String>? additionalProjectPaths` - paths of any projects (outside of `cwd`) that are open in the users workspace - `String? cwd` - the working directory for the Flutter process to be spawned in - `List<String>? toolArgs` - arguments for the `flutter run`, `flutter attach` or `flutter test` commands - `String? customTool` - an optional tool to run instead of `flutter` - the custom tool must be completely compatible with the tool/command it is replacing - `int? customToolReplacesArgs` - the number of arguments to delete from the beginning of the argument list when invoking `customTool` - e.g. setting `customTool` to `flutter_test_wrapper` and `customToolReplacesArgs` to `1` for a test run would invoke `flutter_test_wrapper foo_test.dart` instead of `flutter test foo_test.dart` (if larger than the number of computed arguments all arguments will be removed, if not supplied will default to `0`) Arguments specific to `launchRequest` are: - `bool? noDebug` - whether to run in debug or noDebug mode (if not supplied, defaults to debug) - `String program` - the path of the Flutter application to run - `List<String>? args` - arguments to be passed to the Flutter program Arguments specific to `attachRequest` are: - `String? vmServiceInfoFile` - the file to read the VM Service info from \* - `String? vmServiceUri` - the VM Service URI to attach to \* \* Only one of `vmServiceInfoFile` or `vmServiceUri` may be supplied. If neither are supplied, Flutter will try to discover it from the device. ## Custom Requests Some custom requests are available for clients to call. Below are the Flutter-specific custom requests, but the standard Dart DAP custom requests are also [documented here](https://github.com/dart-lang/sdk/blob/main/pkg/dds/tool/dap/README.md#custom-requests). ### `hotReload` `hotReload` injects updated source code files into the running VM and then rebuilds the widget tree. An optional `reason` can be provided and should usually be `"manual"` or `"save"` to indicate what how the reload was triggered (for example by the user clicking a button, versus a hot-reload-on-save feature). ``` { "reason": "manual" } ``` ### `hotRestart` `hotRestart` updates the code on the device and performs a full restart (which does not preserve state). An optional `reason` can be provided and should usually be `"manual"` or `"save"` to indicate what how the reload was triggered (for example by the user clicking a button, versus a hot-reload-on-save feature). ``` { "reason": "manual" } ``` ## Custom Events The debug adapter may emit several custom events that are useful to clients. Below are the Flutter-specific custom events, and the standard Dart DAP custom events are [documented here](https://github.com/dart-lang/sdk/blob/main/pkg/dds/tool/dap/README.md#custom-events). ### `flutter.appStarted` This event is emitted when the application has started up. Unlike `dart.debuggerUris`, this event occurs even for `noDebug` launches or those that do not include a VM Service. ### `flutter.serviceExtensionStateChanged` When the value of a Flutter service extension changes, this event is emitted and includes the new value. Values are always encoded as strings, even if numeric/boolean. ``` { "type": "event", "event": "flutter.serviceExtensionStateChanged", "body": { "extension": "ext.flutter.debugPaint", "value": "true", } } ```
flutter/packages/flutter_tools/lib/src/debug_adapters/README.md/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/debug_adapters/README.md", "repo_id": "flutter", "token_count": 1629 }
748
// 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 'dart:async'; import 'dart:math' as math; import 'package:file/file.dart'; import 'package:meta/meta.dart'; import 'package:package_config/package_config.dart'; import 'package:webdriver/async_io.dart' as async_io; import '../base/common.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../convert.dart'; import '../device.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../resident_runner.dart'; import '../web/web_runner.dart'; import 'drive_service.dart'; /// An implementation of the driver service for web debug and release applications. class WebDriverService extends DriverService { WebDriverService({ required ProcessUtils processUtils, required String dartSdkPath, required Logger logger, }) : _processUtils = processUtils, _dartSdkPath = dartSdkPath, _logger = logger; final ProcessUtils _processUtils; final String _dartSdkPath; final Logger _logger; late ResidentRunner _residentRunner; Uri? _webUri; @visibleForTesting Uri? get webUri => _webUri; /// The result of [ResidentRunner.run]. /// /// This is expected to stay `null` throughout the test, as the application /// must be running until [stop] is called. If it becomes non-null, it likely /// indicates a bug. int? _runResult; @override Future<void> start( BuildInfo buildInfo, Device device, DebuggingOptions debuggingOptions, bool ipv6, { File? applicationBinary, String? route, String? userIdentifier, String? mainPath, Map<String, Object> platformArgs = const <String, Object>{}, }) async { final FlutterDevice flutterDevice = await FlutterDevice.create( device, target: mainPath, buildInfo: buildInfo, platform: globals.platform, ); _residentRunner = webRunnerFactory!.createWebRunner( flutterDevice, target: mainPath, ipv6: ipv6, debuggingOptions: buildInfo.isRelease ? DebuggingOptions.disabled( buildInfo, port: debuggingOptions.port, hostname: debuggingOptions.hostname, webRenderer: debuggingOptions.webRenderer, ) : DebuggingOptions.enabled( buildInfo, port: debuggingOptions.port, hostname: debuggingOptions.hostname, disablePortPublication: debuggingOptions.disablePortPublication, webRenderer: debuggingOptions.webRenderer, ), stayResident: true, flutterProject: FlutterProject.current(), fileSystem: globals.fs, usage: globals.flutterUsage, analytics: globals.analytics, logger: _logger, systemClock: globals.systemClock, ); final Completer<void> appStartedCompleter = Completer<void>.sync(); final Future<int?> runFuture = _residentRunner.run( appStartedCompleter: appStartedCompleter, route: route, ); bool isAppStarted = false; await Future.any(<Future<Object?>>[ runFuture.then((int? result) { _runResult = result; return null; }), appStartedCompleter.future.then((_) { isAppStarted = true; return null; }), ]); if (_runResult != null) { throw ToolExit( 'Application exited before the test started. Check web driver logs ' 'for possible application-side errors.' ); } if (!isAppStarted) { throw ToolExit('Failed to start application'); } if (_residentRunner.uri == null) { throw ToolExit('Unable to connect to the app. URL not available.'); } if (debuggingOptions.webLaunchUrl != null) { // It should throw an error if the provided url is invalid so no tryParse _webUri = Uri.parse(debuggingOptions.webLaunchUrl!); } else { _webUri = _residentRunner.uri; } } @override Future<int> startTest( String testFile, List<String> arguments, Map<String, String> environment, PackageConfig packageConfig, { bool? headless, String? chromeBinary, String? browserName, bool? androidEmulator, int? driverPort, List<String> webBrowserFlags = const <String>[], List<String>? browserDimension, String? profileMemory, }) async { late async_io.WebDriver webDriver; final Browser browser = Browser.fromCliName(browserName); try { webDriver = await async_io.createDriver( uri: Uri.parse('http://localhost:$driverPort/'), desired: getDesiredCapabilities( browser, headless, webBrowserFlags: webBrowserFlags, chromeBinary: chromeBinary, ), ); } on SocketException catch (error) { _logger.printTrace('$error'); throwToolExit( 'Unable to start a WebDriver session for web testing.\n' 'Make sure you have the correct WebDriver server (e.g. chromedriver) running at $driverPort.\n' 'For instructions on how to obtain and run a WebDriver server, see:\n' 'https://flutter.dev/docs/testing/integration-tests#running-in-a-browser\n' ); } final bool isAndroidChrome = browser == Browser.androidChrome; // Do not set the window size for android chrome browser. if (!isAndroidChrome) { assert(browserDimension!.length == 2); late int x; late int y; try { x = int.parse(browserDimension![0]); y = int.parse(browserDimension[1]); } on FormatException catch (ex) { throwToolExit('Dimension provided to --browser-dimension is invalid: $ex'); } final async_io.Window window = await webDriver.window; await window.setLocation(const math.Point<int>(0, 0)); await window.setSize(math.Rectangle<int>(0, 0, x, y)); } final int result = await _processUtils.stream(<String>[ _dartSdkPath, ...arguments, testFile, '-rexpanded', ], environment: <String, String>{ 'VM_SERVICE_URL': _webUri.toString(), ..._additionalDriverEnvironment(webDriver, browserName, androidEmulator), ...environment, }); await webDriver.quit(); return result; } @override Future<void> stop({File? writeSkslOnExit, String? userIdentifier}) async { final bool appDidFinishPrematurely = _runResult != null; await _residentRunner.exitApp(); await _residentRunner.cleanupAtFinish(); if (appDidFinishPrematurely) { throw ToolExit( 'Application exited before the test finished. Check web driver logs ' 'for possible application-side errors.' ); } } Map<String, String> _additionalDriverEnvironment(async_io.WebDriver webDriver, String? browserName, bool? androidEmulator) { return <String, String>{ 'DRIVER_SESSION_ID': webDriver.id, 'DRIVER_SESSION_URI': webDriver.uri.toString(), 'DRIVER_SESSION_SPEC': webDriver.spec.toString(), 'DRIVER_SESSION_CAPABILITIES': json.encode(webDriver.capabilities), 'SUPPORT_TIMELINE_ACTION': (Browser.fromCliName(browserName) == Browser.chrome).toString(), 'FLUTTER_WEB_TEST': 'true', 'ANDROID_CHROME_ON_EMULATOR': (Browser.fromCliName(browserName) == Browser.androidChrome && androidEmulator!).toString(), }; } @override Future<void> reuseApplication(Uri vmServiceUri, Device device, DebuggingOptions debuggingOptions, bool ipv6) async { throwToolExit('--use-existing-app is not supported with flutter web driver'); } } /// A list of supported browsers. enum Browser implements CliEnum { /// Chrome on Android: https://developer.chrome.com/docs/multidevice/android/ androidChrome, /// Chrome: https://www.google.com/chrome/ chrome, /// Edge: https://www.microsoft.com/edge edge, /// Firefox: https://www.mozilla.org/en-US/firefox/ firefox, /// Safari in iOS: https://www.apple.com/safari/ iosSafari, /// Safari in macOS: https://www.apple.com/safari/ safari; @override String get helpText => switch (this) { Browser.androidChrome => 'Chrome on Android (see also "--android-emulator").', Browser.chrome => 'Google Chrome on this computer (see also "--chrome-binary").', Browser.edge => 'Microsoft Edge on this computer (Windows only).', Browser.firefox => 'Mozilla Firefox on this computer.', Browser.iosSafari => 'Apple Safari on an iOS device.', Browser.safari => 'Apple Safari on this computer (macOS only).', }; @override String get cliName => snakeCase(name, '-'); static Browser fromCliName(String? value) => Browser.values.singleWhere( (Browser element) => element.cliName == value, orElse: () => throw UnsupportedError('Browser $value not supported'), ); } /// Returns desired capabilities for given [browser], [headless], [chromeBinary] /// and [webBrowserFlags]. @visibleForTesting Map<String, dynamic> getDesiredCapabilities( Browser browser, bool? headless, { List<String> webBrowserFlags = const <String>[], String? chromeBinary, }) => switch (browser) { Browser.chrome => <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'chrome', 'goog:loggingPrefs': <String, String>{ async_io.LogType.browser: 'INFO', async_io.LogType.performance: 'ALL', }, 'goog:chromeOptions': <String, dynamic>{ if (chromeBinary != null) 'binary': chromeBinary, 'w3c': true, 'args': <String>[ '--bwsi', '--disable-background-timer-throttling', '--disable-default-apps', '--disable-extensions', '--disable-popup-blocking', '--disable-translate', '--no-default-browser-check', '--no-sandbox', '--no-first-run', if (headless!) '--headless', ...webBrowserFlags, ], 'perfLoggingPrefs': <String, String>{ 'traceCategories': 'devtools.timeline,' 'v8,blink.console,benchmark,blink,' 'blink.user_timing', }, }, }, Browser.firefox => <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'firefox', 'moz:firefoxOptions': <String, dynamic>{ 'args': <String>[ if (headless!) '-headless', ...webBrowserFlags, ], 'prefs': <String, dynamic>{ 'dom.file.createInChild': true, 'dom.timeout.background_throttling_max_budget': -1, 'media.autoplay.default': 0, 'media.gmp-manager.url': '', 'media.gmp-provider.enabled': false, 'network.captive-portal-service.enabled': false, 'security.insecure_field_warning.contextual.enabled': false, 'test.currentTimeOffsetSeconds': 11491200, }, 'log': <String, String>{'level': 'trace'}, }, }, Browser.edge => <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'edge', }, Browser.safari => <String, dynamic>{ 'browserName': 'safari', }, Browser.iosSafari => <String, dynamic>{ 'platformName': 'ios', 'browserName': 'safari', 'safari:useSimulator': true, }, Browser.androidChrome => <String, dynamic>{ 'browserName': 'chrome', 'platformName': 'android', 'goog:chromeOptions': <String, dynamic>{ 'androidPackage': 'com.android.chrome', 'args': <String>[ '--disable-fullscreen', ...webBrowserFlags, ], }, }, };
flutter/packages/flutter_tools/lib/src/drive/web_driver_service.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/drive/web_driver_service.dart", "repo_id": "flutter", "token_count": 4854 }
749
// 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 '../base/context.dart'; import '../base/platform.dart'; import '../doctor_validator.dart'; import '../features.dart'; import 'fuchsia_sdk.dart'; /// The [FuchsiaWorkflow] instance. FuchsiaWorkflow? get fuchsiaWorkflow => context.get<FuchsiaWorkflow>(); /// The Fuchsia-specific implementation of a [Workflow]. /// /// This workflow assumes development within the fuchsia source tree, /// including a working fx command-line tool in the user's PATH. class FuchsiaWorkflow implements Workflow { FuchsiaWorkflow({ required Platform platform, required FeatureFlags featureFlags, required FuchsiaArtifacts fuchsiaArtifacts, }) : _platform = platform, _featureFlags = featureFlags, _fuchsiaArtifacts = fuchsiaArtifacts; final Platform _platform; final FeatureFlags _featureFlags; final FuchsiaArtifacts _fuchsiaArtifacts; @override bool get appliesToHostPlatform => _featureFlags.isFuchsiaEnabled && (_platform.isLinux || _platform.isMacOS); @override bool get canListDevices { return _fuchsiaArtifacts.ffx != null; } @override bool get canLaunchDevices { return _fuchsiaArtifacts.ffx != null && _fuchsiaArtifacts.sshConfig != null; } @override bool get canListEmulators => false; }
flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_workflow.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_workflow.dart", "repo_id": "flutter", "token_count": 447 }
750
// 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 '../../base/file_system.dart'; import '../../base/project_migrator.dart'; import '../../xcode_project.dart'; /// Update the minimum iOS deployment version to the minimum allowed by Xcode without causing a warning. class IOSDeploymentTargetMigration extends ProjectMigrator { IOSDeploymentTargetMigration( IosProject project, super.logger, ) : _xcodeProjectInfoFile = project.xcodeProjectInfoFile, _podfile = project.podfile, _appFrameworkInfoPlist = project.appFrameworkInfoPlist; final File _xcodeProjectInfoFile; final File _podfile; final File _appFrameworkInfoPlist; @override void migrate() { if (_xcodeProjectInfoFile.existsSync()) { processFileLines(_xcodeProjectInfoFile); } else { logger.printTrace('Xcode project not found, skipping iOS deployment target version migration.'); } if (_appFrameworkInfoPlist.existsSync()) { processFileLines(_appFrameworkInfoPlist); } else { logger.printTrace('AppFrameworkInfo.plist not found, skipping minimum OS version migration.'); } if (_podfile.existsSync()) { processFileLines(_podfile); } else { logger.printTrace('Podfile not found, skipping global platform iOS version migration.'); } } @override String migrateFileContents(String fileContents) { const String minimumOSVersionOriginal8 = ''' <key>MinimumOSVersion</key> <string>8.0</string> '''; const String minimumOSVersionOriginal9 = ''' <key>MinimumOSVersion</key> <string>9.0</string> '''; const String minimumOSVersionOriginal11 = ''' <key>MinimumOSVersion</key> <string>11.0</string> '''; const String minimumOSVersionReplacement = ''' <key>MinimumOSVersion</key> <string>12.0</string> '''; return fileContents .replaceAll(minimumOSVersionOriginal8, minimumOSVersionReplacement) .replaceAll(minimumOSVersionOriginal9, minimumOSVersionReplacement) .replaceAll(minimumOSVersionOriginal11, minimumOSVersionReplacement); } @override String? migrateLine(String line) { // Xcode project file changes. const String deploymentTargetOriginal8 = 'IPHONEOS_DEPLOYMENT_TARGET = 8.0;'; const String deploymentTargetOriginal9 = 'IPHONEOS_DEPLOYMENT_TARGET = 9.0;'; const String deploymentTargetOriginal11 = 'IPHONEOS_DEPLOYMENT_TARGET = 11.0;'; // Podfile changes. const String podfilePlatformVersionOriginal9 = "platform :ios, '9.0'"; const String podfilePlatformVersionOriginal11 = "platform :ios, '11.0'"; if (line.contains(deploymentTargetOriginal8) || line.contains(deploymentTargetOriginal9) || line.contains(deploymentTargetOriginal11) || line.contains(podfilePlatformVersionOriginal9) || line.contains(podfilePlatformVersionOriginal11)) { if (!migrationRequired) { // Only print for the first discovered change found. logger.printStatus('Updating minimum iOS deployment target to 12.0.'); } const String deploymentTargetReplacement = 'IPHONEOS_DEPLOYMENT_TARGET = 12.0;'; const String podfilePlatformVersionReplacement = "platform :ios, '12.0'"; return line .replaceAll(deploymentTargetOriginal8, deploymentTargetReplacement) .replaceAll(deploymentTargetOriginal9, deploymentTargetReplacement) .replaceAll(deploymentTargetOriginal11, deploymentTargetReplacement) .replaceAll(podfilePlatformVersionOriginal9, podfilePlatformVersionReplacement) .replaceAll(podfilePlatformVersionOriginal11, podfilePlatformVersionReplacement); } return line; } }
flutter/packages/flutter_tools/lib/src/ios/migrations/ios_deployment_target_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/migrations/ios_deployment_target_migration.dart", "repo_id": "flutter", "token_count": 1283 }
751
// 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:native_assets_builder/native_assets_builder.dart' hide NativeAssetsBuildRunner; import 'package:native_assets_cli/native_assets_cli_internal.dart' as native_assets_cli; import 'package:native_assets_cli/native_assets_cli_internal.dart' hide BuildMode; import '../../../android/android_sdk.dart'; import '../../../base/common.dart'; import '../../../base/file_system.dart'; import '../../../build_info.dart'; import '../../../globals.dart' as globals; import '../native_assets.dart'; /// Dry run the native builds. /// /// This does not build native assets, it only simulates what the final paths /// of all assets will be so that this can be embedded in the kernel file. Future<Uri?> dryRunNativeAssetsAndroid({ required NativeAssetsBuildRunner buildRunner, required Uri projectUri, bool flutterTester = false, required FileSystem fileSystem, }) async { if (!await nativeBuildRequired(buildRunner)) { return null; } final Uri buildUri_ = nativeAssetsBuildUri(projectUri, OS.android); final Iterable<KernelAsset> nativeAssetPaths = await dryRunNativeAssetsAndroidInternal( fileSystem, projectUri, buildRunner, ); final Uri nativeAssetsUri = await writeNativeAssetsYaml( KernelAssets(nativeAssetPaths), buildUri_, fileSystem, ); return nativeAssetsUri; } Future<Iterable<KernelAsset>> dryRunNativeAssetsAndroidInternal( FileSystem fileSystem, Uri projectUri, NativeAssetsBuildRunner buildRunner, ) async { const OS targetOS = OS.android; globals.logger.printTrace('Dry running native assets for $targetOS.'); final DryRunResult dryRunResult = await buildRunner.dryRun( linkModePreference: LinkModePreference.dynamic, targetOS: targetOS, workingDirectory: projectUri, includeParentEnvironment: true, ); ensureNativeAssetsBuildSucceed(dryRunResult); final List<Asset> nativeAssets = dryRunResult.assets; ensureNoLinkModeStatic(nativeAssets); globals.logger.printTrace('Dry running native assets for $targetOS done.'); final Map<Asset, KernelAsset> assetTargetLocations = _assetTargetLocations(nativeAssets); return assetTargetLocations.values; } /// Builds native assets. Future<(Uri? nativeAssetsYaml, List<Uri> dependencies)> buildNativeAssetsAndroid({ required NativeAssetsBuildRunner buildRunner, required Iterable<AndroidArch> androidArchs, required Uri projectUri, required BuildMode buildMode, String? codesignIdentity, Uri? yamlParentDirectory, required FileSystem fileSystem, required int targetAndroidNdkApi, }) async { const OS targetOS = OS.android; final Uri buildUri_ = nativeAssetsBuildUri(projectUri, targetOS); if (!await nativeBuildRequired(buildRunner)) { final Uri nativeAssetsYaml = await writeNativeAssetsYaml( KernelAssets(), yamlParentDirectory ?? buildUri_, fileSystem, ); return (nativeAssetsYaml, <Uri>[]); } final List<Target> targets = androidArchs.map(_getNativeTarget).toList(); final native_assets_cli.BuildMode buildModeCli = nativeAssetsBuildMode(buildMode); globals.logger .printTrace('Building native assets for $targets $buildModeCli.'); final List<Asset> nativeAssets = <Asset>[]; final Set<Uri> dependencies = <Uri>{}; for (final Target target in targets) { final BuildResult result = await buildRunner.build( linkModePreference: LinkModePreference.dynamic, target: target, buildMode: buildModeCli, workingDirectory: projectUri, includeParentEnvironment: true, cCompilerConfig: await buildRunner.ndkCCompilerConfig, targetAndroidNdkApi: targetAndroidNdkApi, ); ensureNativeAssetsBuildSucceed(result); nativeAssets.addAll(result.assets); dependencies.addAll(result.dependencies); } ensureNoLinkModeStatic(nativeAssets); globals.logger.printTrace('Building native assets for $targets done.'); final Map<Asset, KernelAsset> assetTargetLocations = _assetTargetLocations(nativeAssets); await _copyNativeAssetsAndroid(buildUri_, assetTargetLocations, fileSystem); final Uri nativeAssetsUri = await writeNativeAssetsYaml( KernelAssets(assetTargetLocations.values), yamlParentDirectory ?? buildUri_, fileSystem); return (nativeAssetsUri, dependencies.toList()); } Future<void> _copyNativeAssetsAndroid( Uri buildUri, Map<Asset, KernelAsset> assetTargetLocations, FileSystem fileSystem, ) async { if (assetTargetLocations.isNotEmpty) { globals.logger .printTrace('Copying native assets to ${buildUri.toFilePath()}.'); final List<String> jniArchDirs = <String>[ for (final AndroidArch androidArch in AndroidArch.values) androidArch.archName, ]; for (final String jniArchDir in jniArchDirs) { final Uri archUri = buildUri.resolve('jniLibs/lib/$jniArchDir/'); await fileSystem.directory(archUri).create(recursive: true); } for (final MapEntry<Asset, KernelAsset> assetMapping in assetTargetLocations.entries) { final Uri source = (assetMapping.key.path as AssetAbsolutePath).uri; final Uri target = (assetMapping.value.path as KernelAssetAbsolutePath).uri; final AndroidArch androidArch = _getAndroidArch(assetMapping.value.target); final String jniArchDir = androidArch.archName; final Uri archUri = buildUri.resolve('jniLibs/lib/$jniArchDir/'); final Uri targetUri = archUri.resolveUri(target); final String targetFullPath = targetUri.toFilePath(); await fileSystem.file(source).copy(targetFullPath); } globals.logger.printTrace('Copying native assets done.'); } } /// Get the [Target] for [androidArch]. Target _getNativeTarget(AndroidArch androidArch) { switch (androidArch) { case AndroidArch.armeabi_v7a: return Target.androidArm; case AndroidArch.arm64_v8a: return Target.androidArm64; case AndroidArch.x86: return Target.androidIA32; case AndroidArch.x86_64: return Target.androidX64; } } /// Get the [AndroidArch] for [target]. AndroidArch _getAndroidArch(Target target) { switch (target) { case Target.androidArm: return AndroidArch.armeabi_v7a; case Target.androidArm64: return AndroidArch.arm64_v8a; case Target.androidIA32: return AndroidArch.x86; case Target.androidX64: return AndroidArch.x86_64; case Target.androidRiscv64: throwToolExit('Android RISC-V not yet supported.'); default: throwToolExit('Invalid target: $target.'); } } Map<Asset, KernelAsset> _assetTargetLocations(List<Asset> nativeAssets) { return <Asset, KernelAsset>{ for (final Asset asset in nativeAssets) asset: _targetLocationAndroid(asset), }; } /// Converts the `path` of [asset] as output from a `build.dart` invocation to /// the path used inside the Flutter app bundle. KernelAsset _targetLocationAndroid(Asset asset) { final AssetPath path = asset.path; final KernelAssetPath kernelAssetPath; switch (path) { case AssetSystemPath _: kernelAssetPath = KernelAssetSystemPath(path.uri); case AssetInExecutable _: kernelAssetPath = KernelAssetInExecutable(); case AssetInProcess _: kernelAssetPath = KernelAssetInProcess(); case AssetAbsolutePath _: final String fileName = path.uri.pathSegments.last; kernelAssetPath = KernelAssetAbsolutePath(Uri(path: fileName)); default: throw Exception( 'Unsupported asset path type ${path.runtimeType} in asset $asset', ); } return KernelAsset( id: asset.id, target: asset.target, path: kernelAssetPath, ); } /// Looks the NDK clang compiler tools. /// /// Tool-exits if the NDK cannot be found. /// /// Should only be invoked if a native assets build is performed. If the native /// assets feature is disabled, or none of the packages have native assets, a /// missing NDK is okay. @override Future<CCompilerConfig> cCompilerConfigAndroid() async { final AndroidSdk? androidSdk = AndroidSdk.locateAndroidSdk(); if (androidSdk == null) { throwToolExit('Android SDK could not be found.'); } final CCompilerConfig result = CCompilerConfig( cc: _toOptionalFileUri(androidSdk.getNdkClangPath()), ar: _toOptionalFileUri(androidSdk.getNdkArPath()), ld: _toOptionalFileUri(androidSdk.getNdkLdPath()), ); if (result.cc == null || result.ar == null || result.ld == null) { throwToolExit('Android NDK Clang could not be found.'); } return result; } Uri? _toOptionalFileUri(String? string) { if (string == null) { return null; } return Uri.file(string); }
flutter/packages/flutter_tools/lib/src/isolated/native_assets/android/native_assets.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/isolated/native_assets/android/native_assets.dart", "repo_id": "flutter", "token_count": 3033 }
752
// 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. const String emptyPubspecTemplate = ''' # Generated by the flutter tool name: synthetic_package description: The Flutter application's synthetic package. '''; const String fileTemplate = ''' @(header)import 'dart:async'; @(requiresFoundationImport) import 'package:flutter/widgets.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:intl/intl.dart' as intl; @(messageClassImports) /// Callers can lookup localized strings with an instance of @(class) /// returned by `@(class).of(context)`. /// /// Applications need to include `@(class).delegate()` in their app's /// `localizationDelegates` list, and the locales they support in the app's /// `supportedLocales` list. For example: /// /// ```dart /// import '@(importFile)'; /// /// return MaterialApp( /// localizationsDelegates: @(class).localizationsDelegates, /// supportedLocales: @(class).supportedLocales, /// home: MyApplicationHome(), /// ); /// ``` /// /// ## Update pubspec.yaml /// /// Please make sure to update your pubspec.yaml to include the following /// packages: /// /// ```yaml /// dependencies: /// # Internationalization support. /// flutter_localizations: /// sdk: flutter /// intl: any # Use the pinned version from flutter_localizations /// /// # Rest of dependencies /// ``` /// /// ## iOS Applications /// /// iOS applications define key application metadata, including supported /// locales, in an Info.plist file that is built into the application bundle. /// To configure the locales supported by your app, you’ll need to edit this /// file. /// /// First, open your project’s ios/Runner.xcworkspace Xcode workspace file. /// Then, in the Project Navigator, open the Info.plist file under the Runner /// project’s Runner folder. /// /// Next, select the Information Property List item, select Add Item from the /// Editor menu, then select Localizations from the pop-up menu. /// /// Select and expand the newly-created Localizations item then, for each /// locale your application supports, add a new item and select the locale /// you wish to add from the pop-up menu in the Value field. This list should /// be consistent with the languages listed in the @(class).supportedLocales /// property. abstract class @(class) { @(class)(String locale) : localeName = intl.Intl.canonicalizedLocale(locale.toString()); final String localeName; static @(class)@(canBeNullable) of(BuildContext context) { return Localizations.of<@(class)>(context, @(class))@(needsNullCheck); } static const LocalizationsDelegate<@(class)> delegate = _@(class)Delegate(); /// A list of this localizations delegate along with the default localizations /// delegates. /// /// Returns a list of localizations delegates containing this delegate along with /// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, /// and GlobalWidgetsLocalizations.delegate. /// /// Additional delegates can be added by appending to this list in /// MaterialApp. This list does not have to be used at all if a custom list /// of delegates is preferred or required. static const List<LocalizationsDelegate<dynamic>> localizationsDelegates = <LocalizationsDelegate<dynamic>>[ delegate, GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ]; /// A list of this localizations delegate's supported locales. static const List<Locale> supportedLocales = <Locale>[ @(supportedLocales) ]; @(methods)} @(delegateClass) '''; const String numberFormatPositionalTemplate = ''' final intl.NumberFormat @(placeholder)NumberFormat = intl.NumberFormat.@(format)(localeName); final String @(placeholder)String = @(placeholder)NumberFormat.format(@(placeholder)); '''; const String numberFormatNamedTemplate = ''' final intl.NumberFormat @(placeholder)NumberFormat = intl.NumberFormat.@(format)( locale: localeName, @(parameters) ); final String @(placeholder)String = @(placeholder)NumberFormat.format(@(placeholder)); '''; const String dateFormatTemplate = ''' final intl.DateFormat @(placeholder)DateFormat = intl.DateFormat.@(format)(localeName); final String @(placeholder)String = @(placeholder)DateFormat.format(@(placeholder)); '''; const String dateFormatCustomTemplate = ''' final intl.DateFormat @(placeholder)DateFormat = intl.DateFormat(@(format), localeName); final String @(placeholder)String = @(placeholder)DateFormat.format(@(placeholder)); '''; const String getterTemplate = ''' @override String get @(name) => @(message);'''; const String methodTemplate = ''' @override String @(name)(@(parameters)) { @(dateFormatting) @(numberFormatting) @(tempVars) return @(message); }'''; const String methodWithNamedParameterTemplate = ''' @override String @(name)({@(parameters)}) { @(dateFormatting) @(numberFormatting) @(tempVars) return @(message); }'''; const String pluralVariableTemplate = ''' String @(varName) = intl.Intl.pluralLogic( @(count), locale: localeName, @(pluralLogicArgs) );'''; const String selectVariableTemplate = ''' String @(varName) = intl.Intl.selectLogic( @(choice), { @(selectCases) }, );'''; const String dateVariableTemplate = ''' String @(varName) = intl.DateFormat.@(formatType)(localeName).format(@(argument));'''; const String classFileTemplate = ''' @(header)@(requiresIntlImport)import '@(fileName)'; /// The translations for @(language) (`@(localeName)`). class @(class) extends @(baseClass) { @(class)([String locale = '@(localeName)']) : super(locale); @(methods) } @(subclasses)'''; const String subclassTemplate = ''' /// The translations for @(language) (`@(localeName)`). class @(class) extends @(baseLanguageClassName) { @(class)(): super('@(localeName)'); @(methods) } '''; const String baseClassGetterTemplate = ''' @(comment) /// @(templateLocaleTranslationComment) String get @(name); '''; const String baseClassMethodTemplate = ''' @(comment) /// @(templateLocaleTranslationComment) String @(name)(@(parameters)); '''; const String baseClassMethodWithNamedParameterTemplate = ''' @(comment) /// @(templateLocaleTranslationComment) String @(name)({@(parameters)}); '''; // DELEGATE CLASS TEMPLATES const String delegateClassTemplate = ''' class _@(class)Delegate extends LocalizationsDelegate<@(class)> { const _@(class)Delegate(); @override Future<@(class)> load(Locale locale) { @(loadBody) } @override bool isSupported(Locale locale) => <String>[@(supportedLanguageCodes)].contains(locale.languageCode); @override bool shouldReload(_@(class)Delegate old) => false; } @(lookupFunction)'''; const String loadBodyTemplate = '''return SynchronousFuture<@(class)>(@(lookupName)(locale));'''; const String loadBodyDeferredLoadingTemplate = '''return @(lookupName)(locale);'''; // DELEGATE LOOKUP TEMPLATES const String lookupFunctionTemplate = r''' @(class) @(lookupName)(Locale locale) { @(lookupBody) throw FlutterError( '@(class).delegate failed to load unsupported locale "$locale". This is likely ' 'an issue with the localizations generation tool. Please file an issue ' 'on GitHub with a reproducible sample app and the gen-l10n configuration ' 'that was used.' ); }'''; const String lookupFunctionDeferredLoadingTemplate = r''' Future<@(class)> @(lookupName)(Locale locale) { @(lookupBody) throw FlutterError( '@(class).delegate failed to load unsupported locale "$locale". This is likely ' 'an issue with the localizations generation tool. Please file an issue ' 'on GitHub with a reproducible sample app and the gen-l10n configuration ' 'that was used.' ); }'''; const String lookupBodyTemplate = ''' @(lookupAllCodesSpecified) @(lookupScriptCodeSpecified) @(lookupCountryCodeSpecified) @(lookupLanguageCodeSpecified)'''; const String switchClauseTemplate = '''case '@(case)': return @(localeClass)();'''; const String switchClauseDeferredLoadingTemplate = '''case '@(case)': return @(library).loadLibrary().then((dynamic _) => @(library).@(localeClass)());'''; const String nestedSwitchTemplate = ''' case '@(languageCode)': { switch (locale.@(code)) { @(switchClauses) } break; }'''; const String languageCodeSwitchTemplate = ''' @(comment) switch (locale.languageCode) { @(switchClauses) } '''; const String allCodesLookupTemplate = ''' // Lookup logic when language+script+country codes are specified. switch (locale.toString()) { @(allCodesSwitchClauses) } ''';
flutter/packages/flutter_tools/lib/src/localizations/gen_l10n_templates.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/localizations/gen_l10n_templates.dart", "repo_id": "flutter", "token_count": 2786 }
753