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/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
class TestPointerSignalListener {
TestPointerSignalListener(this.event);
final PointerSignalEvent event;
bool callbackRan = false;
void callback(PointerSignalEvent event) {
expect(event, equals(this.event));
expect(callbackRan, isFalse);
callbackRan = true;
}
}
class PointerSignalTester {
final PointerSignalResolver resolver = PointerSignalResolver();
PointerSignalEvent event = const PointerScrollEvent();
TestPointerSignalListener addListener() {
final TestPointerSignalListener listener = TestPointerSignalListener(event);
resolver.register(event, listener.callback);
return listener;
}
/// Simulates a new event dispatch cycle by resolving the current event and
/// setting a new event to use for future calls.
void resolve() {
resolver.resolve(event);
event = const PointerScrollEvent();
}
}
void main() {
test('Resolving with no entries should be a no-op', () {
final PointerSignalTester tester = PointerSignalTester();
tester.resolver.resolve(tester.event);
});
test('First entry should always win', () {
final PointerSignalTester tester = PointerSignalTester();
final TestPointerSignalListener first = tester.addListener();
final TestPointerSignalListener second = tester.addListener();
tester.resolve();
expect(first.callbackRan, isTrue);
expect(second.callbackRan, isFalse);
});
test('Re-use after resolve should work', () {
final PointerSignalTester tester = PointerSignalTester();
final TestPointerSignalListener first = tester.addListener();
final TestPointerSignalListener second = tester.addListener();
tester.resolve();
expect(first.callbackRan, isTrue);
expect(second.callbackRan, isFalse);
final TestPointerSignalListener newEventListener = tester.addListener();
tester.resolve();
expect(newEventListener.callbackRan, isTrue);
// Nothing should have changed for the previous event's listeners.
expect(first.callbackRan, isTrue);
expect(second.callbackRan, isFalse);
});
test('works with transformed events', () {
final PointerSignalResolver resolver = PointerSignalResolver();
const PointerScrollEvent originalEvent = PointerScrollEvent();
final PointerSignalEvent transformedEvent = originalEvent
.transformed(Matrix4.translationValues(10.0, 20.0, 0.0));
final PointerSignalEvent anotherTransformedEvent = originalEvent
.transformed(Matrix4.translationValues(30.0, 50.0, 0.0));
expect(originalEvent, isNot(same(transformedEvent)));
expect(transformedEvent.original, same(originalEvent));
expect(originalEvent, isNot(same(anotherTransformedEvent)));
expect(anotherTransformedEvent.original, same(originalEvent));
final List<PointerSignalEvent> events = <PointerSignalEvent>[];
resolver.register(transformedEvent, (PointerSignalEvent event) {
events.add(event);
});
// Registering a second transformed event should not throw an assertion.
expect(() {
resolver.register(anotherTransformedEvent, (PointerSignalEvent event) {
// This shouldn't be called because only the first registered callback is
// invoked.
events.add(event);
});
}, returnsNormally);
resolver.resolve(originalEvent);
expect(events.single, same(transformedEvent));
});
}
| flutter/packages/flutter/test/gestures/pointer_signal_resolver_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/pointer_signal_resolver_test.dart",
"repo_id": "flutter",
"token_count": 1150
} | 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.
/// A 50x50 blue square png.
const List<int> kBlueSquarePng = <int>[
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49,
0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x32, 0x08, 0x06,
0x00, 0x00, 0x00, 0x1e, 0x3f, 0x88, 0xb1, 0x00, 0x00, 0x00, 0x48, 0x49, 0x44,
0x41, 0x54, 0x78, 0xda, 0xed, 0xcf, 0x31, 0x0d, 0x00, 0x30, 0x08, 0x00, 0xb0,
0x61, 0x63, 0x2f, 0xfe, 0x2d, 0x61, 0x05, 0x34, 0xf0, 0x92, 0xd6, 0x41, 0x23,
0x7f, 0xf5, 0x3b, 0x20, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x36, 0x06, 0x03, 0x6e, 0x69, 0x47, 0x12, 0x8e, 0xea, 0xaa,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];
const List<int> kTransparentImage = <int>[
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49,
0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06,
0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4B,
0x47, 0x44, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xA0, 0xBD, 0xA7, 0x93, 0x00,
0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0B, 0x13, 0x00, 0x00,
0x0B, 0x13, 0x01, 0x00, 0x9A, 0x9C, 0x18, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49,
0x4D, 0x45, 0x07, 0xE6, 0x03, 0x10, 0x17, 0x07, 0x1D, 0x2E, 0x5E, 0x30, 0x9B,
0x00, 0x00, 0x00, 0x0B, 0x49, 0x44, 0x41, 0x54, 0x08, 0xD7, 0x63, 0x60, 0x00,
0x02, 0x00, 0x00, 0x05, 0x00, 0x01, 0xE2, 0x26, 0x05, 0x9B, 0x00, 0x00, 0x00,
0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
];
/// An animated GIF image with 3 1x1 pixel frames (a red, green, and blue
/// frames). The GIF animates forever, and each frame has a 100ms delay.
const List<int> kAnimatedGif = <int> [
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0xa1, 0x03, 0x00,
0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0x21,
0xff, 0x0b, 0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30,
0x03, 0x01, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x00, 0x0a, 0x00, 0xff, 0x00,
0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x4c,
0x01, 0x00, 0x21, 0xf9, 0x04, 0x00, 0x0a, 0x00, 0xff, 0x00, 0x2c, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x54, 0x01, 0x00, 0x21,
0xf9, 0x04, 0x00, 0x0a, 0x00, 0xff, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b,
];
/// A PNG with 100x100 blue pixels.
//
// Constructed by the following code:
// ```dart
// Future<void> someTest(WidgetTester tester) async {
// Uint8List? bytes;
// await tester.runAsync(() async {
// const int imageWidth = 100;
// const int imageHeight = 100;
// final Uint8List pixels = Uint8List.fromList(List<int>.generate(
// imageWidth * imageHeight * 4,
// (int i) => i % 4 < 2 ? 0x00 : 0xFF, // opaque blue
// ));
// final Completer<void> completer = Completer<void>();
// ui.decodeImageFromPixels(
// pixels, imageWidth, imageHeight, ui.PixelFormat.rgba8888,
// (ui.Image image) async {
// final ByteData? byteData = await image.toByteData(
// format: ui.ImageByteFormat.png);
// bytes = byteData!.buffer.asUint8List();
// completer.complete();
// },
// );
// await completer.future;
// });
// print(bytes);
// }
// ```
const List<int> kBlueRectPng = <int> [
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 100, 0,
0, 0, 100, 8, 6, 0, 0, 0, 112, 226, 149, 84, 0, 0, 0, 4, 115, 66, 73, 84, 8,
8, 8, 8, 124, 8, 100, 136, 0, 0, 1, 0, 73, 68, 65, 84, 120, 156, 237, 209, 65,
13, 0, 32, 16, 192, 176, 3, 255, 158, 225, 141, 2, 246, 104, 21, 44, 217, 154,
57, 103, 200, 216, 191, 3, 120, 25, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 204, 5, 234, 78, 2, 198, 180,
170, 48, 200, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
];
/// A portrait-mode (50x100) PNG with blue pixels.
const List<int> kBluePortraitPng = <int> [
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 50, 0,
0, 0, 100, 8, 6, 0, 0, 0, 196, 232, 99, 91, 0, 0, 0, 4, 115, 66, 73, 84, 8, 8,
8, 8, 124, 8, 100, 136, 0, 0, 0, 140, 73, 68, 65, 84, 120, 156, 237, 207, 1,
13, 192, 48, 12, 192, 176, 126, 252, 57, 247, 36, 46, 45, 186, 108, 4, 201,
51, 179, 59, 63, 112, 110, 7, 124, 197, 72, 141, 145, 26, 35, 53, 70, 106,
140, 212, 24, 169, 49, 82, 99, 164, 198, 72, 141, 145, 26, 35, 53, 70, 106,
140, 212, 24, 169, 49, 82, 99, 164, 198, 72, 141, 145, 26, 35, 53, 70, 106,
140, 212, 24, 169, 49, 82, 99, 164, 198, 72, 141, 145, 26, 35, 53, 70, 106,
140, 212, 24, 169, 49, 82, 99, 164, 198, 72, 141, 145, 26, 35, 53, 70, 106,
140, 212, 24, 169, 49, 82, 99, 164, 198, 72, 141, 145, 26, 35, 53, 70, 106,
140, 212, 24, 169, 49, 82, 99, 164, 198, 72, 205, 11, 105, 8, 2, 198, 99, 140,
153, 87, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
];
/// A landscape-mode (100x50) PNG with blue pixels.
const List<int> kBlueLandscapePng = <int> [
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 100, 0,
0, 0, 50, 8, 6, 0, 0, 0, 170, 53, 126, 190, 0, 0, 0, 4, 115, 66, 73, 84, 8, 8,
8, 8, 124, 8, 100, 136, 0, 0, 0, 143, 73, 68, 65, 84, 120, 156, 237, 209, 65,
13, 0, 32, 16, 192, 176, 3, 255, 158, 225, 141, 2, 246, 104, 21, 44, 217, 154,
57, 103, 200, 216, 191, 3, 120, 25, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 24, 18, 99, 72, 140, 33, 49, 134, 196, 24, 18,
99, 72, 140, 33, 49, 134, 196, 92, 164, 190, 2, 98, 53, 3, 99, 174, 0, 0, 0,
0, 73, 69, 78, 68, 174, 66, 96, 130,
];
| flutter/packages/flutter/test/image_data.dart/0 | {
"file_path": "flutter/packages/flutter/test/image_data.dart",
"repo_id": "flutter",
"token_count": 3839
} | 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.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Large Badge defaults', (WidgetTester tester) async {
late final ThemeData theme;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light(useMaterial3: true),
home: Align(
alignment: Alignment.topLeft,
child: Builder(
builder: (BuildContext context) {
// theme.textTheme is updated when the MaterialApp is built.
theme = Theme.of(context);
return const Badge(
label: Text('0'),
child: Icon(Icons.add),
);
},
),
),
),
);
expect(
tester.renderObject<RenderParagraph>(find.text('0')).text.style,
theme.textTheme.labelSmall!.copyWith(color: theme.colorScheme.onError),
);
// default badge alignment = AlignmentDirection.topEnd
// default offset for LTR = Offset(4, -4)
// default padding = EdgeInsets.symmetric(horizontal: 4)
// default largeSize = 16
// '0'.width = 12
// icon.width = 24
expect(tester.getSize(find.byType(Badge)), const Size(24, 24)); // default Icon size
expect(tester.getTopLeft(find.byType(Badge)), Offset.zero);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(tester.getTopLeft(find.text('0')), const Offset(16, -4));
}
final RenderBox box = tester.renderObject(find.byType(Badge));
final RRect rrect = RRect.fromLTRBR(12, -4, 31.5, 12, const Radius.circular(8));
expect(box, paints..rrect(rrect: rrect, color: theme.colorScheme.error));
});
testWidgets('Large Badge defaults with RTL', (WidgetTester tester) async {
late final ThemeData theme;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light(useMaterial3: true),
home: Directionality(
textDirection: TextDirection.rtl,
child: Align(
alignment: Alignment.topLeft,
child: Builder(
builder: (BuildContext context) {
// theme.textTheme is updated when the MaterialApp is built.
theme = Theme.of(context);
return const Badge(
label: Text('0'),
child: Icon(Icons.add),
);
},
),
),
),
),
);
expect(
tester.renderObject<RenderParagraph>(find.text('0')).text.style,
theme.textTheme.labelSmall!.copyWith(color: theme.colorScheme.onError),
);
expect(tester.getSize(find.byType(Badge)), const Size(24, 24)); // default Icon size
expect(tester.getTopLeft(find.byType(Badge)), Offset.zero);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(tester.getTopLeft(find.text('0')), const Offset(0, -4));
}
final RenderBox box = tester.renderObject(find.byType(Badge));
final RRect rrect = RRect.fromLTRBR(-4, -4, 15.5, 12, const Radius.circular(8));
expect(box, paints..rrect(rrect: rrect, color: theme.colorScheme.error));
});
// Essentially the same as 'Large Badge defaults'
testWidgets('Badge.count', (WidgetTester tester) async {
late final ThemeData theme;
Widget buildFrame(int count) {
return MaterialApp(
theme: ThemeData.light(useMaterial3: true),
home: Align(
alignment: Alignment.topLeft,
child: Builder(
builder: (BuildContext context) {
// theme.textTheme is updated when the MaterialApp is built.
if (count == 0) {
theme = Theme.of(context);
}
return Badge.count(
count: count,
child: const Icon(Icons.add),
);
},
),
),
);
}
await tester.pumpWidget(buildFrame(0));
expect(
tester.renderObject<RenderParagraph>(find.text('0')).text.style,
theme.textTheme.labelSmall!.copyWith(color: theme.colorScheme.onError),
);
// default badge alignment = AlignmentDirectional(12, -4)
// default padding = EdgeInsets.symmetric(horizontal: 4)
// default largeSize = 16
// '0'.width = 12
// icon.width = 24
expect(tester.getSize(find.byType(Badge)), const Size(24, 24)); // default Icon size
expect(tester.getTopLeft(find.byType(Badge)), Offset.zero);
// x = alignment.start + padding.left
// y = alignment.top
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(tester.getTopLeft(find.text('0')), const Offset(16, -4));
}
final RenderBox box = tester.renderObject(find.byType(Badge));
// '0'.width = 12
// L = alignment.start
// T = alignment.top
// R = L + '0'.width + padding.width
// B = T + largeSize, R = largeSize/2
final RRect rrect = RRect.fromLTRBR(12, -4, 31.5, 12, const Radius.circular(8));
expect(box, paints..rrect(rrect: rrect, color: theme.colorScheme.error));
await tester.pumpWidget(buildFrame(1000));
expect(find.text('999+'), findsOneWidget);
});
testWidgets('Small Badge defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData.light(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Align(
alignment: Alignment.topLeft,
child: Badge(
child: Icon(Icons.add),
),
),
),
);
// default badge location is end=0, top=0
// default padding = EdgeInsets.symmetric(horizontal: 4)
// default smallSize = 6
// icon.width = 24
expect(tester.getSize(find.byType(Badge)), const Size(24, 24)); // default Icon size
expect(tester.getTopLeft(find.byType(Badge)), Offset.zero);
final RenderBox box = tester.renderObject(find.byType(Badge));
// L = icon.size.width - smallSize
// T = 0
// R = icon.size.width
// B = smallSize
expect(box, paints..rrect(rrect: RRect.fromLTRBR(18, 0, 24, 6, const Radius.circular(3)), color: theme.colorScheme.error));
});
testWidgets('Small Badge RTL defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData.light(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Directionality(
textDirection: TextDirection.rtl,
child: Align(
alignment: Alignment.topLeft,
child: Badge(
child: Icon(Icons.add),
),
),
),
),
);
// default badge location is end=0, top=0
// default smallSize = 6
// icon.width = 24
expect(tester.getSize(find.byType(Badge)), const Size(24, 24)); // default Icon size
expect(tester.getTopLeft(find.byType(Badge)), Offset.zero);
final RenderBox box = tester.renderObject(find.byType(Badge));
// L = 0
// T = 0
// R = smallSize
// B = smallSize
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 0, 6, 6, const Radius.circular(3)), color: theme.colorScheme.error));
});
testWidgets('Large Badge textStyle and colors', (WidgetTester tester) async {
final ThemeData theme = ThemeData.light(useMaterial3: true);
const Color green = Color(0xff00ff00);
const Color black = Color(0xff000000);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Align(
alignment: Alignment.topLeft,
child: Badge(
textColor: green,
backgroundColor: black,
textStyle: TextStyle(fontSize: 10),
label: Text('0'),
child: Icon(Icons.add),
),
),
),
);
final TextStyle textStyle = tester.renderObject<RenderParagraph>(find.text('0')).text.style!;
expect(textStyle.fontSize, 10);
expect(textStyle.color, green);
expect(tester.renderObject(find.byType(Badge)), paints..rrect(color: black));
});
testWidgets('isLabelVisible', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light(useMaterial3: true),
home: const Align(
alignment: Alignment.topLeft,
child: Badge(
label: Text('0'),
isLabelVisible: false,
child: Icon(Icons.add),
),
),
),
);
expect(find.text('0'), findsNothing);
expect(find.byType(Icon), findsOneWidget);
expect(tester.getSize(find.byType(Badge)), const Size(24, 24)); // default Icon size
expect(tester.getTopLeft(find.byType(Badge)), Offset.zero);
final RenderBox box = tester.renderObject(find.byType(Badge));
expect(box, isNot(paints..rrect()));
});
testWidgets('Large Badge alignment', (WidgetTester tester) async {
const Radius badgeRadius = Radius.circular(8);
Widget buildFrame(Alignment alignment, [Offset offset = Offset.zero]) {
return MaterialApp(
theme: ThemeData.light(useMaterial3: true),
home: Align(
alignment: Alignment.topLeft,
child: Badge(
// Default largeSize = 16, badge with label is "large".
label: Container(width: 8, height: 8, color: Colors.blue),
alignment: alignment,
offset: offset,
child: Container(
color: const Color(0xFF00FF00),
width: 200,
height: 200,
),
),
),
);
}
await tester.pumpWidget(buildFrame(Alignment.topLeft));
final RenderBox box = tester.renderObject(find.byType(Badge));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 0, 16, 16, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.topCenter));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(100 - 8, 0, 100 + 8, 16, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.topRight));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 16, 0, 200, 16, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.centerLeft));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 100 - 8, 16, 100 + 8, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.centerRight));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 16, 100 - 8, 200, 100 + 8, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomLeft));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 200 - 16, 16, 200, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomCenter));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(100 - 8, 200 - 16, 100 + 8, 200, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomRight));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 16, 200 - 16, 200, 200, badgeRadius)));
const Offset offset = Offset(5, 10);
await tester.pumpWidget(buildFrame(Alignment.topLeft, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 0, 16, 16, badgeRadius).shift(offset)));
await tester.pumpWidget(buildFrame(Alignment.topCenter, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(100 - 8, 0, 100 + 8, 16, badgeRadius).shift(offset)));
await tester.pumpWidget(buildFrame(Alignment.topRight, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 16, 0, 200, 16, badgeRadius).shift(offset)));
await tester.pumpWidget(buildFrame(Alignment.centerLeft, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 100 - 8, 16, 100 + 8, badgeRadius).shift(offset)));
await tester.pumpWidget(buildFrame(Alignment.centerRight, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 16, 100 - 8, 200, 100 + 8, badgeRadius).shift(offset)));
await tester.pumpWidget(buildFrame(Alignment.bottomLeft, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 200 - 16, 16, 200, badgeRadius).shift(offset)));
await tester.pumpWidget(buildFrame(Alignment.bottomCenter, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(100 - 8, 200 - 16, 100 + 8, 200, badgeRadius).shift(offset)));
await tester.pumpWidget(buildFrame(Alignment.bottomRight, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 16, 200 - 16, 200, 200, badgeRadius).shift(offset)));
});
testWidgets('Small Badge alignment', (WidgetTester tester) async {
const Radius badgeRadius = Radius.circular(3);
Widget buildFrame(Alignment alignment, [Offset offset = Offset.zero]) {
return MaterialApp(
theme: ThemeData.light(useMaterial3: true),
home: Align(
alignment: Alignment.topLeft,
child: Badge(
// Default smallSize = 6, badge without label is "small".
alignment: alignment,
offset: offset, // Not used for smallSize badges.
child: Container(
color: const Color(0xFF00FF00),
width: 200,
height: 200,
),
),
),
);
}
await tester.pumpWidget(buildFrame(Alignment.topLeft));
final RenderBox box = tester.renderObject(find.byType(Badge));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 0, 6, 6, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.topCenter));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(100 - 3, 0, 100 + 3, 6, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.topRight));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 6, 0, 200, 6, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.centerLeft));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 100 - 3, 6, 100 + 3, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.centerRight));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 6, 100 - 3, 200, 100 + 3, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomLeft));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 200 - 6, 6, 200, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomCenter));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(100 - 3, 200 - 6, 100 + 3, 200, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomRight));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 6, 200 - 6, 200, 200, badgeRadius)));
const Offset offset = Offset(5, 10); // Not used for smallSize Badges.
await tester.pumpWidget(buildFrame(Alignment.topLeft, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 0, 6, 6, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.topCenter, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(100 - 3, 0, 100 + 3, 6, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.topRight, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 6, 0, 200, 6, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.centerLeft, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 100 - 3, 6, 100 + 3, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.centerRight, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 6, 100 - 3, 200, 100 + 3, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomLeft, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(0, 200 - 6, 6, 200, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomCenter, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(100 - 3, 200 - 6, 100 + 3, 200, badgeRadius)));
await tester.pumpWidget(buildFrame(Alignment.bottomRight, offset));
expect(box, paints..rrect(rrect: RRect.fromLTRBR(200 - 6, 200 - 6, 200, 200, badgeRadius)));
});
}
| flutter/packages/flutter/test/material/badge_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/badge_test.dart",
"repo_id": "flutter",
"token_count": 6659
} | 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.
// 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_test/flutter_test.dart';
void main() {
test('CardTheme copyWith, ==, hashCode basics', () {
expect(const CardTheme(), const CardTheme().copyWith());
expect(const CardTheme().hashCode, const CardTheme().copyWith().hashCode);
});
test('CardTheme lerp special cases', () {
expect(CardTheme.lerp(null, null, 0), const CardTheme());
const CardTheme theme = CardTheme();
expect(identical(CardTheme.lerp(theme, theme, 0.5), theme), true);
});
testWidgets('Material3 - Passing no CardTheme returns defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(MaterialApp(
theme: theme,
home: const Scaffold(
body: Card(),
),
));
final Container container = _getCardContainer(tester);
final Material material = _getCardMaterial(tester);
expect(material.clipBehavior, Clip.none);
expect(material.color, theme.colorScheme.surfaceContainerLow);
expect(material.shadowColor, theme.colorScheme.shadow);
expect(material.surfaceTintColor, Colors.transparent); // Default primary color
expect(material.elevation, 1.0);
expect(container.margin, const EdgeInsets.all(4.0));
expect(material.shape, const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
));
});
testWidgets('Card uses values from CardTheme', (WidgetTester tester) async {
final CardTheme cardTheme = _cardTheme();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(cardTheme: cardTheme),
home: const Scaffold(
body: Card(),
),
));
final Container container = _getCardContainer(tester);
final Material material = _getCardMaterial(tester);
expect(material.clipBehavior, cardTheme.clipBehavior);
expect(material.color, cardTheme.color);
expect(material.shadowColor, cardTheme.shadowColor);
expect(material.surfaceTintColor, cardTheme.surfaceTintColor);
expect(material.elevation, cardTheme.elevation);
expect(container.margin, cardTheme.margin);
expect(material.shape, cardTheme.shape);
});
testWidgets('Card widget properties take priority over theme', (WidgetTester tester) async {
const Clip clip = Clip.hardEdge;
const Color color = Colors.orange;
const Color shadowColor = Colors.pink;
const double elevation = 7.0;
const EdgeInsets margin = EdgeInsets.all(3.0);
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(9.0)),
);
await tester.pumpWidget(MaterialApp(
theme: _themeData().copyWith(cardTheme: _cardTheme()),
home: const Scaffold(
body: Card(
clipBehavior: clip,
color: color,
shadowColor: shadowColor,
elevation: elevation,
margin: margin,
shape: shape,
),
),
));
final Container container = _getCardContainer(tester);
final Material material = _getCardMaterial(tester);
expect(material.clipBehavior, clip);
expect(material.color, color);
expect(material.shadowColor, shadowColor);
expect(material.elevation, elevation);
expect(container.margin, margin);
expect(material.shape, shape);
});
testWidgets('CardTheme properties take priority over ThemeData properties', (WidgetTester tester) async {
final CardTheme cardTheme = _cardTheme();
final ThemeData themeData = _themeData().copyWith(cardTheme: cardTheme);
await tester.pumpWidget(MaterialApp(
theme: themeData,
home: const Scaffold(
body: Card(),
),
));
final Material material = _getCardMaterial(tester);
expect(material.color, cardTheme.color);
});
testWidgets('Material3 - ThemeData properties are used when no CardTheme is set', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
await tester.pumpWidget(MaterialApp(
theme: themeData,
home: const Scaffold(
body: Card(),
),
));
final Material material = _getCardMaterial(tester);
expect(material.color, themeData.colorScheme.surfaceContainerLow);
});
testWidgets('Material3 - CardTheme customizes shape', (WidgetTester tester) async {
const CardTheme cardTheme = CardTheme(
color: Colors.white,
shape: BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(7))),
elevation: 1.0,
);
final Key painterKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(cardTheme: cardTheme, useMaterial3: true),
home: Scaffold(
body: RepaintBoundary(
key: painterKey,
child: Center(
child: Card(
child: SizedBox.fromSize(size: const Size(200, 300)),
),
),
),
),
));
await expectLater(
find.byKey(painterKey),
matchesGoldenFile('card_theme.custom_shape.png'),
);
});
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('Material2 - ThemeData properties are used when no CardTheme is set', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: false);
await tester.pumpWidget(MaterialApp(
theme: themeData,
home: const Scaffold(
body: Card(),
),
));
final Material material = _getCardMaterial(tester);
expect(material.color, themeData.cardColor);
});
testWidgets('Material2 - Passing no CardTheme returns defaults', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: const Scaffold(
body: Card(),
),
));
final Container container = _getCardContainer(tester);
final Material material = _getCardMaterial(tester);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.white);
expect(material.shadowColor, Colors.black);
expect(material.surfaceTintColor, null);
expect(material.elevation, 1.0);
expect(container.margin, const EdgeInsets.all(4.0));
expect(material.shape, const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
));
});
testWidgets('Material2 - CardTheme customizes shape', (WidgetTester tester) async {
const CardTheme cardTheme = CardTheme(
color: Colors.white,
shape: BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(7))),
elevation: 1.0,
);
final Key painterKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(cardTheme: cardTheme, useMaterial3: false),
home: Scaffold(
body: RepaintBoundary(
key: painterKey,
child: Center(
child: Card(
child: SizedBox.fromSize(size: const Size(200, 300)),
),
),
),
),
));
await expectLater(
find.byKey(painterKey),
matchesGoldenFile('card_theme.custom_shape_m2.png'),
);
});
});
}
CardTheme _cardTheme() {
return const CardTheme(
clipBehavior: Clip.antiAlias,
color: Colors.green,
shadowColor: Colors.red,
surfaceTintColor: Colors.purple,
elevation: 6.0,
margin: EdgeInsets.all(7.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
);
}
ThemeData _themeData() {
return ThemeData(
cardColor: Colors.pink,
);
}
Material _getCardMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(
of: find.byType(Card),
matching: find.byType(Material),
),
);
}
Container _getCardContainer(WidgetTester tester) {
return tester.widget<Container>(
find.descendant(
of: find.byType(Card),
matching: find.byType(Container),
),
);
}
| flutter/packages/flutter/test/material/card_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/card_theme_test.dart",
"repo_id": "flutter",
"token_count": 3176
} | 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('debugCheckHasMaterial control test', (WidgetTester tester) async {
await tester.pumpWidget(const Center(child: Chip(label: Text('label'))));
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(
'To introduce a Material widget, you can either directly include\n'
'one, or use a widget that contains Material itself, such as a\n'
'Card, Dialog, Drawer, or Scaffold.\n',
),
);
expect(error.diagnostics[3], isA<DiagnosticsProperty<Element>>());
expect(error.diagnostics[4], isA<DiagnosticsBlock>());
expect(
error.toStringDeep(), startsWith(
'FlutterError\n'
' No Material widget found.\n'
' Chip widgets require a Material widget ancestor within the\n'
' closest LookupBoundary.\n'
' In Material Design, most widgets are conceptually "printed" on a\n'
" sheet of material. In Flutter's material library, that material\n"
' is represented by the Material widget. It is the Material widget\n'
' that renders ink splashes, for instance. Because of this, many\n'
' material library widgets require that there be a Material widget\n'
' in the tree above them.\n'
' To introduce a Material widget, you can either directly include\n'
' one, or use a widget that contains Material itself, such as a\n'
' Card, Dialog, Drawer, or Scaffold.\n'
' The specific widget that could not find a Material ancestor was:\n'
' Chip\n'
' The ancestors of this widget were:\n'
' Center\n'
// End of ancestor chain omitted, not relevant for test.
));
});
testWidgets('debugCheckHasMaterialLocalizations control test', (WidgetTester tester) async {
await tester.pumpWidget(const Center(child: BackButton()));
final dynamic exception = tester.takeException();
expect(exception, isFlutterError);
final FlutterError error = exception as FlutterError;
expect(error.diagnostics.length, 6);
expect(error.diagnostics[3].level, DiagnosticLevel.hint);
expect(
error.diagnostics[3].toStringDeep(),
equalsIgnoringHashCodes(
'To introduce a MaterialLocalizations, either use a MaterialApp at\n'
'the root of your application to include them automatically, or\n'
'add a Localization widget with a MaterialLocalizations delegate.\n',
),
);
expect(error.diagnostics[4], isA<DiagnosticsProperty<Element>>());
expect(error.diagnostics[5], isA<DiagnosticsBlock>());
expect(
error.toStringDeep(), startsWith(
'FlutterError\n'
' No MaterialLocalizations found.\n'
' BackButton widgets require MaterialLocalizations to be provided\n'
' by a Localizations widget ancestor.\n'
' The material library uses Localizations to generate messages,\n'
' labels, and abbreviations.\n'
' To introduce a MaterialLocalizations, either use a MaterialApp at\n'
' the root of your application to include them automatically, or\n'
' add a Localization widget with a MaterialLocalizations delegate.\n'
' The specific widget that could not find a MaterialLocalizations\n'
' ancestor was:\n'
' BackButton\n'
' The ancestors of this widget were:\n'
' Center\n'
// End of ancestor chain omitted, not relevant for test.
));
});
testWidgets('debugCheckHasScaffold control test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
},
),
),
home: Builder(
builder: (BuildContext context) {
showBottomSheet(
context: context,
builder: (BuildContext context) => 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], isA<DiagnosticsProperty<Element>>());
expect(error.diagnostics[3], isA<DiagnosticsBlock>());
expect(error.diagnostics[4].level, DiagnosticLevel.hint);
expect(
error.diagnostics[4].toStringDeep(),
equalsIgnoringHashCodes(
'Typically, the Scaffold widget is introduced by the MaterialApp\n'
'or WidgetsApp widget at the top of your application widget tree.\n',
),
);
expect(error.toStringDeep(), startsWith(
'FlutterError\n'
' No Scaffold widget found.\n'
' Builder widgets require a Scaffold widget ancestor.\n'
' The specific widget that could not find a Scaffold ancestor was:\n'
' Builder\n'
' The ancestors of this widget were:\n'
' Semantics\n'
' Builder\n'
));
expect(error.toStringDeep(), endsWith(
' [root]\n'
' Typically, the Scaffold widget is introduced by the MaterialApp\n'
' or WidgetsApp widget at the top of your application widget tree.\n'
));
});
testWidgets('debugCheckHasScaffoldMessenger control test', (WidgetTester tester) async {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
final SnackBar snackBar = SnackBar(
content: const Text('Snack'),
action: SnackBarAction(label: 'Test', onPressed: () {}),
);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ScaffoldMessenger(
key: scaffoldMessengerKey,
child: Builder(
builder: (BuildContext context) {
return Scaffold(
key: scaffoldKey,
body: Container(),
);
},
),
),
));
final List<dynamic> exceptions = <dynamic>[];
final FlutterExceptionHandler? oldHandler = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails details) {
exceptions.add(details.exception);
};
// ScaffoldMessenger shows SnackBar.
scaffoldMessengerKey.currentState!.showSnackBar(snackBar);
await tester.pumpAndSettle();
// Pump widget to rebuild without ScaffoldMessenger
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Scaffold(
key: scaffoldKey,
body: Container(),
),
));
// Tap SnackBarAction to dismiss.
// The SnackBarAction should assert we still have an ancestor
// ScaffoldMessenger in order to dismiss the SnackBar from the
// Scaffold.
await tester.tap(find.text('Test'));
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'
' SnackBarAction widgets require a ScaffoldMessenger widget\n'
' ancestor.\n'
' The specific widget that could not find a ScaffoldMessenger\n'
' ancestor was:\n'
' SnackBarAction\n'
' The ancestors of this widget were:\n'
' TextButtonTheme\n'
' Padding\n'
' Row\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'
));
});
}
| flutter/packages/flutter/test/material/debug_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/debug_test.dart",
"repo_id": "flutter",
"token_count": 3397
} | 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('applySurfaceTint with null surface tint returns given color', () {
final Color result = ElevationOverlay.applySurfaceTint(const Color(0xff888888), null, 42.0);
expect(result, equals(const Color(0xFF888888)));
});
test('applySurfaceTint with exact elevation levels uses the right opacity overlay', () {
const Color baseColor = Color(0xff888888);
const Color surfaceTintColor = Color(0xff44CCFF);
Color overlayWithOpacity(double opacity) {
return Color.alphaBlend(surfaceTintColor.withOpacity(opacity), baseColor);
}
// Based on values from the spec:
// https://m3.material.io/styles/color/the-color-system/color-roles
// Elevation level 0 (0.0) - should have opacity 0.0.
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 0.0), equals(overlayWithOpacity(0.0)));
// Elevation level 1 (1.0) - should have opacity 0.05.
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 1.0), equals(overlayWithOpacity(0.05)));
// Elevation level 2 (3.0) - should have opacity 0.08.
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 3.0), equals(overlayWithOpacity(0.08)));
// Elevation level 3 (6.0) - should have opacity 0.11`.
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 6.0), equals(overlayWithOpacity(0.11)));
// Elevation level 4 (8.0) - should have opacity 0.12.
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 8.0), equals(overlayWithOpacity(0.12)));
// Elevation level 5 (12.0) - should have opacity 0.14.
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 12.0), equals(overlayWithOpacity(0.14)));
});
test('applySurfaceTint with elevation lower than level 0 should have no overlay', () {
const Color baseColor = Color(0xff888888);
const Color surfaceTintColor = Color(0xff44CCFF);
Color overlayWithOpacity(double opacity) {
return Color.alphaBlend(surfaceTintColor.withOpacity(opacity), baseColor);
}
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, -42.0), equals(overlayWithOpacity(0.0)));
});
test('applySurfaceTint with elevation higher than level 5 should have no level 5 overlay', () {
const Color baseColor = Color(0xff888888);
const Color surfaceTintColor = Color(0xff44CCFF);
Color overlayWithOpacity(double opacity) {
return Color.alphaBlend(surfaceTintColor.withOpacity(opacity), baseColor);
}
// Elevation level 5 (12.0) - should have opacity 0.14.
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 42.0), equals(overlayWithOpacity(0.14)));
});
test('applySurfaceTint with elevation between two levels should interpolate the opacity', () {
const Color baseColor = Color(0xff888888);
const Color surfaceTintColor = Color(0xff44CCFF);
Color overlayWithOpacity(double opacity) {
return Color.alphaBlend(surfaceTintColor.withOpacity(opacity), baseColor);
}
// Elevation between level 4 (8.0) and level 5 (12.0) should be interpolated
// between the opacities 0.12 and 0.14.
// One third (0.3): (elevation 9.2) -> (opacity 0.126)
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 9.2), equals(overlayWithOpacity(0.126)));
// Half way (0.5): (elevation 10.0) -> (opacity 0.13)
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 10.0), equals(overlayWithOpacity(0.13)));
// Two thirds (0.6): (elevation 10.4) -> (opacity 0.132)
expect(ElevationOverlay.applySurfaceTint(baseColor, surfaceTintColor, 10.4), equals(overlayWithOpacity(0.132)));
});
}
| flutter/packages/flutter/test/material/elevation_overlay_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/elevation_overlay_test.dart",
"repo_id": "flutter",
"token_count": 1390
} | 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.
// 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_test/flutter_test.dart';
void main() {
testWidgets('Flutter Logo golden test', (WidgetTester tester) async {
final Key logo = UniqueKey();
await tester.pumpWidget(FlutterLogo(key: logo));
await expectLater(
find.byKey(logo),
matchesGoldenFile('flutter_logo.png'),
);
});
}
| flutter/packages/flutter/test/material/flutter_logo_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/flutter_logo_test.dart",
"repo_id": "flutter",
"token_count": 226
} | 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.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final MagnifierController magnifierController = MagnifierController();
const Rect reasonableTextField = Rect.fromLTRB(50, 100, 200, 100);
final Offset basicOffset = Offset(Magnifier.kDefaultMagnifierSize.width / 2,
Magnifier.kStandardVerticalFocalPointShift + Magnifier.kDefaultMagnifierSize.height);
Offset getMagnifierPosition(WidgetTester tester, [bool animated = false]) {
if (animated) {
final AnimatedPositioned animatedPositioned =
tester.firstWidget(find.byType(AnimatedPositioned));
return Offset(animatedPositioned.left ?? 0, animatedPositioned.top ?? 0);
} else {
final Positioned positioned = tester.firstWidget(find.byType(Positioned));
return Offset(positioned.left ?? 0, positioned.top ?? 0);
}
}
Future<void> showMagnifier(
BuildContext context,
WidgetTester tester,
ValueNotifier<MagnifierInfo> magnifierInfo,
) async {
final Future<void> magnifierShown = magnifierController.show(
context: context,
builder: (_) => TextMagnifier(
magnifierInfo: magnifierInfo,
));
WidgetsBinding.instance.scheduleFrame();
await tester.pumpAndSettle();
// Verify that the magnifier is shown.
await magnifierShown;
}
tearDown(() {
magnifierController.removeFromOverlay();
magnifierController.animationController = null;
});
group('adaptiveMagnifierControllerBuilder', () {
testWidgets('should return a TextEditingMagnifier on Android',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context = tester.firstElement(find.byType(Placeholder));
final ValueNotifier<MagnifierInfo> magnifierPositioner = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty);
addTearDown(magnifierPositioner.dispose);
final Widget? builtWidget = TextMagnifier.adaptiveMagnifierConfiguration.magnifierBuilder(
context,
MagnifierController(),
magnifierPositioner,
);
expect(builtWidget, isA<TextMagnifier>());
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('should return a CupertinoMagnifier on iOS',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context = tester.firstElement(find.byType(Placeholder));
final ValueNotifier<MagnifierInfo> magnifierPositioner = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty);
addTearDown(magnifierPositioner.dispose);
final Widget? builtWidget = TextMagnifier.adaptiveMagnifierConfiguration.magnifierBuilder(
context,
MagnifierController(),
magnifierPositioner,
);
expect(builtWidget, isA<CupertinoTextMagnifier>());
}, variant: TargetPlatformVariant.only(TargetPlatform.iOS));
testWidgets('should return null on all platforms not Android, iOS',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context = tester.firstElement(find.byType(Placeholder));
final ValueNotifier<MagnifierInfo> magnifierPositioner = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty);
addTearDown(magnifierPositioner.dispose);
final Widget? builtWidget = TextMagnifier.adaptiveMagnifierConfiguration.magnifierBuilder(
context,
MagnifierController(),
magnifierPositioner,
);
expect(builtWidget, isNull);
},
variant: TargetPlatformVariant.all(
excluding: <TargetPlatform>{
TargetPlatform.iOS,
TargetPlatform.android
}),
);
});
group('magnifier', () {
group('position', () {
testWidgets(
'should be at gesture position if does not violate any positioning rules',
(WidgetTester tester) async {
final Key textField = UniqueKey();
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
await tester.pumpWidget(
ColoredBox(
color: const Color.fromARGB(255, 0, 255, 179),
child: MaterialApp(
home: Center(
child: Container(
key: textField,
width: 10,
height: 10,
color: Colors.red,
child: const Placeholder(),
),
),
),
),
);
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
// Magnifier should be positioned directly over the red square.
final RenderBox tapPointRenderBox =
tester.firstRenderObject(find.byKey(textField)) as RenderBox;
final Rect fakeTextFieldRect =
tapPointRenderBox.localToGlobal(Offset.zero) &
tapPointRenderBox.size;
final ValueNotifier<MagnifierInfo> magnifierInfo =
ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: fakeTextFieldRect,
fieldBounds: fakeTextFieldRect,
caretRect: fakeTextFieldRect,
// The tap position is dragBelow units below the text field.
globalGesturePosition: fakeTextFieldRect.center,
));
addTearDown(magnifierInfo.dispose);
await showMagnifier(context, tester, magnifierInfo);
// Should show two red squares; original, and one in the magnifier,
// directly ontop of one another.
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('magnifier.position.default.png'),
);
});
testWidgets(
'should never move outside the right bounds of the editing line',
(WidgetTester tester) async {
const double gestureOutsideLine = 100;
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
late ValueNotifier<MagnifierInfo> magnifierPositioner;
addTearDown(() => magnifierPositioner.dispose());
await showMagnifier(
context,
tester,
magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: reasonableTextField,
// Inflate these two to make sure we're bounding on the
// current line boundaries, not anything else.
fieldBounds: reasonableTextField.inflate(gestureOutsideLine),
caretRect: reasonableTextField.inflate(gestureOutsideLine),
// The tap position is far out of the right side of the app.
globalGesturePosition: Offset(reasonableTextField.right + gestureOutsideLine, 0),
),
),
);
// Should be less than the right edge, since we have padding.
expect(getMagnifierPosition(tester).dx,
lessThanOrEqualTo(reasonableTextField.right));
});
testWidgets(
'should never move outside the left bounds of the editing line',
(WidgetTester tester) async {
const double gestureOutsideLine = 100;
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
late ValueNotifier<MagnifierInfo> magnifierPositioner;
addTearDown(() => magnifierPositioner.dispose());
await showMagnifier(
context,
tester,
magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: reasonableTextField,
// Inflate these two to make sure we're bounding on the
// current line boundaries, not anything else.
fieldBounds: reasonableTextField.inflate(gestureOutsideLine),
caretRect: reasonableTextField.inflate(gestureOutsideLine),
// The tap position is far out of the left side of the app.
globalGesturePosition: Offset(reasonableTextField.left - gestureOutsideLine, 0),
),
),
);
expect(getMagnifierPosition(tester).dx + basicOffset.dx,
greaterThanOrEqualTo(reasonableTextField.left));
});
testWidgets('should position vertically at the center of the line', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
late ValueNotifier<MagnifierInfo> magnifierPositioner;
addTearDown(() => magnifierPositioner.dispose());
await showMagnifier(
context,
tester,
magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: reasonableTextField,
fieldBounds: reasonableTextField,
caretRect: reasonableTextField,
globalGesturePosition: reasonableTextField.center,
)));
expect(getMagnifierPosition(tester).dy,
reasonableTextField.center.dy - basicOffset.dy);
});
testWidgets('should reposition vertically if mashed against the ceiling',
(WidgetTester tester) async {
final Rect topOfScreenTextFieldRect =
Rect.fromPoints(Offset.zero, const Offset(200, 0));
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
late ValueNotifier<MagnifierInfo> magnifierPositioner;
addTearDown(() => magnifierPositioner.dispose());
await showMagnifier(
context,
tester,
magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: topOfScreenTextFieldRect,
fieldBounds: topOfScreenTextFieldRect,
caretRect: topOfScreenTextFieldRect,
globalGesturePosition: topOfScreenTextFieldRect.topCenter,
),
),
);
expect(getMagnifierPosition(tester).dy, greaterThanOrEqualTo(0));
});
});
group('focal point', () {
Offset getMagnifierAdditionalFocalPoint(WidgetTester tester) {
final Magnifier magnifier = tester.firstWidget(find.byType(Magnifier));
return magnifier.additionalFocalPointOffset;
}
testWidgets(
'should shift focal point so that the lens sees nothing out of bounds',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
late ValueNotifier<MagnifierInfo> magnifierPositioner;
addTearDown(() => magnifierPositioner.dispose());
await showMagnifier(
context,
tester,
magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: reasonableTextField,
fieldBounds: reasonableTextField,
caretRect: reasonableTextField,
// Gesture on the far right of the magnifier.
globalGesturePosition: reasonableTextField.topLeft,
),
),
);
expect(getMagnifierAdditionalFocalPoint(tester).dx,
lessThan(reasonableTextField.left));
});
testWidgets(
'focal point should shift if mashed against the top to always point to text',
(WidgetTester tester) async {
final Rect topOfScreenTextFieldRect =
Rect.fromPoints(Offset.zero, const Offset(200, 0));
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
late ValueNotifier<MagnifierInfo> magnifierPositioner;
addTearDown(() => magnifierPositioner.dispose());
await showMagnifier(
context,
tester,
magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: topOfScreenTextFieldRect,
fieldBounds: topOfScreenTextFieldRect,
caretRect: topOfScreenTextFieldRect,
globalGesturePosition: topOfScreenTextFieldRect.topCenter,
),
),
);
expect(getMagnifierAdditionalFocalPoint(tester).dy, lessThan(0));
});
});
group('animation state', () {
bool getIsAnimated(WidgetTester tester) {
final AnimatedPositioned animatedPositioned =
tester.firstWidget(find.byType(AnimatedPositioned));
return animatedPositioned.duration.compareTo(Duration.zero) != 0;
}
testWidgets('should not be animated on the initial state',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
late ValueNotifier<MagnifierInfo> magnifierInfo;
addTearDown(() => magnifierInfo.dispose());
await showMagnifier(
context,
tester,
magnifierInfo = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: reasonableTextField,
fieldBounds: reasonableTextField,
caretRect: reasonableTextField,
globalGesturePosition: reasonableTextField.center,
),
),
);
expect(getIsAnimated(tester), false);
});
testWidgets('should not be animated on horizontal shifts',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
final ValueNotifier<MagnifierInfo> magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: reasonableTextField,
fieldBounds: reasonableTextField,
caretRect: reasonableTextField,
globalGesturePosition: reasonableTextField.center,
),
);
addTearDown(magnifierPositioner.dispose);
await showMagnifier(context, tester, magnifierPositioner);
// New position has a horizontal shift.
magnifierPositioner.value = MagnifierInfo(
currentLineBoundaries: reasonableTextField,
fieldBounds: reasonableTextField,
caretRect: reasonableTextField,
globalGesturePosition:
reasonableTextField.center + const Offset(200, 0),
);
await tester.pumpAndSettle();
expect(getIsAnimated(tester), false);
});
testWidgets('should be animated on vertical shifts',
(WidgetTester tester) async {
const Offset verticalShift = Offset(0, 200);
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
final ValueNotifier<MagnifierInfo> magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: reasonableTextField,
fieldBounds: reasonableTextField,
caretRect: reasonableTextField,
globalGesturePosition: reasonableTextField.center,
),
);
addTearDown(magnifierPositioner.dispose);
await showMagnifier(context, tester, magnifierPositioner);
// New position has a vertical shift.
magnifierPositioner.value = MagnifierInfo(
currentLineBoundaries: reasonableTextField.shift(verticalShift),
fieldBounds: Rect.fromPoints(reasonableTextField.topLeft,
reasonableTextField.bottomRight + verticalShift),
caretRect: reasonableTextField.shift(verticalShift),
globalGesturePosition: reasonableTextField.center + verticalShift,
);
await tester.pump();
expect(getIsAnimated(tester), true);
});
testWidgets('should stop being animated when timer is up',
(WidgetTester tester) async {
const Offset verticalShift = Offset(0, 200);
await tester.pumpWidget(const MaterialApp(
home: Placeholder(),
));
final BuildContext context =
tester.firstElement(find.byType(Placeholder));
final ValueNotifier<MagnifierInfo> magnifierPositioner = ValueNotifier<MagnifierInfo>(
MagnifierInfo(
currentLineBoundaries: reasonableTextField,
fieldBounds: reasonableTextField,
caretRect: reasonableTextField,
globalGesturePosition: reasonableTextField.center,
),
);
addTearDown(magnifierPositioner.dispose);
await showMagnifier(context, tester, magnifierPositioner);
// New position has a vertical shift.
magnifierPositioner.value = MagnifierInfo(
currentLineBoundaries: reasonableTextField.shift(verticalShift),
fieldBounds: Rect.fromPoints(reasonableTextField.topLeft,
reasonableTextField.bottomRight + verticalShift),
caretRect: reasonableTextField.shift(verticalShift),
globalGesturePosition: reasonableTextField.center + verticalShift,
);
await tester.pump();
expect(getIsAnimated(tester), true);
await tester.pump(TextMagnifier.jumpBetweenLinesAnimationDuration +
const Duration(seconds: 2));
expect(getIsAnimated(tester), false);
});
});
});
}
| flutter/packages/flutter/test/material/magnifier_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/magnifier_test.dart",
"repo_id": "flutter",
"token_count": 7619
} | 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:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
testWidgets('Custom selected and unselected textStyles are honored', (WidgetTester tester) async {
const TextStyle selectedTextStyle = TextStyle(fontWeight: FontWeight.w300, fontSize: 17.0);
const TextStyle unselectedTextStyle = TextStyle(fontWeight: FontWeight.w800, fontSize: 11.0);
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
selectedLabelTextStyle: selectedTextStyle,
unselectedLabelTextStyle: unselectedTextStyle,
),
);
final TextStyle actualSelectedTextStyle = tester.renderObject<RenderParagraph>(find.text('Abc')).text.style!;
final TextStyle actualUnselectedTextStyle = tester.renderObject<RenderParagraph>(find.text('Def')).text.style!;
expect(actualSelectedTextStyle.fontSize, equals(selectedTextStyle.fontSize));
expect(actualSelectedTextStyle.fontWeight, equals(selectedTextStyle.fontWeight));
expect(actualUnselectedTextStyle.fontSize, equals(actualUnselectedTextStyle.fontSize));
expect(actualUnselectedTextStyle.fontWeight, equals(actualUnselectedTextStyle.fontWeight));
});
testWidgets('Custom selected and unselected iconThemes are honored', (WidgetTester tester) async {
const IconThemeData selectedIconTheme = IconThemeData(size: 36, color: Color(0x00000001));
const IconThemeData unselectedIconTheme = IconThemeData(size: 18, color: Color(0x00000002));
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
),
);
final TextStyle actualSelectedIconTheme = _iconStyle(tester, Icons.favorite);
final TextStyle actualUnselectedIconTheme = _iconStyle(tester, Icons.bookmark_border);
expect(actualSelectedIconTheme.color, equals(selectedIconTheme.color));
expect(actualSelectedIconTheme.fontSize, equals(selectedIconTheme.size));
expect(actualUnselectedIconTheme.color, equals(unselectedIconTheme.color));
expect(actualUnselectedIconTheme.fontSize, equals(unselectedIconTheme.size));
});
testWidgets('No selected destination when selectedIndex is null', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: null,
destinations: _destinations(),
),
);
final Iterable<Semantics> semantics = tester.widgetList<Semantics>(find.byType(Semantics));
expect(semantics.where((Semantics s) => s.properties.selected ?? false), isEmpty);
});
testWidgets('backgroundColor can be changed', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
expect(_railMaterial(tester).color, equals(const Color(0xfffef7ff))); // default surface color in M3 colorScheme
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
backgroundColor: Colors.green,
),
);
expect(_railMaterial(tester).color, equals(Colors.green));
});
testWidgets('elevation can be changed', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
expect(_railMaterial(tester).elevation, equals(0));
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
elevation: 7,
),
);
expect(_railMaterial(tester).elevation, equals(7));
});
testWidgets('Renders at the correct default width - [labelType]=none (default)', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 80.0);
});
testWidgets('Renders at the correct default width - [labelType]=selected', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
labelType: NavigationRailLabelType.selected,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 80.0);
});
testWidgets('Renders at the correct default width - [labelType]=all', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
labelType: NavigationRailLabelType.all,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 80.0);
});
testWidgets('Renders wider for a destination with a long label - [labelType]=all', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
labelType: NavigationRailLabelType.all,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Longer Label'),
),
],
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
// Total padding is 16 (8 on each side).
expect(renderBox.size.width, _labelRenderBox(tester, 'Longer Label').size.width + 16.0);
});
testWidgets('Renders only icons - [labelType]=none (default)', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
expect(find.byIcon(Icons.favorite), findsOneWidget);
expect(find.byIcon(Icons.bookmark_border), findsOneWidget);
expect(find.byIcon(Icons.star_border), findsOneWidget);
expect(find.byIcon(Icons.hotel), findsOneWidget);
// When there are no labels, a 0 opacity label is still shown for semantics.
expect(_labelOpacity(tester, 'Abc'), 0);
expect(_labelOpacity(tester, 'Def'), 0);
expect(_labelOpacity(tester, 'Ghi'), 0);
expect(_labelOpacity(tester, 'Jkl'), 0);
});
testWidgets('Renders icons and labels - [labelType]=all', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
expect(find.byIcon(Icons.favorite), findsOneWidget);
expect(find.byIcon(Icons.bookmark_border), findsOneWidget);
expect(find.byIcon(Icons.star_border), findsOneWidget);
expect(find.byIcon(Icons.hotel), findsOneWidget);
expect(find.text('Abc'), findsOneWidget);
expect(find.text('Def'), findsOneWidget);
expect(find.text('Ghi'), findsOneWidget);
expect(find.text('Jkl'), findsOneWidget);
// When displaying all labels, there is no opacity.
expect(_opacityAboveLabel('Abc'), findsNothing);
expect(_opacityAboveLabel('Def'), findsNothing);
expect(_opacityAboveLabel('Ghi'), findsNothing);
expect(_opacityAboveLabel('Jkl'), findsNothing);
});
testWidgets('Renders icons and selected label - [labelType]=selected', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.selected,
),
);
expect(find.byIcon(Icons.favorite), findsOneWidget);
expect(find.byIcon(Icons.bookmark_border), findsOneWidget);
expect(find.byIcon(Icons.star_border), findsOneWidget);
expect(find.byIcon(Icons.hotel), findsOneWidget);
// Only the selected label is visible.
expect(_labelOpacity(tester, 'Abc'), 1);
expect(_labelOpacity(tester, 'Def'), 0);
expect(_labelOpacity(tester, 'Ghi'), 0);
expect(_labelOpacity(tester, 'Jkl'), 0);
});
testWidgets('Destination spacing is correct - [labelType]=none (default), [textScaleFactor]=1.0 (default)', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationPadding = 12.0;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationPadding / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is one height below the first destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is one height below the second destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is one height below the third destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Destination spacing is correct - [labelType]=none (default), [textScaleFactor]=3.0', (WidgetTester tester) async {
// Since the rail is icon only, its destinations should not be affected by
// textScaleFactor.
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationPadding = 12.0;
await _pumpNavigationRail(
tester,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationPadding / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is one height below the first destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is one height below the second destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is one height below the third destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Destination spacing is correct - [labelType]=none (default), [textScaleFactor]=0.75', (WidgetTester tester) async {
// Since the rail is icon only, its destinations should not be affected by
// textScaleFactor.
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationPadding = 12.0;
await _pumpNavigationRail(
tester,
textScaleFactor: 0.75,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationPadding / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is one height below the first destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is one height below the second destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is one height below the third destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Destination spacing is correct - [labelType]=selected, [textScaleFactor]=1.0 (default)', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between the indicator and label.
const double destinationLabelSpacing = 4.0;
// Height of the label.
const double labelHeight = 16.0;
// Height of a destination with both icon and label.
const double destinationHeightWithLabel = destinationHeight + destinationLabelSpacing + labelHeight;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.selected,
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination is topPadding below the rail top.
double nextDestinationY = topPadding;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + destinationHeight + destinationLabelSpacing,
),
),
);
// The second destination is below the first with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
}
// The third destination is below the second with some spacing.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
}
// The fourth destination is below the third with some spacing.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}
});
testWidgets('Destination spacing is correct - [labelType]=selected, [textScaleFactor]=3.0', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 125.5;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between the indicator and label.
const double destinationLabelSpacing = 4.0;
// Height of the label.
const double labelHeight = 16.0 * 3.0;
// Height of a destination with both icon and label.
const double destinationHeightWithLabel = destinationHeight + destinationLabelSpacing + labelHeight;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.selected,
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination topPadding below the rail top.
double nextDestinationY = topPadding;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + destinationHeight + destinationLabelSpacing,
),
),
);
// The second destination is below the first with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
}
// The third destination is below the second with some spacing.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
}
// The fourth destination is below the third with some spacing.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}
});
testWidgets('Destination spacing is correct - [labelType]=selected, [textScaleFactor]=0.75', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between the indicator and label.
const double destinationLabelSpacing = 4.0;
// Height of the label.
const double labelHeight = 16.0 * 0.75;
// Height of a destination with both icon and label.
const double destinationHeightWithLabel = destinationHeight + destinationLabelSpacing + labelHeight;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
textScaleFactor: 0.75,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.selected,
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination topPadding below the rail top.
double nextDestinationY = topPadding;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + destinationHeight + destinationLabelSpacing,
),
),
);
// The second destination is below the first with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
}
// The third destination is below the second with some spacing.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
}
// The fourth destination is below the third with some spacing.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}
});
testWidgets('Destination spacing is correct - [labelType]=all, [textScaleFactor]=1.0 (default)', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between the indicator and label.
const double destinationLabelSpacing = 4.0;
// Height of the label.
const double labelHeight = 16.0;
// Height of a destination with both icon and label.
const double destinationHeightWithLabel = destinationHeight + destinationLabelSpacing + labelHeight;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination topPadding below the rail top.
double nextDestinationY = topPadding;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + destinationHeight + destinationLabelSpacing,
),
),
);
// The second destination is below the first with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
}
// The third destination is below the second with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
}
// The fourth destination is below the third with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}
});
testWidgets('Destination spacing is correct - [labelType]=all, [textScaleFactor]=3.0', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 125.5;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between the indicator and label.
const double destinationLabelSpacing = 4.0;
// Height of the label.
const double labelHeight = 16.0 * 3.0;
// Height of a destination with both icon and label.
const double destinationHeightWithLabel = destinationHeight + destinationLabelSpacing + labelHeight;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination topPadding below the rail top.
double nextDestinationY = topPadding;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + destinationHeight + destinationLabelSpacing,
),
),
);
// The second destination is below the first with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
}
// The third destination is below the second with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
}
// The fourth destination is below the third with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}
});
testWidgets('Destination spacing is correct - [labelType]=all, [textScaleFactor]=0.75', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between the indicator and label.
const double destinationLabelSpacing = 4.0;
// Height of the label.
const double labelHeight = 16.0 * 0.75;
// Height of a destination with both icon and label.
const double destinationHeightWithLabel = destinationHeight + destinationLabelSpacing + labelHeight;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
textScaleFactor: 0.75,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination topPadding below the rail top.
double nextDestinationY = topPadding;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + destinationHeight + destinationLabelSpacing,
),
),
);
// The second destination is below the first with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
}
// The third destination is below the second with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
}
// The fourth destination is below the third with some spacing.
nextDestinationY += destinationHeightWithLabel + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}
});
testWidgets('Destination spacing is correct for a compact rail - [preferredWidth]=56, [textScaleFactor]=1.0 (default)', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double compactWidth = 56.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
minWidth: 56.0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 56.0);
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationSpacing / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is row below the first destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is a row below the second destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is a row below the third destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Destination spacing is correct for a compact rail - [preferredWidth]=56, [textScaleFactor]=3.0', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double compactWidth = 56.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
minWidth: 56.0,
destinations: _destinations(),
),
);
// Since the rail is icon only, its preferred width should not be affected
// by textScaleFactor.
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, compactWidth);
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationSpacing / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is row below the first destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is a row below the second destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is a row below the third destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Destination spacing is correct for a compact rail - [preferredWidth]=56, [textScaleFactor]=0.75', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double compactWidth = 56.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationSpacing = 12.0;
await _pumpNavigationRail(
tester,
textScaleFactor: 0.75,
navigationRail: NavigationRail(
selectedIndex: 0,
minWidth: 56.0,
destinations: _destinations(),
),
);
// Since the rail is icon only, its preferred width should not be affected
// by textScaleFactor.
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, compactWidth);
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationSpacing / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is row below the first destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is a row below the second destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is a row below the third destination.
nextDestinationY += destinationHeight + destinationSpacing;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(compactWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Group alignment works - [groupAlignment]=-1.0 (default)', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationPadding = 12.0;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationPadding / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is one height below the first destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is one height below the second destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is one height below the third destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Group alignment works - [groupAlignment]=0.0', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationPadding = 12.0;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
groupAlignment: 0.0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination below the rail top by some padding with an offset for the alignment.
double nextDestinationY = topPadding + destinationPadding / 2 + 208;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is one height below the first destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is one height below the second destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is one height below the third destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Group alignment works - [groupAlignment]=1.0', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationPadding = 12.0;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
groupAlignment: 1.0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, destinationWidth);
// The first destination below the rail top by some padding with an offset for the alignment.
double nextDestinationY = topPadding + destinationPadding / 2 + 416;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is one height below the first destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is one height below the second destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is one height below the third destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Leading and trailing appear in the correct places', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
leading: FloatingActionButton(onPressed: () { }),
trailing: FloatingActionButton(onPressed: () { }),
destinations: _destinations(),
),
);
final RenderBox leading = tester.renderObject<RenderBox>(find.byType(FloatingActionButton).at(0));
final RenderBox trailing = tester.renderObject<RenderBox>(find.byType(FloatingActionButton).at(1));
expect(leading.localToGlobal(Offset.zero), Offset((80 - leading.size.width) / 2, 8.0));
expect(trailing.localToGlobal(Offset.zero), Offset((80 - trailing.size.width) / 2, 248.0));
});
testWidgets('Extended rail animates the width and labels appear - [textDirection]=LTR', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationPadding = 12.0;
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
final RenderBox rail = tester.firstRenderObject<RenderBox>(find.byType(NavigationRail));
expect(rail.size.width, destinationWidth);
stateSetter(() {
extended = true;
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(rail.size.width, equals(168.0));
await tester.pumpAndSettle();
expect(rail.size.width, equals(256.0));
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationPadding / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
destinationWidth,
nextDestinationY + (destinationHeight - firstLabelRenderBox.size.height) / 2.0,
),
),
);
// The second destination is one height below the first destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
final RenderBox secondLabelRenderBox = _labelRenderBox(tester, 'Def');
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
expect(
secondLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
destinationWidth,
nextDestinationY + (destinationHeight - secondLabelRenderBox.size.height) / 2.0,
),
),
);
// The third destination is one height below the second destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
final RenderBox thirdLabelRenderBox = _labelRenderBox(tester, 'Ghi');
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
expect(
thirdLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
destinationWidth,
nextDestinationY + (destinationHeight - thirdLabelRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is one height below the third destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
final RenderBox fourthLabelRenderBox = _labelRenderBox(tester, 'Jkl');
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(destinationWidth - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
expect(
fourthLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
destinationWidth,
nextDestinationY + (destinationHeight - fourthLabelRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Extended rail animates the width and labels appear - [textDirection]=RTL', (WidgetTester tester) async {
// Padding at the top of the rail.
const double topPadding = 8.0;
// Width of a destination.
const double destinationWidth = 80.0;
// Height of a destination indicator with icon.
const double destinationHeight = 32.0;
// Space between destinations.
const double destinationPadding = 12.0;
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: Row(
textDirection: TextDirection.rtl,
children: <Widget>[
NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
),
);
},
),
),
);
final RenderBox rail = tester.firstRenderObject<RenderBox>(find.byType(NavigationRail));
expect(rail.size.width, equals(destinationWidth));
expect(rail.localToGlobal(Offset.zero), equals(const Offset(720.0, 0.0)));
stateSetter(() {
extended = true;
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(rail.size.width, equals(168.0));
expect(rail.localToGlobal(Offset.zero), equals(const Offset(632.0, 0.0)));
await tester.pumpAndSettle();
expect(rail.size.width, equals(256.0));
expect(rail.localToGlobal(Offset.zero), equals(const Offset(544.0, 0.0)));
// The first destination below the rail top by some padding.
double nextDestinationY = topPadding + destinationPadding / 2;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - (destinationWidth + firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - destinationWidth - firstLabelRenderBox.size.width,
nextDestinationY + (destinationHeight - firstLabelRenderBox.size.height) / 2.0,
),
),
);
// The second destination is one height below the first destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
final RenderBox secondLabelRenderBox = _labelRenderBox(tester, 'Def');
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - (destinationWidth + secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - secondIconRenderBox.size.height) / 2.0,
),
),
);
expect(
secondLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - destinationWidth - secondLabelRenderBox.size.width,
nextDestinationY + (destinationHeight - secondLabelRenderBox.size.height) / 2.0,
),
),
);
// The third destination is one height below the second destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
final RenderBox thirdLabelRenderBox = _labelRenderBox(tester, 'Ghi');
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - (destinationWidth + thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - thirdIconRenderBox.size.height) / 2.0,
),
),
);
expect(
thirdLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - destinationWidth - thirdLabelRenderBox.size.width,
nextDestinationY + (destinationHeight - thirdLabelRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is one height below the third destination.
nextDestinationY += destinationHeight + destinationPadding;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
final RenderBox fourthLabelRenderBox = _labelRenderBox(tester, 'Jkl');
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800 - (destinationWidth + fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (destinationHeight - fourthIconRenderBox.size.height) / 2.0,
),
),
);
expect(
fourthLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - destinationWidth - fourthLabelRenderBox.size.width,
nextDestinationY + (destinationHeight - fourthLabelRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Extended rail gets wider with longer labels are larger text scale', (WidgetTester tester) async {
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
MediaQuery.withClampedTextScaling(
minScaleFactor: 3.0,
maxScaleFactor: 3.0,
child: NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Longer Label'),
),
],
extended: extended,
),
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
final RenderBox rail = tester.firstRenderObject<RenderBox>(find.byType(NavigationRail));
expect(rail.size.width, equals(80.0));
stateSetter(() {
extended = true;
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(rail.size.width, equals(303.0));
await tester.pumpAndSettle();
expect(rail.size.width, equals(526.0));
});
testWidgets('Extended rail final width can be changed', (WidgetTester tester) async {
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 0,
minExtendedWidth: 300,
destinations: _destinations(),
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
final RenderBox rail = tester.firstRenderObject<RenderBox>(find.byType(NavigationRail));
expect(rail.size.width, equals(80.0));
stateSetter(() {
extended = true;
});
await tester.pumpAndSettle();
expect(rail.size.width, equals(300.0));
});
/// Regression test for https://github.com/flutter/flutter/issues/65657
testWidgets('Extended rail transition does not jump from the beginning', (WidgetTester tester) async {
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Longer Label'),
),
],
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
final Finder rail = find.byType(NavigationRail);
// Before starting the animation, the rail has a width of 80.
expect(tester.getSize(rail).width, 80.0);
stateSetter(() {
extended = true;
});
await tester.pump();
// Create very close to 0, but non-zero, animation value.
await tester.pump(const Duration(milliseconds: 1));
// Expect that it has started to extend.
expect(tester.getSize(rail).width, greaterThan(80.0));
// Expect that it has only extended by a small amount, or that the first
// frame does not jump. This helps verify that it is a smooth animation.
expect(tester.getSize(rail).width, closeTo(80.0, 1.0));
});
testWidgets('Extended rail animation can be consumed', (WidgetTester tester) async {
bool extended = false;
late Animation<double> animation;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 0,
leading: Builder(
builder: (BuildContext context) {
animation = NavigationRail.extendedAnimation(context);
return FloatingActionButton(onPressed: () { });
},
),
destinations: _destinations(),
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
expect(animation.isDismissed, isTrue);
stateSetter(() {
extended = true;
});
await tester.pumpAndSettle();
expect(animation.isCompleted, isTrue);
});
testWidgets('onDestinationSelected is called', (WidgetTester tester) async {
late int selectedIndex;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
onDestinationSelected: (int index) {
selectedIndex = index;
},
labelType: NavigationRailLabelType.all,
),
);
await tester.tap(find.text('Def'));
expect(selectedIndex, 1);
await tester.tap(find.text('Ghi'));
expect(selectedIndex, 2);
// Wait for any pending shader compilation.
tester.pumpAndSettle();
});
testWidgets('onDestinationSelected is not called if null', (WidgetTester tester) async {
const int selectedIndex = 0;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: selectedIndex,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
await tester.tap(find.text('Def'));
expect(selectedIndex, 0);
// Wait for any pending shader compilation.
tester.pumpAndSettle();
});
testWidgets('Changing destinations animate when [labelType]=selected', (WidgetTester tester) async {
int selectedIndex = 0;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
destinations: _destinations(),
selectedIndex: selectedIndex,
labelType: NavigationRailLabelType.selected,
onDestinationSelected: (int index) {
setState(() {
selectedIndex = index;
});
},
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
// Tap the second destination.
await tester.tap(find.byIcon(Icons.bookmark_border));
expect(selectedIndex, 1);
// The second destination animates in.
expect(_labelOpacity(tester, 'Def'), equals(0.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(_labelOpacity(tester, 'Def'), equals(0.5));
await tester.pumpAndSettle();
expect(_labelOpacity(tester, 'Def'), equals(1.0));
// Tap the third destination.
await tester.tap(find.byIcon(Icons.star_border));
expect(selectedIndex, 2);
// The second destination animates out quickly and the third destination
// animates in.
expect(_labelOpacity(tester, 'Ghi'), equals(0.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 25));
expect(_labelOpacity(tester, 'Def'), equals(0.5));
expect(_labelOpacity(tester, 'Ghi'), equals(0.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 25));
expect(_labelOpacity(tester, 'Def'), equals(0.0));
expect(_labelOpacity(tester, 'Ghi'), equals(0.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(_labelOpacity(tester, 'Ghi'), equals(0.5));
await tester.pumpAndSettle();
expect(_labelOpacity(tester, 'Ghi'), equals(1.0));
});
testWidgets('Changing destinations animate for selectedIndex=null', (WidgetTester tester) async {
int? selectedIndex = 0;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
destinations: _destinations(),
selectedIndex: selectedIndex,
labelType: NavigationRailLabelType.selected,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
// Unset the selected index.
stateSetter(() {
selectedIndex = null;
});
// The first destination animates out.
expect(_labelOpacity(tester, 'Abc'), equals(1.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 25));
expect(_labelOpacity(tester, 'Abc'), equals(0.5));
await tester.pumpAndSettle();
expect(_labelOpacity(tester, 'Abc'), equals(0.0));
// Set the selected index to the first destination.
stateSetter(() {
selectedIndex = 0;
});
// The first destination animates in.
expect(_labelOpacity(tester, 'Abc'), equals(0.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(_labelOpacity(tester, 'Abc'), equals(0.5));
await tester.pumpAndSettle();
expect(_labelOpacity(tester, 'Abc'), equals(1.0));
});
testWidgets('Changing destinations animate when selectedIndex=null during transition', (WidgetTester tester) async {
int? selectedIndex = 0;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
destinations: _destinations(),
selectedIndex: selectedIndex,
labelType: NavigationRailLabelType.selected,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
stateSetter(() {
selectedIndex = 1;
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 175));
// Interrupt while animating from index 0 to 1.
stateSetter(() {
selectedIndex = null;
});
expect(_labelOpacity(tester, 'Abc'), equals(0));
expect(_labelOpacity(tester, 'Def'), equals(1));
await tester.pump();
// Create very close to 0, but non-zero, animation value.
await tester.pump(const Duration(milliseconds: 1));
// Ensure the opacity is animated back towards 0.
expect(_labelOpacity(tester, 'Def'), lessThan(0.5));
expect(_labelOpacity(tester, 'Def'), closeTo(0.5, 0.03));
await tester.pumpAndSettle();
expect(_labelOpacity(tester, 'Abc'), equals(0.0));
expect(_labelOpacity(tester, 'Def'), equals(0.0));
});
testWidgets('Semantics - labelType=[none]', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await _pumpLocalizedTestRail(tester, labelType: NavigationRailLabelType.none);
expect(semantics, hasSemantics(_expectedSemantics(), ignoreId: true, ignoreTransform: true, ignoreRect: true));
semantics.dispose();
});
testWidgets('Semantics - labelType=[selected]', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await _pumpLocalizedTestRail(tester, labelType: NavigationRailLabelType.selected);
expect(semantics, hasSemantics(_expectedSemantics(), ignoreId: true, ignoreTransform: true, ignoreRect: true));
semantics.dispose();
});
testWidgets('Semantics - labelType=[all]', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await _pumpLocalizedTestRail(tester, labelType: NavigationRailLabelType.all);
expect(semantics, hasSemantics(_expectedSemantics(), ignoreId: true, ignoreTransform: true, ignoreRect: true));
semantics.dispose();
});
testWidgets('Semantics - extended', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await _pumpLocalizedTestRail(tester, extended: true);
expect(semantics, hasSemantics(_expectedSemantics(), ignoreId: true, ignoreTransform: true, ignoreRect: true));
semantics.dispose();
});
testWidgets('NavigationRailDestination padding properly applied - NavigationRailLabelType.all', (WidgetTester tester) async {
const EdgeInsets defaultPadding = EdgeInsets.symmetric(horizontal: 8.0);
const EdgeInsets secondItemPadding = EdgeInsets.symmetric(vertical: 30.0);
const EdgeInsets thirdItemPadding = EdgeInsets.symmetric(horizontal: 10.0);
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
labelType: NavigationRailLabelType.all,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
padding: secondItemPadding,
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
padding: thirdItemPadding,
),
],
),
);
final Iterable<Widget> indicatorInkWells = tester.allWidgets.where((Widget object) => object.runtimeType.toString() == '_IndicatorInkWell');
final Padding firstItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(0).runtimeType, 'Abc'),
matching: find.widgetWithText(Padding, 'Abc'),
)
);
final Padding secondItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(1).runtimeType, 'Def'),
matching: find.widgetWithText(Padding, 'Def'),
)
);
final Padding thirdItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(2).runtimeType, 'Ghi'),
matching: find.widgetWithText(Padding, 'Ghi'),
)
);
expect(firstItem.padding, defaultPadding);
expect(secondItem.padding, secondItemPadding);
expect(thirdItem.padding, thirdItemPadding);
});
testWidgets('NavigationRailDestination padding properly applied - NavigationRailLabelType.selected', (WidgetTester tester) async {
const EdgeInsets defaultPadding = EdgeInsets.symmetric(horizontal: 8.0);
const EdgeInsets secondItemPadding = EdgeInsets.symmetric(vertical: 30.0);
const EdgeInsets thirdItemPadding = EdgeInsets.symmetric(horizontal: 10.0);
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
labelType: NavigationRailLabelType.selected,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
padding: secondItemPadding,
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
padding: thirdItemPadding,
),
],
),
);
final Iterable<Widget> indicatorInkWells = tester.allWidgets.where((Widget object) => object.runtimeType.toString() == '_IndicatorInkWell');
final Padding firstItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(0).runtimeType, 'Abc'),
matching: find.widgetWithText(Padding, 'Abc'),
)
);
final Padding secondItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(1).runtimeType, 'Def'),
matching: find.widgetWithText(Padding, 'Def'),
)
);
final Padding thirdItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(2).runtimeType, 'Ghi'),
matching: find.widgetWithText(Padding, 'Ghi'),
)
);
expect(firstItem.padding, defaultPadding);
expect(secondItem.padding, secondItemPadding);
expect(thirdItem.padding, thirdItemPadding);
});
testWidgets('NavigationRailDestination padding properly applied - NavigationRailLabelType.none', (WidgetTester tester) async {
const EdgeInsets defaultPadding = EdgeInsets.zero;
const EdgeInsets secondItemPadding = EdgeInsets.symmetric(vertical: 30.0);
const EdgeInsets thirdItemPadding = EdgeInsets.symmetric(horizontal: 10.0);
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
labelType: NavigationRailLabelType.none,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
padding: secondItemPadding,
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
padding: thirdItemPadding,
),
],
),
);
final Iterable<Widget> indicatorInkWells = tester.allWidgets.where((Widget object) => object.runtimeType.toString() == '_IndicatorInkWell');
final Padding firstItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(0).runtimeType, 'Abc'),
matching: find.widgetWithText(Padding, 'Abc'),
)
);
final Padding secondItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(1).runtimeType, 'Def'),
matching: find.widgetWithText(Padding, 'Def'),
)
);
final Padding thirdItem = tester.widget<Padding>(
find.descendant(
of: find.widgetWithText(indicatorInkWells.elementAt(2).runtimeType, 'Ghi'),
matching: find.widgetWithText(Padding, 'Ghi'),
)
);
expect(firstItem.padding, defaultPadding);
expect(secondItem.padding, secondItemPadding);
expect(thirdItem.padding, thirdItemPadding);
});
testWidgets('NavigationRailDestination adds indicator by default when ThemeData.useMaterial3 is true', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
labelType: NavigationRailLabelType.selected,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
),
],
),
);
expect(find.byType(NavigationIndicator), findsWidgets);
});
testWidgets('NavigationRailDestination adds indicator when useIndicator is true', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
useIndicator: true,
labelType: NavigationRailLabelType.selected,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
),
],
),
);
expect(find.byType(NavigationIndicator), findsWidgets);
});
testWidgets('NavigationRailDestination does not add indicator when useIndicator is false', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
useIndicator: false,
labelType: NavigationRailLabelType.selected,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
),
],
),
);
expect(find.byType(NavigationIndicator), findsNothing);
});
testWidgets('NavigationRailDestination adds an oval indicator when no labels are present', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
useIndicator: true,
labelType: NavigationRailLabelType.none,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
),
],
),
);
final NavigationIndicator indicator = tester.widget<NavigationIndicator>(find.byType(NavigationIndicator).first);
expect(indicator.width, 56);
expect(indicator.height, 32);
});
testWidgets('NavigationRailDestination adds an oval indicator when selected labels are present', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
useIndicator: true,
labelType: NavigationRailLabelType.selected,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
),
],
),
);
final NavigationIndicator indicator = tester.widget<NavigationIndicator>(find.byType(NavigationIndicator).first);
expect(indicator.width, 56);
expect(indicator.height, 32);
});
testWidgets('NavigationRailDestination adds an oval indicator when all labels are present', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
useIndicator: true,
labelType: NavigationRailLabelType.all,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
),
],
),
);
final NavigationIndicator indicator = tester.widget<NavigationIndicator>(find.byType(NavigationIndicator).first);
expect(indicator.width, 56);
expect(indicator.height, 32);
});
testWidgets('NavigationRailDestination has center aligned indicator - [labelType]=none', (WidgetTester tester) async {
// This is a regression test for
// https://github.com/flutter/flutter/issues/97753
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
labelType: NavigationRailLabelType.none,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Stack(
children: <Widget>[
Icon(Icons.umbrella),
Positioned(
top: 0,
right: 0,
child: Text(
'Text',
style: TextStyle(fontSize: 10, color: Colors.red),
),
),
],
),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.umbrella),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
label: Text('Ghi'),
),
],
),
);
// Indicator with Stack widget
final RenderBox firstIndicator = tester.renderObject(find.byType(Icon).first);
expect(firstIndicator.localToGlobal(Offset.zero).dx, 28.0);
// Indicator without Stack widget
final RenderBox lastIndicator = tester.renderObject(find.byType(Icon).last);
expect(lastIndicator.localToGlobal(Offset.zero).dx, 28.0);
});
testWidgets('NavigationRail respects the notch/system navigation bar in landscape mode', (WidgetTester tester) async {
const double safeAreaPadding = 40.0;
NavigationRail navigationRail() {
return NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
],
);
}
await tester.pumpWidget(_buildWidget(navigationRail()));
final double defaultWidth = tester.getSize(find.byType(NavigationRail)).width;
expect(defaultWidth, 80);
await tester.pumpWidget(
_buildWidget(
MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.only(left: safeAreaPadding),
),
child: navigationRail(),
),
),
);
final double updatedWidth = tester.getSize(find.byType(NavigationRail)).width;
expect(updatedWidth, defaultWidth + safeAreaPadding);
// test width when text direction is RTL.
await tester.pumpWidget(
_buildWidget(
MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.only(right: safeAreaPadding),
),
child: navigationRail(),
),
isRTL: true,
),
);
final double updatedWidthRTL = tester.getSize(find.byType(NavigationRail)).width;
expect(updatedWidthRTL, defaultWidth + safeAreaPadding);
});
testWidgets('NavigationRail indicator renders ripple', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 1,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
],
labelType: NavigationRailLabelType.all,
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
const Rect indicatorRect = Rect.fromLTRB(12.0, 0.0, 68.0, 32.0);
const Rect includedRect = indicatorRect;
final Rect excludedRect = includedRect.inflate(10);
expect(
inkFeatures,
paints
..clipPath(
pathMatcher: isPathThat(
includes: <Offset>[
includedRect.centerLeft,
includedRect.topCenter,
includedRect.centerRight,
includedRect.bottomCenter,
],
excludes: <Offset>[
excludedRect.centerLeft,
excludedRect.topCenter,
excludedRect.centerRight,
excludedRect.bottomCenter,
],
),
)
..rect(
rect: indicatorRect,
color: const Color(0x0a6750a4),
)
..rrect(
rrect: RRect.fromLTRBR(12.0, 72.0, 68.0, 104.0, const Radius.circular(16)),
color: const Color(0xffe8def8),
),
);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('NavigationRail indicator renders ripple - extended', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/117126
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 1,
extended: true,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
],
labelType: NavigationRailLabelType.none,
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
const Rect indicatorRect = Rect.fromLTRB(12.0, 6.0, 68.0, 38.0);
const Rect includedRect = indicatorRect;
final Rect excludedRect = includedRect.inflate(10);
expect(
inkFeatures,
paints
..clipPath(
pathMatcher: isPathThat(
includes: <Offset>[
includedRect.centerLeft,
includedRect.topCenter,
includedRect.centerRight,
includedRect.bottomCenter,
],
excludes: <Offset>[
excludedRect.centerLeft,
excludedRect.topCenter,
excludedRect.centerRight,
excludedRect.bottomCenter,
],
),
)
..rect(
rect: indicatorRect,
color: const Color(0x0a6750a4),
)
..rrect(
rrect: RRect.fromLTRBR(12.0, 58.0, 68.0, 90.0, const Radius.circular(16)),
color: const Color(0xffe8def8),
),
);
});
testWidgets('NavigationRail indicator renders properly when padding is applied', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/117126
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 1,
extended: true,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
padding: EdgeInsets.all(10),
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
padding: EdgeInsets.all(18),
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
],
labelType: NavigationRailLabelType.none,
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
const Rect indicatorRect = Rect.fromLTRB(22.0, 16.0, 78.0, 48.0);
const Rect includedRect = indicatorRect;
final Rect excludedRect = includedRect.inflate(10);
expect(
inkFeatures,
paints
..clipPath(
pathMatcher: isPathThat(
includes: <Offset>[
includedRect.centerLeft,
includedRect.topCenter,
includedRect.centerRight,
includedRect.bottomCenter,
],
excludes: <Offset>[
excludedRect.centerLeft,
excludedRect.topCenter,
excludedRect.centerRight,
excludedRect.bottomCenter,
],
),
)
..rect(
rect: indicatorRect,
color: const Color(0x0a6750a4),
)
..rrect(
rrect: RRect.fromLTRBR(30.0, 96.0, 86.0, 128.0, const Radius.circular(16)),
color: const Color(0xffe8def8),
),
);
});
testWidgets('Indicator renders properly when NavigationRai.minWidth < default minWidth', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/117126
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
minWidth: 50,
selectedIndex: 1,
extended: true,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
],
labelType: NavigationRailLabelType.none,
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
const Rect indicatorRect = Rect.fromLTRB(-3.0, 6.0, 53.0, 38.0);
const Rect includedRect = indicatorRect;
final Rect excludedRect = includedRect.inflate(10);
expect(
inkFeatures,
paints
..clipPath(
pathMatcher: isPathThat(
includes: <Offset>[
includedRect.centerLeft,
includedRect.topCenter,
includedRect.centerRight,
includedRect.bottomCenter,
],
excludes: <Offset>[
excludedRect.centerLeft,
excludedRect.topCenter,
excludedRect.centerRight,
excludedRect.bottomCenter,
],
),
)
..rect(
rect: indicatorRect,
color: const Color(0x0a6750a4),
)
..rrect(
rrect: RRect.fromLTRBR(0.0, 58.0, 50.0, 90.0, const Radius.circular(16)),
color: const Color(0xffe8def8),
),
);
});
testWidgets('NavigationRail indicator renders properly with custom padding and minWidth', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/117126
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
minWidth: 300,
selectedIndex: 1,
extended: true,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
padding: EdgeInsets.all(10),
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
padding: EdgeInsets.all(18),
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
],
labelType: NavigationRailLabelType.none,
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
const Rect indicatorRect = Rect.fromLTRB(132.0, 16.0, 188.0, 48.0);
const Rect includedRect = indicatorRect;
final Rect excludedRect = includedRect.inflate(10);
expect(
inkFeatures,
paints
..clipPath(
pathMatcher: isPathThat(
includes: <Offset>[
includedRect.centerLeft,
includedRect.topCenter,
includedRect.centerRight,
includedRect.bottomCenter,
],
excludes: <Offset>[
excludedRect.centerLeft,
excludedRect.topCenter,
excludedRect.centerRight,
excludedRect.bottomCenter,
],
),
)
..rect(
rect: indicatorRect,
color: const Color(0x0a6750a4),
)
..rrect(
rrect: RRect.fromLTRBR(140.0, 96.0, 196.0, 128.0, const Radius.circular(16)),
color: const Color(0xffe8def8),
),
);
});
testWidgets('NavigationRail indicator renders properly with long labels', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/128005.
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 1,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('ABC'),
),
],
labelType: NavigationRailLabelType.all,
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
// Default values from M3 specification.
const double indicatorHeight = 32.0;
const double destinationWidth = 72.0;
const double destinationHorizontalPadding = 8.0;
const double indicatorWidth = destinationWidth - 2 * destinationHorizontalPadding; // 56.0
const double verticalSpacer = 8.0;
const double verticalIconLabelSpacing = 4.0;
const double verticalDestinationSpacing = 12.0;
// The navigation rail width is larger than default because of the first destination long label.
final double railWidth = tester.getSize(find.byType(NavigationRail)).width;
// Expected indicator position.
final double indicatorLeft = (railWidth - indicatorWidth) / 2;
final double indicatorRight = (railWidth + indicatorWidth) / 2;
final Rect indicatorRect = Rect.fromLTRB(indicatorLeft, 0.0, indicatorRight, indicatorHeight);
final Rect includedRect = indicatorRect;
final Rect excludedRect = includedRect.inflate(10);
// Compute the vertical position for the selected destination (the one with 'bookmark' icon).
const double labelHeight = 16; // fontSize is 12 and height is 1.3.
const double destinationHeight = indicatorHeight + verticalIconLabelSpacing + labelHeight + verticalDestinationSpacing;
const double secondDestinationVerticalOffset = verticalSpacer + destinationHeight;
const double secondIndicatorVerticalOffset = secondDestinationVerticalOffset;
expect(
inkFeatures,
paints
..clipPath(
pathMatcher: isPathThat(
includes: <Offset>[
includedRect.centerLeft,
includedRect.topCenter,
includedRect.centerRight,
includedRect.bottomCenter,
],
excludes: <Offset>[
excludedRect.centerLeft,
excludedRect.topCenter,
excludedRect.centerRight,
excludedRect.bottomCenter,
],
),
)
..rect(
rect: indicatorRect,
color: const Color(0x0a6750a4),
)
..rrect(
rrect: RRect.fromLTRBR(
indicatorLeft,
secondIndicatorVerticalOffset,
indicatorRight,
secondIndicatorVerticalOffset + indicatorHeight,
const Radius.circular(16),
),
color: const Color(0xffe8def8),
),
);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('NavigationRail indicator renders properly with large icon', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/133799.
const double iconSize = 50;
await _pumpNavigationRail(
tester,
navigationRailTheme: const NavigationRailThemeData(
selectedIconTheme: IconThemeData(size: iconSize),
unselectedIconTheme: IconThemeData(size: iconSize),
),
navigationRail: NavigationRail(
selectedIndex: 1,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('ABC'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('DEF'),
),
],
labelType: NavigationRailLabelType.all,
),
);
// Hover the first destination.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
// Default values from M3 specification.
const double railMinWidth = 80.0;
const double indicatorHeight = 32.0;
const double destinationWidth = 72.0;
const double destinationHorizontalPadding = 8.0;
const double indicatorWidth = destinationWidth - 2 * destinationHorizontalPadding; // 56.0
const double verticalSpacer = 8.0;
const double verticalIconLabelSpacing = 4.0;
const double verticalDestinationSpacing = 12.0;
// The navigation rail width is the default one because labels are short.
final double railWidth = tester.getSize(find.byType(NavigationRail)).width;
expect(railWidth, railMinWidth);
// Expected indicator position.
final double indicatorLeft = (railWidth - indicatorWidth) / 2;
final double indicatorRight = (railWidth + indicatorWidth) / 2;
const double indicatorTop = (iconSize - indicatorHeight) / 2;
const double indicatorBottom = (iconSize + indicatorHeight) / 2;
final Rect indicatorRect = Rect.fromLTRB(indicatorLeft, indicatorTop, indicatorRight, indicatorBottom);
final Rect includedRect = indicatorRect;
final Rect excludedRect = includedRect.inflate(10);
// Compute the vertical position for the selected destination (the one with 'bookmark' icon).
const double labelHeight = 16; // fontSize is 12 and height is 1.3.
const double destinationHeight = iconSize + verticalIconLabelSpacing + labelHeight + verticalDestinationSpacing;
const double secondDestinationVerticalOffset = verticalSpacer + destinationHeight;
const double indicatorOffset = (iconSize - indicatorHeight) / 2;
const double secondIndicatorVerticalOffset = secondDestinationVerticalOffset + indicatorOffset;
expect(
inkFeatures,
paints
..clipPath(
pathMatcher: isPathThat(
includes: <Offset>[
includedRect.centerLeft,
includedRect.topCenter,
includedRect.centerRight,
includedRect.bottomCenter,
],
excludes: <Offset>[
excludedRect.centerLeft,
excludedRect.topCenter,
excludedRect.centerRight,
excludedRect.bottomCenter,
],
),
)
// Hover highlight for the hovered destination (the one with 'favorite' icon).
..rect(
rect: indicatorRect,
color: const Color(0x0a6750a4),
)
// Indicator for the selected destination (the one with 'bookmark' icon).
..rrect(
rrect: RRect.fromLTRBR(
indicatorLeft,
secondIndicatorVerticalOffset,
indicatorRight,
secondIndicatorVerticalOffset + indicatorHeight,
const Radius.circular(16),
),
color: const Color(0xffe8def8),
),
);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('NavigationRail indicator renders properly when text direction is rtl', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/134361.
await tester.pumpWidget(_buildWidget(
NavigationRail(
selectedIndex: 1,
extended: true,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('ABC'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('DEF'),
),
],
),
isRTL: true,
));
// Hover the first destination.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
// Default values from M3 specification.
const double railMinExtendedWidth = 256.0;
const double indicatorHeight = 32.0;
const double destinationWidth = 72.0;
const double destinationHorizontalPadding = 8.0;
const double indicatorWidth = destinationWidth - 2 * destinationHorizontalPadding; // 56.0
const double verticalSpacer = 8.0;
const double verticalDestinationSpacingM3 = 12.0;
// The navigation rail width is the default one because labels are short.
final double railWidth = tester.getSize(find.byType(NavigationRail)).width;
expect(railWidth, railMinExtendedWidth);
// Expected indicator position.
final double indicatorLeft = railWidth - (destinationWidth - destinationHorizontalPadding / 2);
final double indicatorRight = indicatorLeft + indicatorWidth;
final Rect indicatorRect = Rect.fromLTRB(
indicatorLeft,
verticalDestinationSpacingM3 / 2,
indicatorRight,
verticalDestinationSpacingM3 / 2 + indicatorHeight,
);
final Rect includedRect = indicatorRect;
final Rect excludedRect = includedRect.inflate(10);
// Compute the vertical position for the selected destination (the one with 'bookmark' icon).
const double destinationHeight = indicatorHeight + verticalDestinationSpacingM3;
const double secondDestinationVerticalOffset = verticalSpacer + destinationHeight;
const double secondIndicatorVerticalOffset = secondDestinationVerticalOffset + verticalDestinationSpacingM3 / 2;
const double secondDestinationHorizontalOffset = 800 - railMinExtendedWidth; // RTL.
expect(
inkFeatures,
paints
..clipPath(
pathMatcher: isPathThat(
includes: <Offset>[
includedRect.centerLeft,
includedRect.topCenter,
includedRect.centerRight,
includedRect.bottomCenter,
],
excludes: <Offset>[
excludedRect.centerLeft,
excludedRect.topCenter,
excludedRect.centerRight,
excludedRect.bottomCenter,
],
),
)
// Hover highlight for the hovered destination (the one with 'favorite' icon).
..rect(
rect: indicatorRect,
color: const Color(0x0a6750a4),
)
// Indicator for the selected destination (the one with 'bookmark' icon).
..rrect(
rrect: RRect.fromLTRBR(
secondDestinationHorizontalOffset + indicatorLeft,
secondIndicatorVerticalOffset,
secondDestinationHorizontalOffset + indicatorRight,
secondIndicatorVerticalOffset + indicatorHeight,
const Radius.circular(16),
),
color: const Color(0xffe8def8),
),
);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('NavigationRail indicator scale transform', (WidgetTester tester) async {
int selectedIndex = 0;
Future<void> buildWidget() async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: selectedIndex,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
],
labelType: NavigationRailLabelType.all,
),
);
}
await buildWidget();
await tester.pumpAndSettle();
final Finder transformFinder = find.descendant(
of: find.byType(NavigationIndicator),
matching: find.byType(Transform),
).last;
Matrix4 transform = tester.widget<Transform>(transformFinder).transform;
expect(transform.getColumn(0)[0], 0.0);
selectedIndex = 1;
await buildWidget();
await tester.pump(const Duration(milliseconds: 100));
transform = tester.widget<Transform>(transformFinder).transform;
expect(transform.getColumn(0)[0], closeTo(0.9705023956298828, precisionErrorTolerance));
await tester.pump(const Duration(milliseconds: 100));
transform = tester.widget<Transform>(transformFinder).transform;
expect(transform.getColumn(0)[0], 1.0);
});
testWidgets('Navigation destination updates indicator color and shape', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
const Color color = Color(0xff0000ff);
const ShapeBorder shape = RoundedRectangleBorder();
Widget buildNavigationRail({Color? indicatorColor, ShapeBorder? indicatorShape}) {
return MaterialApp(
theme: theme,
home: Builder(
builder: (BuildContext context) {
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
useIndicator: true,
indicatorColor: indicatorColor,
indicatorShape: indicatorShape,
selectedIndex: 0,
destinations: _destinations(),
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
);
}
await tester.pumpWidget(buildNavigationRail());
// Test default indicator color and shape.
expect(_getIndicatorDecoration(tester)?.color, theme.colorScheme.secondaryContainer);
expect(_getIndicatorDecoration(tester)?.shape, const StadiumBorder());
await tester.pumpWidget(buildNavigationRail(indicatorColor: color, indicatorShape: shape));
// Test custom indicator color and shape.
expect(_getIndicatorDecoration(tester)?.color, color);
expect(_getIndicatorDecoration(tester)?.shape, shape);
});
testWidgets("Destination's respect their disabled state", (WidgetTester tester) async {
late int selectedIndex;
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Bcd'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Cde'),
disabled: true,
),
],
onDestinationSelected: (int index) {
selectedIndex = index;
},
labelType: NavigationRailLabelType.all,
),
);
await tester.tap(find.text('Abc'));
expect(selectedIndex, 0);
await tester.tap(find.text('Bcd'));
expect(selectedIndex, 1);
await tester.tap(find.text('Cde'));
expect(selectedIndex, 1);
// Wait for any pending shader compilation.
tester.pumpAndSettle();
});
testWidgets("Destination's label with the right opacity while disabled", (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Bcd'),
disabled: true,
),
],
onDestinationSelected: (int index) {},
labelType: NavigationRailLabelType.all,
),
);
await tester.pumpAndSettle();
double? defaultTextStyleOpacity(String text) {
return tester.widget<DefaultTextStyle>(
find.ancestor(
of: find.text(text),
matching: find.byType(DefaultTextStyle),
).first,
).style.color?.opacity;
}
final double? abcLabelOpacity = defaultTextStyleOpacity('Abc');
final double? bcdLabelOpacity = defaultTextStyleOpacity('Bcd');
expect(abcLabelOpacity, 1.0);
expect(bcdLabelOpacity, closeTo(0.38, 0.01));
});
testWidgets('NavigationRail indicator inkwell can be transparent', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/135866.
final ThemeData theme = ThemeData(
colorScheme: const ColorScheme.light().copyWith(primary: Colors.transparent),
// Material 3 defaults to InkSparkle which is not testable using paints.
splashFactory: InkSplash.splashFactory,
);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Builder(
builder: (BuildContext context) {
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 1,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('ABC'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('DEF'),
),
],
labelType: NavigationRailLabelType.all,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pumpAndSettle();
RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..rect(color: Colors.transparent));
await gesture.down(tester.getCenter(find.byIcon(Icons.favorite_border)));
await tester.pump(); // Start the splash and highlight animations.
await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..circle(color: Colors.transparent));
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Navigation rail can have expanded widgets inside', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
label: Text('Bcd'),
),
],
trailing: const Expanded(
child: Icon(Icons.search),
),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
});
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('Renders at the correct default width - [labelType]=none (default)', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
});
testWidgets('Renders at the correct default width - [labelType]=selected', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
labelType: NavigationRailLabelType.selected,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
});
testWidgets('Renders at the correct default width - [labelType]=all', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
labelType: NavigationRailLabelType.all,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
});
testWidgets('Destination spacing is correct - [labelType]=none (default), [textScaleFactor]=1.0 (default)', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Destination spacing is correct - [labelType]=none (default), [textScaleFactor]=3.0', (WidgetTester tester) async {
// Since the rail is icon only, its destinations should not be affected by
// textScaleFactor.
await _pumpNavigationRail(
tester,
useMaterial3: false,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Destination spacing is correct - [labelType]=none (default), [textScaleFactor]=0.75', (WidgetTester tester) async {
// Since the rail is icon only, its destinations should not be affected by
// textScaleFactor.
await _pumpNavigationRail(
tester,
useMaterial3: false,
textScaleFactor: 0.75,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Destination spacing is correct - [labelType]=selected, [textScaleFactor]=1.0 (default)', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.selected,
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height - firstLabelRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 + firstIconRenderBox.size.height - firstLabelRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Destination spacing is correct - [labelType]=selected, [textScaleFactor]=3.0', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.selected,
),
);
// The rail and destinations sizes grow to fit the larger text labels.
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 142.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
// The first label sits right below the first icon.
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + firstIconRenderBox.size.height,
),
),
);
nextDestinationY += 16.0 + firstIconRenderBox.size.height + firstLabelRenderBox.size.height + 16.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + 24.0,
),
),
);
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + 24.0,
),
),
);
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + 24.0,
),
),
);
});
testWidgets('Destination spacing is correct - [labelType]=selected, [textScaleFactor]=0.75', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
textScaleFactor: 0.75,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.selected,
),
);
// A smaller textScaleFactor will not reduce the default width of the rail
// since there is a minWidth.
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height - firstLabelRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 + firstIconRenderBox.size.height - firstLabelRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
)),
);
});
testWidgets('Destination spacing is correct - [labelType]=all, [textScaleFactor]=1.0 (default)', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + firstIconRenderBox.size.height,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
final RenderBox secondLabelRenderBox = _labelRenderBox(tester, 'Def');
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
secondLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + secondIconRenderBox.size.height,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
final RenderBox thirdLabelRenderBox = _labelRenderBox(tester, 'Ghi');
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
thirdLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + thirdIconRenderBox.size.height,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
final RenderBox fourthLabelRenderBox = _labelRenderBox(tester, 'Jkl');
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
fourthLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + fourthIconRenderBox.size.height,
),
),
);
});
testWidgets('Destination spacing is correct - [labelType]=all, [textScaleFactor]=3.0', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
// The rail and destinations sizes grow to fit the larger text labels.
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 142.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + firstIconRenderBox.size.height,
),
),
);
nextDestinationY += 16.0 + firstIconRenderBox.size.height + firstLabelRenderBox.size.height + 16.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
final RenderBox secondLabelRenderBox = _labelRenderBox(tester, 'Def');
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
secondLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - secondLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + secondIconRenderBox.size.height,
),
),
);
nextDestinationY += 16.0 + secondIconRenderBox.size.height + secondLabelRenderBox.size.height + 16.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
final RenderBox thirdLabelRenderBox = _labelRenderBox(tester, 'Ghi');
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
thirdLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - thirdLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + thirdIconRenderBox.size.height,
),
),
);
nextDestinationY += 16.0 + thirdIconRenderBox.size.height + thirdLabelRenderBox.size.height + 16.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
final RenderBox fourthLabelRenderBox = _labelRenderBox(tester, 'Jkl');
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
fourthLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(142.0 - fourthLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + fourthIconRenderBox.size.height,
),
),
);
});
testWidgets('Destination spacing is correct - [labelType]=all, [textScaleFactor]=0.75', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
textScaleFactor: 0.75,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
labelType: NavigationRailLabelType.all,
),
);
// A smaller textScaleFactor will not reduce the default size of the rail.
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 72.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + firstIconRenderBox.size.height,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
final RenderBox secondLabelRenderBox = _labelRenderBox(tester, 'Def');
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
secondLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + secondIconRenderBox.size.height,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
final RenderBox thirdLabelRenderBox = _labelRenderBox(tester, 'Ghi');
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
thirdLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + thirdIconRenderBox.size.height,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
final RenderBox fourthLabelRenderBox = _labelRenderBox(tester, 'Jkl');
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + 16.0,
),
),
);
expect(
fourthLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthLabelRenderBox.size.width) / 2.0,
nextDestinationY + 16.0 + fourthIconRenderBox.size.height,
),
),
);
});
testWidgets('Destination spacing is correct for a compact rail - [preferredWidth]=56, [textScaleFactor]=1.0 (default)', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
minWidth: 56.0,
destinations: _destinations(),
),
);
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 56.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 56 below the first destination.
nextDestinationY += 56.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 56 below the second destination.
nextDestinationY += 56.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 56 below the third destination.
nextDestinationY += 56.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Destination spacing is correct for a compact rail - [preferredWidth]=56, [textScaleFactor]=3.0', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
minWidth: 56.0,
destinations: _destinations(),
),
);
// Since the rail is icon only, its preferred width should not be affected
// by textScaleFactor.
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 56.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 56 below the first destination.
nextDestinationY += 56.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 56 below the second destination.
nextDestinationY += 56.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 56 below the third destination.
nextDestinationY += 56.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Destination spacing is correct for a compact rail - [preferredWidth]=56, [textScaleFactor]=0.75', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
textScaleFactor: 3.0,
navigationRail: NavigationRail(
selectedIndex: 0,
minWidth: 56.0,
destinations: _destinations(),
),
);
// Since the rail is icon only, its preferred width should not be affected
// by textScaleFactor.
final RenderBox renderBox = tester.renderObject(find.byType(NavigationRail));
expect(renderBox.size.width, 56.0);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 56 below the first destination.
nextDestinationY += 56.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 56 below the second destination.
nextDestinationY += 56.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 56 below the third destination.
nextDestinationY += 56.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(56.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (56.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Group alignment works - [groupAlignment]=-1.0 (default)', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
),
);
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Group alignment works - [groupAlignment]=0.0', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
groupAlignment: 0.0,
destinations: _destinations(),
),
);
double nextDestinationY = 160.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Group alignment works - [groupAlignment]=1.0', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
groupAlignment: 1.0,
destinations: _destinations(),
),
);
double nextDestinationY = 312.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Leading and trailing appear in the correct places', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
selectedIndex: 0,
leading: FloatingActionButton(onPressed: () { }),
trailing: FloatingActionButton(onPressed: () { }),
destinations: _destinations(),
),
);
final RenderBox leading = tester.renderObject<RenderBox>(find.byType(FloatingActionButton).at(0));
final RenderBox trailing = tester.renderObject<RenderBox>(find.byType(FloatingActionButton).at(1));
expect(leading.localToGlobal(Offset.zero), Offset((72 - leading.size.width) / 2.0, 8.0));
expect(trailing.localToGlobal(Offset.zero), Offset((72 - trailing.size.width) / 2.0, 360.0));
});
testWidgets('Extended rail animates the width and labels appear - [textDirection]=LTR', (WidgetTester tester) async {
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
final RenderBox rail = tester.firstRenderObject<RenderBox>(find.byType(NavigationRail));
expect(rail.size.width, equals(72.0));
stateSetter(() {
extended = true;
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(rail.size.width, equals(164.0));
await tester.pumpAndSettle();
expect(rail.size.width, equals(256.0));
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
72.0,
nextDestinationY + (72.0 - firstLabelRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
final RenderBox secondLabelRenderBox = _labelRenderBox(tester, 'Def');
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
expect(
secondLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
72.0,
nextDestinationY + (72.0 - secondLabelRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
final RenderBox thirdLabelRenderBox = _labelRenderBox(tester, 'Ghi');
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
expect(
thirdLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
72.0,
nextDestinationY + (72.0 - thirdLabelRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
final RenderBox fourthLabelRenderBox = _labelRenderBox(tester, 'Jkl');
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
(72.0 - fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
expect(
fourthLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
72.0,
nextDestinationY + (72.0 - fourthLabelRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Extended rail animates the width and labels appear - [textDirection]=RTL', (WidgetTester tester) async {
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: Row(
textDirection: TextDirection.rtl,
children: <Widget>[
NavigationRail(
selectedIndex: 0,
destinations: _destinations(),
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
),
);
},
),
),
);
final RenderBox rail = tester.firstRenderObject<RenderBox>(find.byType(NavigationRail));
expect(rail.size.width, equals(72.0));
expect(rail.localToGlobal(Offset.zero), equals(const Offset(728.0, 0.0)));
stateSetter(() {
extended = true;
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(rail.size.width, equals(164.0));
expect(rail.localToGlobal(Offset.zero), equals(const Offset(636.0, 0.0)));
await tester.pumpAndSettle();
expect(rail.size.width, equals(256.0));
expect(rail.localToGlobal(Offset.zero), equals(const Offset(544.0, 0.0)));
// The first destination is 8 from the top because of the default vertical
// padding at the to of the rail.
double nextDestinationY = 8.0;
final RenderBox firstIconRenderBox = _iconRenderBox(tester, Icons.favorite);
final RenderBox firstLabelRenderBox = _labelRenderBox(tester, 'Abc');
expect(
firstIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - (72.0 + firstIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - firstIconRenderBox.size.height) / 2.0,
),
),
);
expect(
firstLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - 72.0 - firstLabelRenderBox.size.width,
nextDestinationY + (72.0 - firstLabelRenderBox.size.height) / 2.0,
),
),
);
// The second destination is 72 below the first destination.
nextDestinationY += 72.0;
final RenderBox secondIconRenderBox = _iconRenderBox(tester, Icons.bookmark_border);
final RenderBox secondLabelRenderBox = _labelRenderBox(tester, 'Def');
expect(
secondIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - (72.0 + secondIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - secondIconRenderBox.size.height) / 2.0,
),
),
);
expect(
secondLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - 72.0 - secondLabelRenderBox.size.width,
nextDestinationY + (72.0 - secondLabelRenderBox.size.height) / 2.0,
),
),
);
// The third destination is 72 below the second destination.
nextDestinationY += 72.0;
final RenderBox thirdIconRenderBox = _iconRenderBox(tester, Icons.star_border);
final RenderBox thirdLabelRenderBox = _labelRenderBox(tester, 'Ghi');
expect(
thirdIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - (72.0 + thirdIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - thirdIconRenderBox.size.height) / 2.0,
),
),
);
expect(
thirdLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - 72.0 - thirdLabelRenderBox.size.width,
nextDestinationY + (72.0 - thirdLabelRenderBox.size.height) / 2.0,
),
),
);
// The fourth destination is 72 below the third destination.
nextDestinationY += 72.0;
final RenderBox fourthIconRenderBox = _iconRenderBox(tester, Icons.hotel);
final RenderBox fourthLabelRenderBox = _labelRenderBox(tester, 'Jkl');
expect(
fourthIconRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - (72.0 + fourthIconRenderBox.size.width) / 2.0,
nextDestinationY + (72.0 - fourthIconRenderBox.size.height) / 2.0,
),
),
);
expect(
fourthLabelRenderBox.localToGlobal(Offset.zero),
equals(
Offset(
800.0 - 72.0 - fourthLabelRenderBox.size.width,
nextDestinationY + (72.0 - fourthLabelRenderBox.size.height) / 2.0,
),
),
);
});
testWidgets('Extended rail gets wider with longer labels are larger text scale', (WidgetTester tester) async {
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
MediaQuery.withClampedTextScaling(
minScaleFactor: 3.0,
maxScaleFactor: 3.0,
child: NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Longer Label'),
),
],
extended: extended,
),
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
final RenderBox rail = tester.firstRenderObject<RenderBox>(find.byType(NavigationRail));
expect(rail.size.width, equals(72.0));
stateSetter(() {
extended = true;
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(rail.size.width, equals(328.0));
await tester.pumpAndSettle();
expect(rail.size.width, equals(584.0));
});
testWidgets('Extended rail final width can be changed', (WidgetTester tester) async {
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 0,
minExtendedWidth: 300,
destinations: _destinations(),
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
final RenderBox rail = tester.firstRenderObject<RenderBox>(find.byType(NavigationRail));
expect(rail.size.width, equals(72.0));
stateSetter(() {
extended = true;
});
await tester.pumpAndSettle();
expect(rail.size.width, equals(300.0));
});
/// Regression test for https://github.com/flutter/flutter/issues/65657
testWidgets('Extended rail transition does not jump from the beginning', (WidgetTester tester) async {
bool extended = false;
late StateSetter stateSetter;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Longer Label'),
),
],
extended: extended,
),
const Expanded(
child: Text('body'),
),
],
),
);
},
),
),
);
final Finder rail = find.byType(NavigationRail);
// Before starting the animation, the rail has a width of 72.
expect(tester.getSize(rail).width, 72.0);
stateSetter(() {
extended = true;
});
await tester.pump();
// Create very close to 0, but non-zero, animation value.
await tester.pump(const Duration(milliseconds: 1));
// Expect that it has started to extend.
expect(tester.getSize(rail).width, greaterThan(72.0));
// Expect that it has only extended by a small amount, or that the first
// frame does not jump. This helps verify that it is a smooth animation.
expect(tester.getSize(rail).width, closeTo(72.0, 1.0));
});
testWidgets('NavigationRailDestination adds circular indicator when no labels are present', (WidgetTester tester) async {
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
useIndicator: true,
labelType: NavigationRailLabelType.none,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
),
],
),
);
final NavigationIndicator indicator = tester.widget<NavigationIndicator>(find.byType(NavigationIndicator).first);
expect(indicator.width, 56);
expect(indicator.height, 56);
});
testWidgets('NavigationRailDestination has center aligned indicator - [labelType]=none', (WidgetTester tester) async {
// This is a regression test for
// https://github.com/flutter/flutter/issues/97753
await _pumpNavigationRail(
tester,
useMaterial3: false,
navigationRail: NavigationRail(
labelType: NavigationRailLabelType.none,
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Stack(
children: <Widget>[
Icon(Icons.umbrella),
Positioned(
top: 0,
right: 0,
child: Text(
'Text',
style: TextStyle(fontSize: 10, color: Colors.red),
),
),
],
),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.umbrella),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
label: Text('Ghi'),
),
],
),
);
// Indicator with Stack widget
final RenderBox firstIndicator = tester.renderObject(find.byType(Icon).first);
expect(firstIndicator.localToGlobal(Offset.zero).dx, 24.0);
// Indicator without Stack widget
final RenderBox lastIndicator = tester.renderObject(find.byType(Icon).last);
expect(lastIndicator.localToGlobal(Offset.zero).dx, 24.0);
});
testWidgets('NavigationRail respects the notch/system navigation bar in landscape mode', (WidgetTester tester) async {
const double safeAreaPadding = 40.0;
NavigationRail navigationRail() {
return NavigationRail(
selectedIndex: 0,
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
],
);
}
await tester.pumpWidget(_buildWidget(navigationRail(), useMaterial3: false));
final double defaultWidth = tester.getSize(find.byType(NavigationRail)).width;
expect(defaultWidth, 72);
await tester.pumpWidget(
_buildWidget(
MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.only(left: safeAreaPadding),
),
child: navigationRail(),
),
useMaterial3: false
),
);
final double updatedWidth = tester.getSize(find.byType(NavigationRail)).width;
expect(updatedWidth, defaultWidth + safeAreaPadding);
// test width when text direction is RTL.
await tester.pumpWidget(
_buildWidget(
MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.only(right: safeAreaPadding),
),
child: navigationRail(),
),
useMaterial3: false,
isRTL: true,
),
);
final double updatedWidthRTL = tester.getSize(find.byType(NavigationRail)).width;
expect(updatedWidthRTL, defaultWidth + safeAreaPadding);
});
}); // End Material 2 group
}
TestSemantics _expectedSemantics() {
return TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isSelected,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'Abc\nTab 1 of 4',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isFocusable],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'Def\nTab 2 of 4',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isFocusable],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'Ghi\nTab 3 of 4',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isFocusable],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'Jkl\nTab 4 of 4',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'body',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
],
);
}
List<NavigationRailDestination> _destinations() {
return const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('Abc'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.bookmark),
label: Text('Def'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Ghi'),
),
NavigationRailDestination(
icon: Icon(Icons.hotel),
selectedIcon: Icon(Icons.home),
label: Text('Jkl'),
),
];
}
Future<void> _pumpNavigationRail(
WidgetTester tester, {
double textScaleFactor = 1.0,
required NavigationRail navigationRail,
bool useMaterial3 = true,
NavigationRailThemeData? navigationRailTheme,
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: useMaterial3,
navigationRailTheme: navigationRailTheme,
),
home: Builder(
builder: (BuildContext context) {
return MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor,
maxScaleFactor: textScaleFactor,
child: Scaffold(
body: Row(
children: <Widget>[
navigationRail,
const Expanded(
child: Text('body'),
),
],
),
),
);
},
),
),
);
}
Future<void> _pumpLocalizedTestRail(WidgetTester tester, { NavigationRailLabelType? labelType, bool extended = false }) async {
await tester.pumpWidget(
Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: MaterialApp(
home: Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: 0,
extended: extended,
destinations: _destinations(),
labelType: labelType,
),
const Expanded(
child: Text('body'),
),
],
),
),
),
),
);
}
RenderBox _iconRenderBox(WidgetTester tester, IconData iconData) {
return tester.firstRenderObject<RenderBox>(
find.descendant(
of: find.byIcon(iconData),
matching: find.byType(RichText),
),
);
}
RenderBox _labelRenderBox(WidgetTester tester, String text) {
return tester.firstRenderObject<RenderBox>(
find.descendant(
of: find.text(text),
matching: find.byType(RichText),
),
);
}
TextStyle _iconStyle(WidgetTester tester, IconData icon) {
return tester.widget<RichText>(
find.descendant(
of: find.byIcon(icon),
matching: find.byType(RichText),
),
).text.style!;
}
Finder _opacityAboveLabel(String text) {
return find.ancestor(
of: find.text(text),
matching: find.byType(Opacity),
);
}
// Only valid when labelType != all.
double? _labelOpacity(WidgetTester tester, String text) {
// We search for both Visibility and FadeTransition since in some
// cases opacity is animated, in other it's not.
final Iterable<Visibility> visibilityWidgets = tester.widgetList<Visibility>(find.ancestor(
of: find.text(text),
matching: find.byType(Visibility),
));
if (visibilityWidgets.isNotEmpty) {
return visibilityWidgets.single.visible ? 1.0 : 0.0;
}
final FadeTransition fadeTransitionWidget = tester.widget<FadeTransition>(
find.ancestor(
of: find.text(text),
matching: find.byType(FadeTransition),
).first, // first because there's also a FadeTransition from the MaterialPageRoute, which is up the tree
);
return fadeTransitionWidget.opacity.value;
}
Material _railMaterial(WidgetTester tester) {
// The first material is for the rail, and the rest are for the destinations.
return tester.firstWidget<Material>(
find.descendant(
of: find.byType(NavigationRail),
matching: find.byType(Material),
),
);
}
Widget _buildWidget(Widget child, {bool useMaterial3 = true, bool isRTL = false}) {
return MaterialApp(
theme: ThemeData(useMaterial3: useMaterial3),
home: Directionality(
textDirection: isRTL ? TextDirection.rtl : TextDirection.ltr,
child: Scaffold(
body: Row(
children: <Widget>[
child,
const Expanded(
child: Text('body'),
),
],
),
),
),
);
}
ShapeDecoration? _getIndicatorDecoration(WidgetTester tester) {
return tester.firstWidget<Container>(
find.descendant(
of: find.byType(FadeTransition),
matching: find.byType(Container),
),
).decoration as ShapeDecoration?;
}
| flutter/packages/flutter/test/material/navigation_rail_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/navigation_rail_test.dart",
"repo_id": "flutter",
"token_count": 85569
} | 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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/src/physics/utils.dart' show nearEqual;
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
// Regression test for https://github.com/flutter/flutter/issues/105833
testWidgets('Drag gesture uses provided gesture settings', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.1, 0.5);
bool dragStarted = false;
final Key sliderKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: GestureDetector(
behavior: HitTestBehavior.deferToChild,
onHorizontalDragStart: (DragStartDetails details) {
dragStarted = true;
},
child: MediaQuery(
data: MediaQuery.of(context).copyWith(gestureSettings: const DeviceGestureSettings(touchSlop: 20)),
child: RangeSlider(
key: sliderKey,
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
),
),
);
},
),
),
),
);
TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(sliderKey)));
await tester.pump(kPressTimeout);
// Less than configured touch slop, more than default touch slop
await drag.moveBy(const Offset(19.0, 0));
await tester.pump();
expect(values, const RangeValues(0.1, 0.5));
expect(dragStarted, true);
dragStarted = false;
await drag.up();
await tester.pumpAndSettle();
drag = await tester.startGesture(tester.getCenter(find.byKey(sliderKey)));
await tester.pump(kPressTimeout);
bool sliderEnd = false;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: GestureDetector(
behavior: HitTestBehavior.deferToChild,
onHorizontalDragStart: (DragStartDetails details) {
dragStarted = true;
},
child: MediaQuery(
data: MediaQuery.of(context).copyWith(gestureSettings: const DeviceGestureSettings(touchSlop: 10)),
child: RangeSlider(
key: sliderKey,
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
onChangeEnd: (RangeValues newValues) {
sliderEnd = true;
},
),
),
),
),
);
},
),
),
),
);
// More than touch slop.
await drag.moveBy(const Offset(12.0, 0));
await drag.up();
await tester.pumpAndSettle();
expect(sliderEnd, true);
expect(dragStarted, false);
});
testWidgets('Range Slider can move when tapped (continuous LTR)', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// No thumbs get select when tapping between the thumbs outside the touch
// boundaries
expect(values, equals(const RangeValues(0.3, 0.7)));
// taps at 0.5
await tester.tap(find.byType(RangeSlider));
await tester.pump();
expect(values, equals(const RangeValues(0.3, 0.7)));
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// The start thumb is selected when tapping the left inactive track.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.1;
await tester.tapAt(leftTarget);
expect(values.start, moreOrLessEquals(0.1, epsilon: 0.01));
expect(values.end, equals(0.7));
// The end thumb is selected when tapping the right inactive track.
await tester.pump();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.9;
await tester.tapAt(rightTarget);
expect(values.start, moreOrLessEquals(0.1, epsilon: 0.01));
expect(values.end, moreOrLessEquals(0.9, epsilon: 0.01));
});
testWidgets('Range Slider can move when tapped (continuous RTL)', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// No thumbs get select when tapping between the thumbs outside the touch
// boundaries
expect(values, equals(const RangeValues(0.3, 0.7)));
// taps at 0.5
await tester.tap(find.byType(RangeSlider));
await tester.pump();
expect(values, equals(const RangeValues(0.3, 0.7)));
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// The end thumb is selected when tapping the left inactive track.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.1;
await tester.tapAt(leftTarget);
expect(values.start, 0.3);
expect(values.end, moreOrLessEquals(0.9, epsilon: 0.01));
// The start thumb is selected when tapping the right inactive track.
await tester.pump();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.9;
await tester.tapAt(rightTarget);
expect(values.start, moreOrLessEquals(0.1, epsilon: 0.01));
expect(values.end, moreOrLessEquals(0.9, epsilon: 0.01));
});
testWidgets('Range Slider can move when tapped (discrete LTR)', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100.0,
divisions: 10,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// No thumbs get select when tapping between the thumbs outside the touch
// boundaries
expect(values, equals(const RangeValues(30, 70)));
// taps at 0.5
await tester.tap(find.byType(RangeSlider));
await tester.pumpAndSettle();
expect(values, equals(const RangeValues(30, 70)));
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// The start thumb is selected when tapping the left inactive track.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.1;
await tester.tapAt(leftTarget);
await tester.pumpAndSettle();
expect(values.start.round(), equals(10));
expect(values.end.round(), equals(70));
// The end thumb is selected when tapping the right inactive track.
await tester.pump();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.9;
await tester.tapAt(rightTarget);
await tester.pumpAndSettle();
expect(values.start.round(), equals(10));
expect(values.end.round(), equals(90));
});
testWidgets('Range Slider can move when tapped (discrete RTL)', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
divisions: 10,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// No thumbs get select when tapping between the thumbs outside the touch
// boundaries
expect(values, equals(const RangeValues(30, 70)));
// taps at 0.5
await tester.tap(find.byType(RangeSlider));
await tester.pumpAndSettle();
expect(values, equals(const RangeValues(30, 70)));
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// The start thumb is selected when tapping the left inactive track.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.1;
await tester.tapAt(leftTarget);
await tester.pumpAndSettle();
expect(values.start.round(), equals(30));
expect(values.end.round(), equals(90));
// The end thumb is selected when tapping the right inactive track.
await tester.pump();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.9;
await tester.tapAt(rightTarget);
await tester.pumpAndSettle();
expect(values.start.round(), equals(10));
expect(values.end.round(), equals(90));
});
testWidgets('Range Slider thumbs can be dragged to the min and max (continuous LTR)', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// Drag the start thumb to the min.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, topLeft + (bottomRight - topLeft) * -0.4);
expect(values.start, equals(0));
// Drag the end thumb to the max.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, topLeft + (bottomRight - topLeft) * 0.4);
expect(values.end, equals(1));
});
testWidgets('Range Slider thumbs can be dragged to the min and max (continuous RTL)', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// Drag the end thumb to the max.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, topLeft + (bottomRight - topLeft) * -0.4);
expect(values.end, equals(1));
// Drag the start thumb to the min.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, topLeft + (bottomRight - topLeft) * 0.4);
expect(values.start, equals(0));
});
testWidgets('Range Slider thumbs can be dragged to the min and max (discrete LTR)', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
divisions: 10,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// Drag the start thumb to the min.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, topLeft + (bottomRight - topLeft) * -0.4);
expect(values.start, equals(0));
// Drag the end thumb to the max.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, topLeft + (bottomRight - topLeft) * 0.4);
expect(values.end, equals(100));
});
testWidgets('Range Slider thumbs can be dragged to the min and max (discrete RTL)', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
divisions: 10,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// Drag the end thumb to the max.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, topLeft + (bottomRight - topLeft) * -0.4);
expect(values.end, equals(100));
// Drag the start thumb to the min.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, topLeft + (bottomRight - topLeft) * 0.4);
expect(values.start, equals(0));
});
testWidgets('Range Slider thumbs can be dragged together and the start thumb can be dragged apart (continuous LTR)', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the start thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
expect(values.start, moreOrLessEquals(0.5, epsilon: 0.05));
// Drag the end thumb towards the center.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.end, moreOrLessEquals(0.5, epsilon: 0.05));
// Drag the start thumb apart.
await tester.pumpAndSettle();
await tester.dragFrom(middle, -(bottomRight - topLeft) * 0.3);
expect(values.start, moreOrLessEquals(0.2, epsilon: 0.05));
});
testWidgets('Range Slider thumbs can be dragged together and the start thumb can be dragged apart (continuous RTL)', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the end thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
expect(values.end, moreOrLessEquals(0.5, epsilon: 0.05));
// Drag the start thumb towards the center.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.start, moreOrLessEquals(0.5, epsilon: 0.05));
// Drag the start thumb apart.
await tester.pumpAndSettle();
await tester.dragFrom(middle, (bottomRight - topLeft) * 0.3);
expect(values.start, moreOrLessEquals(0.2, epsilon: 0.05));
});
testWidgets('Range Slider thumbs can be dragged together and the start thumb can be dragged apart (discrete LTR)', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
divisions: 10,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the start thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
expect(values.start, moreOrLessEquals(50, epsilon: 0.01));
// Drag the end thumb towards the center.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.end, moreOrLessEquals(50, epsilon: 0.01));
// Drag the start thumb apart.
await tester.pumpAndSettle();
await tester.dragFrom(middle, -(bottomRight - topLeft) * 0.3);
expect(values.start, moreOrLessEquals(20, epsilon: 0.01));
});
testWidgets('Range Slider thumbs can be dragged together and the start thumb can be dragged apart (discrete RTL)', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
divisions: 10,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the end thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
expect(values.end, moreOrLessEquals(50, epsilon: 0.01));
// Drag the start thumb towards the center.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.start, moreOrLessEquals(50, epsilon: 0.01));
// Drag the start thumb apart.
await tester.pumpAndSettle();
await tester.dragFrom(middle, (bottomRight - topLeft) * 0.3);
expect(values.start, moreOrLessEquals(20, epsilon: 0.01));
});
testWidgets('Range Slider thumbs can be dragged together and the end thumb can be dragged apart (continuous LTR)', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the start thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
expect(values.start, moreOrLessEquals(0.5, epsilon: 0.05));
// Drag the end thumb towards the center.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.end, moreOrLessEquals(0.5, epsilon: 0.05));
// Drag the end thumb apart.
await tester.pumpAndSettle();
await tester.dragFrom(middle, (bottomRight - topLeft) * 0.3);
expect(values.end, moreOrLessEquals(0.8, epsilon: 0.05));
});
testWidgets('Range Slider thumbs can be dragged together and the end thumb can be dragged apart (continuous RTL)', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the end thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
expect(values.end, moreOrLessEquals(0.5, epsilon: 0.05));
// Drag the start thumb towards the center.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.start, moreOrLessEquals(0.5, epsilon: 0.05));
// Drag the end thumb apart.
await tester.pumpAndSettle();
await tester.dragFrom(middle, -(bottomRight - topLeft) * 0.3);
expect(values.end, moreOrLessEquals(0.8, epsilon: 0.05));
});
testWidgets('Range Slider thumbs can be dragged together and the end thumb can be dragged apart (discrete LTR)', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
divisions: 10,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the start thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
expect(values.start, moreOrLessEquals(50, epsilon: 0.01));
// Drag the end thumb towards the center.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.end, moreOrLessEquals(50, epsilon: 0.01));
// Drag the end thumb apart.
await tester.pumpAndSettle();
await tester.dragFrom(middle, (bottomRight - topLeft) * 0.3);
expect(values.end, moreOrLessEquals(80, epsilon: 0.01));
});
testWidgets('Range Slider thumbs can be dragged together and the end thumb can be dragged apart (discrete RTL)', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
divisions: 10,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the end thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
expect(values.end, moreOrLessEquals(50, epsilon: 0.01));
// Drag the start thumb towards the center.
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.start, moreOrLessEquals(50, epsilon: 0.01));
// Drag the end thumb apart.
await tester.pumpAndSettle();
await tester.dragFrom(middle, -(bottomRight - topLeft) * 0.3);
expect(values.end, moreOrLessEquals(80, epsilon: 0.01));
});
testWidgets('Range Slider onChangeEnd and onChangeStart are called on an interaction initiated by tap', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
RangeValues? startValues;
RangeValues? endValues;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
onChangeStart: (RangeValues newValues) {
startValues = newValues;
},
onChangeEnd: (RangeValues newValues) {
endValues = newValues;
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// Drag the start thumb towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
expect(startValues, null);
expect(endValues, null);
await tester.dragFrom(leftTarget, (bottomRight - topLeft) * 0.2);
expect(startValues!.start, moreOrLessEquals(30, epsilon: 1));
expect(startValues!.end, moreOrLessEquals(70, epsilon: 1));
expect(values.start, moreOrLessEquals(50, epsilon: 1));
expect(values.end, moreOrLessEquals(70, epsilon: 1));
expect(endValues!.start, moreOrLessEquals(50, epsilon: 1));
expect(endValues!.end, moreOrLessEquals(70, epsilon: 1));
});
testWidgets('Range Slider onChangeEnd and onChangeStart are called on an interaction initiated by drag', (WidgetTester tester) async {
RangeValues values = const RangeValues(30, 70);
late RangeValues startValues;
late RangeValues endValues;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
onChangeStart: (RangeValues newValues) {
startValues = newValues;
},
onChangeEnd: (RangeValues newValues) {
endValues = newValues;
},
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
// Drag the thumbs together.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, (bottomRight - topLeft) * 0.2);
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, (bottomRight - topLeft) * -0.2);
await tester.pumpAndSettle();
expect(values.start, moreOrLessEquals(50, epsilon: 1));
expect(values.end, moreOrLessEquals(51, epsilon: 1));
// Drag the end thumb to the right.
final Offset middleTarget = topLeft + (bottomRight - topLeft) * 0.5;
await tester.dragFrom(middleTarget, (bottomRight - topLeft) * 0.4);
await tester.pumpAndSettle();
expect(startValues.start, moreOrLessEquals(50, epsilon: 1));
expect(startValues.end, moreOrLessEquals(51, epsilon: 1));
expect(endValues.start, moreOrLessEquals(50, epsilon: 1));
expect(endValues.end, moreOrLessEquals(90, epsilon: 1));
});
ThemeData buildTheme() {
return ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
sliderTheme: const SliderThemeData(
disabledThumbColor: Color(0xff000001),
disabledActiveTickMarkColor: Color(0xff000002),
disabledActiveTrackColor: Color(0xff000003),
disabledInactiveTickMarkColor: Color(0xff000004),
disabledInactiveTrackColor: Color(0xff000005),
activeTrackColor: Color(0xff000006),
activeTickMarkColor: Color(0xff000007),
inactiveTrackColor: Color(0xff000008),
inactiveTickMarkColor: Color(0xff000009),
overlayColor: Color(0xff000010),
thumbColor: Color(0xff000011),
valueIndicatorColor: Color(0xff000012),
),
);
}
Widget buildThemedApp({
required ThemeData theme,
Color? activeColor,
Color? inactiveColor,
int? divisions,
bool enabled = true,
}) {
RangeValues values = const RangeValues(0.5, 0.75);
final ValueChanged<RangeValues>? onChanged = !enabled ? null : (RangeValues newValues) {
values = newValues;
};
return MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Theme(
data: theme,
child: RangeSlider(
values: values,
labels: RangeLabels(values.start.toStringAsFixed(2), values.end.toStringAsFixed(2)),
divisions: divisions,
activeColor: activeColor,
inactiveColor: inactiveColor,
onChanged: onChanged,
),
),
),
),
),
);
}
testWidgets('Range Slider uses the right theme colors for the right shapes for a default enabled slider', (WidgetTester tester) async {
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(buildThemedApp(theme: theme));
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
// Check default theme for enabled widget.
expect(
sliderBox,
paints
..rrect(color: sliderTheme.inactiveTrackColor)
..rect(color: sliderTheme.activeTrackColor)
..rrect(color: sliderTheme.inactiveTrackColor),
);
expect(
sliderBox,
paints
..circle(color: sliderTheme.thumbColor)
..circle(color: sliderTheme.thumbColor),
);
expect(sliderBox, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledActiveTrackColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledInactiveTrackColor)));
expect(sliderBox, isNot(paints..circle(color: sliderTheme.activeTickMarkColor)));
expect(sliderBox, isNot(paints..circle(color: sliderTheme.inactiveTickMarkColor)));
});
testWidgets('Range Slider uses the right theme colors for the right shapes when setting the active color', (WidgetTester tester) async {
const Color activeColor = Color(0xcafefeed);
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(buildThemedApp(theme: theme, activeColor: activeColor));
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
expect(
sliderBox,
paints
..rrect(color: sliderTheme.inactiveTrackColor)
..rect(color: activeColor)
..rrect(color: sliderTheme.inactiveTrackColor),
);
expect(
sliderBox,
paints
..circle(color: activeColor)
..circle(color: activeColor),
);
expect(sliderBox, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(sliderBox, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledActiveTrackColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledInactiveTrackColor)));
});
testWidgets('Range Slider uses the right theme colors for the right shapes when setting the inactive color', (WidgetTester tester) async {
const Color inactiveColor = Color(0xdeadbeef);
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(buildThemedApp(theme: theme, inactiveColor: inactiveColor));
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
expect(
sliderBox,
paints
..rrect(color: inactiveColor)
..rect(color: sliderTheme.activeTrackColor)
..rrect(color: inactiveColor),
);
expect(
sliderBox,
paints
..circle(color: sliderTheme.thumbColor)
..circle(color: sliderTheme.thumbColor),
);
expect(sliderBox, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledActiveTrackColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledInactiveTrackColor)));
});
testWidgets('Range Slider uses the right theme colors for the right shapes with active and inactive colors', (WidgetTester tester) async {
const Color activeColor = Color(0xcafefeed);
const Color inactiveColor = Color(0xdeadbeef);
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(buildThemedApp(
theme: theme,
activeColor: activeColor,
inactiveColor: inactiveColor,
));
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
expect(
sliderBox,
paints
..rrect(color: inactiveColor)
..rect(color: activeColor)
..rrect(color: inactiveColor),
);
expect(
sliderBox,
paints
..circle(color: activeColor)
..circle(color: activeColor),
);
expect(sliderBox, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(sliderBox, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledActiveTrackColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledInactiveTrackColor)));
});
testWidgets('Range Slider uses the right theme colors for the right shapes for a discrete slider', (WidgetTester tester) async {
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(buildThemedApp(theme: theme, divisions: 3));
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
expect(
sliderBox,
paints
..rrect(color: sliderTheme.inactiveTrackColor)
..rect(color: sliderTheme.activeTrackColor)
..rrect(color: sliderTheme.inactiveTrackColor),
);
expect(
sliderBox,
paints
..circle(color: sliderTheme.inactiveTickMarkColor)
..circle(color: sliderTheme.inactiveTickMarkColor)
..circle(color: sliderTheme.activeTickMarkColor)
..circle(color: sliderTheme.inactiveTickMarkColor)
..circle(color: sliderTheme.thumbColor)
..circle(color: sliderTheme.thumbColor),
);
expect(sliderBox, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledActiveTrackColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledInactiveTrackColor)));
});
testWidgets('Range Slider uses the right theme colors for the right shapes for a discrete slider with active and inactive colors', (WidgetTester tester) async {
const Color activeColor = Color(0xcafefeed);
const Color inactiveColor = Color(0xdeadbeef);
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(buildThemedApp(
theme: theme,
activeColor: activeColor,
inactiveColor: inactiveColor,
divisions: 3,
));
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
expect(
sliderBox,
paints
..rrect(color: inactiveColor)
..rect(color: activeColor)
..rrect(color: inactiveColor),
);
expect(
sliderBox,
paints
..circle(color: activeColor)
..circle(color: activeColor)
..circle(color: inactiveColor)
..circle(color: activeColor)
..circle(color: activeColor)
..circle(color: activeColor),
);
expect(sliderBox, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(sliderBox, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledActiveTrackColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.disabledInactiveTrackColor)));
expect(sliderBox, isNot(paints..circle(color: sliderTheme.activeTickMarkColor)));
expect(sliderBox, isNot(paints..circle(color: sliderTheme.inactiveTickMarkColor)));
});
testWidgets('Range Slider uses the right theme colors for the right shapes for a default disabled slider', (WidgetTester tester) async {
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(buildThemedApp(theme: theme, enabled: false));
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
expect(
sliderBox,
paints
..rrect(color: sliderTheme.disabledInactiveTrackColor)
..rect(color: sliderTheme.disabledActiveTrackColor)
..rrect(color: sliderTheme.disabledInactiveTrackColor),
);
expect(sliderBox, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.activeTrackColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.inactiveTrackColor)));
});
testWidgets('Range Slider uses the right theme colors for the right shapes for a disabled slider with active and inactive colors', (WidgetTester tester) async {
const Color activeColor = Color(0xcafefeed);
const Color inactiveColor = Color(0xdeadbeef);
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(buildThemedApp(
theme: theme,
activeColor: activeColor,
inactiveColor: inactiveColor,
enabled: false,
));
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
expect(
sliderBox,
paints
..rrect(color: sliderTheme.disabledInactiveTrackColor)
..rect(color: sliderTheme.disabledActiveTrackColor)
..rrect(color: sliderTheme.disabledInactiveTrackColor),
);
expect(sliderBox, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.activeTrackColor)));
expect(sliderBox, isNot(paints..rect(color: sliderTheme.inactiveTrackColor)));
});
testWidgets('Range Slider uses the right theme colors for the right shapes when the value indicators are showing', (WidgetTester tester) async {
final ThemeData theme = buildTheme();
final SliderThemeData sliderTheme = theme.sliderTheme;
RangeValues values = const RangeValues(0.5, 0.75);
Widget buildApp({
Color? activeColor,
Color? inactiveColor,
int? divisions,
bool enabled = true,
}) {
final ValueChanged<RangeValues>? onChanged = !enabled ? null : (RangeValues newValues) {
values = newValues;
};
return MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Theme(
data: theme,
child: RangeSlider(
values: values,
labels: RangeLabels(values.start.toStringAsFixed(2), values.end.toStringAsFixed(2)),
divisions: divisions,
activeColor: activeColor,
inactiveColor: inactiveColor,
onChanged: onChanged,
),
),
),
),
),
);
}
await tester.pumpWidget(buildApp(divisions: 3));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset topRight = tester.getTopRight(find.byType(RangeSlider)).translate(-24, 0);
final TestGesture gesture = await tester.startGesture(topRight);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(values.end, equals(1));
expect(
valueIndicatorBox,
paints
..path(color: Colors.black) // shadow
..path(color: Colors.black) // shadow
..path(color: sliderTheme.valueIndicatorColor)
..paragraph()
);
await gesture.up();
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
});
testWidgets('Range Slider removes value indicator from overlay if Slider gets disposed without value indicator animation completing.', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.5, 0.75);
const Color fillColor = Color(0xf55f5f5f);
Widget buildApp({
Color? activeColor,
Color? inactiveColor,
int? divisions,
bool enabled = true,
}) {
void onChanged(RangeValues newValues) {
values = newValues;
}
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
// The builder is used to pass the context from the MaterialApp widget
// to the [Navigator]. This context is required in order for the
// Navigator to work.
body: Builder(
builder: (BuildContext context) {
return Column(
children: <Widget>[
RangeSlider(
values: values,
labels: RangeLabels(
values.start.toStringAsFixed(2),
values.end.toStringAsFixed(2),
),
divisions: divisions,
onChanged: onChanged,
),
ElevatedButton(
child: const Text('Next'),
onPressed: () {
Navigator.of(context).pushReplacement(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('Inner page'),
onPressed: () { Navigator.of(context).pop(); },
);
},
),
);
},
),
],
);
},
),
),
);
}
await tester.pumpWidget(buildApp(divisions: 3));
final RenderObject valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset topRight = tester.getTopRight(find.byType(RangeSlider)).translate(-24, 0);
final TestGesture gesture = await tester.startGesture(topRight);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
// Represents the raised button wth next text.
..path(color: Colors.black)
..paragraph()
// Represents the range slider.
..path(color: fillColor)
..paragraph()
..path(color: fillColor)
..paragraph(),
);
// Represents the Raised Button and Range Slider.
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 6));
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawParagraph, 3));
await tester.tap(find.text('Next'));
await tester.pumpAndSettle();
expect(find.byType(RangeSlider), findsNothing);
expect(
valueIndicatorBox,
isNot(
paints
..path(color: fillColor)
..paragraph()
..path(color: fillColor)
..paragraph(),
),
);
// Represents the raised button with inner page text.
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 2));
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawParagraph, 1));
// Don't stop holding the value indicator.
await gesture.up();
await tester.pumpAndSettle();
});
testWidgets('Range Slider top thumb gets stroked when overlapping', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
sliderTheme: const SliderThemeData(
thumbColor: Color(0xff000001),
overlappingShapeStrokeColor: Color(0xff000002),
),
);
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Theme(
data: theme,
child: RangeSlider(
values: values,
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
),
);
},
),
),
),
);
final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the thumbs towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
expect(values.start, moreOrLessEquals(0.5, epsilon: 0.03));
expect(values.end, moreOrLessEquals(0.5, epsilon: 0.03));
await tester.pumpAndSettle();
expect(
sliderBox,
paints
..circle(color: sliderTheme.thumbColor)
..circle(color: sliderTheme.overlappingShapeStrokeColor)
..circle(color: sliderTheme.thumbColor),
);
});
testWidgets('Range Slider top value indicator gets stroked when overlapping', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
sliderTheme: const SliderThemeData(
valueIndicatorColor: Color(0xff000001),
overlappingShapeStrokeColor: Color(0xff000002),
showValueIndicator: ShowValueIndicator.always,
),
);
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Theme(
data: theme,
child: RangeSlider(
values: values,
labels: RangeLabels(values.start.toStringAsFixed(2), values.end.toStringAsFixed(2)),
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
),
);
},
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the thumbs towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
await tester.pumpAndSettle();
expect(values.start, moreOrLessEquals(0.5, epsilon: 0.03));
expect(values.end, moreOrLessEquals(0.5, epsilon: 0.03));
final TestGesture gesture = await tester.startGesture(middle);
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: Colors.black) // shadow
..path(color: Colors.black) // shadow
..path(color: sliderTheme.valueIndicatorColor)
..paragraph(),
);
await gesture.up();
});
testWidgets('Range Slider top value indicator gets stroked when overlapping with large text scale', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
sliderTheme: const SliderThemeData(
valueIndicatorColor: Color(0xff000001),
overlappingShapeStrokeColor: Color(0xff000002),
showValueIndicator: ShowValueIndicator.always,
),
);
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MediaQuery(
data: const MediaQueryData(textScaler: TextScaler.linear(2)),
child: Material(
child: Center(
child: Theme(
data: theme,
child: RangeSlider(
values: values,
labels: RangeLabels(values.start.toStringAsFixed(2), values.end.toStringAsFixed(2)),
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
),
),
);
},
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the thumbs towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
await tester.pumpAndSettle();
expect(values.start, moreOrLessEquals(0.5, epsilon: 0.03));
expect(values.end, moreOrLessEquals(0.5, epsilon: 0.03));
final TestGesture gesture = await tester.startGesture(middle);
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: Colors.black) // shadow
..path(color: Colors.black) // shadow
..path(color: sliderTheme.valueIndicatorColor)
..paragraph(),
);
await gesture.up();
});
testWidgets('Range Slider thumb gets stroked when overlapping', (WidgetTester tester) async {
RangeValues values = const RangeValues(0.3, 0.7);
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
sliderTheme: const SliderThemeData(
valueIndicatorColor: Color(0xff000001),
showValueIndicator: ShowValueIndicator.onlyForContinuous,
),
);
final SliderThemeData sliderTheme = theme.sliderTheme;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Theme(
data: theme,
child: RangeSlider(
values: values,
labels: RangeLabels(values.start.toStringAsFixed(2), values.end.toStringAsFixed(2)),
onChanged: (RangeValues newValues) {
setState(() {
values = newValues;
});
},
),
),
),
);
},
),
),
),
);
// Get the bounds of the track by finding the slider edges and translating
// inwards by the overlay radius.
final Offset topLeft = tester.getTopLeft(find.byType(RangeSlider)).translate(24, 0);
final Offset bottomRight = tester.getBottomRight(find.byType(RangeSlider)).translate(-24, 0);
final Offset middle = topLeft + bottomRight / 2;
// Drag the thumbs towards the center.
final Offset leftTarget = topLeft + (bottomRight - topLeft) * 0.3;
await tester.dragFrom(leftTarget, middle - leftTarget);
await tester.pumpAndSettle();
final Offset rightTarget = topLeft + (bottomRight - topLeft) * 0.7;
await tester.dragFrom(rightTarget, middle - rightTarget);
await tester.pumpAndSettle();
expect(values.start, moreOrLessEquals(0.5, epsilon: 0.03));
expect(values.end, moreOrLessEquals(0.5, epsilon: 0.03));
final TestGesture gesture = await tester.startGesture(middle);
await tester.pumpAndSettle();
/// The first circle is the thumb, the second one is the overlapping shape
/// circle, and the last one is the second thumb.
expect(
find.byType(RangeSlider),
paints
..circle()
..circle(color: sliderTheme.overlappingShapeStrokeColor)
..circle(),
);
await gesture.up();
expect(
find.byType(RangeSlider),
paints
..circle()
..circle(color: sliderTheme.overlappingShapeStrokeColor)
..circle(),
);
});
// Regression test for https://github.com/flutter/flutter/issues/101868
testWidgets('RangeSlider.label info should not write to semantic node', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Theme(
data: ThemeData.light(),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: RangeSlider(
values: const RangeValues(10.0, 12.0),
max: 100.0,
onChanged: (RangeValues v) { },
labels: const RangeLabels('Begin', 'End'),
),
),
),
),
),
);
await tester.pumpAndSettle();
expect(
tester.getSemantics(find.byType(RangeSlider)),
matchesSemantics(
scopesRoute: true,
children:<Matcher>[
matchesSemantics(
children: <Matcher>[
matchesSemantics(
isEnabled: true,
isSlider: true,
hasEnabledState: true,
hasIncreaseAction: true,
hasDecreaseAction: true,
value: '10%',
increasedValue: '10%',
decreasedValue: '5%',
label: ''
),
matchesSemantics(
isEnabled: true,
isSlider: true,
hasEnabledState: true,
hasIncreaseAction: true,
hasDecreaseAction: true,
value: '12%',
increasedValue: '17%',
decreasedValue: '12%',
label: ''
),
],
),
],
),
);
});
testWidgets('Range Slider Semantics - ltr', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Theme(
data: ThemeData.light(),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: RangeSlider(
values: const RangeValues(10.0, 30.0),
max: 100.0,
onChanged: (RangeValues v) { },
),
),
),
),
),
);
await tester.pumpAndSettle();
final SemanticsNode semanticsNode = tester.getSemantics(find.byType(RangeSlider));
expect(
semanticsNode,
matchesSemantics(
scopesRoute: true,
children:<Matcher>[
matchesSemantics(
children: <Matcher>[
matchesSemantics(
isEnabled: true,
isSlider: true,
hasEnabledState: true,
hasIncreaseAction: true,
hasDecreaseAction: true,
value: '10%',
increasedValue: '15%',
decreasedValue: '5%',
rect: const Rect.fromLTRB(75.2, 276.0, 123.2, 324.0),
),
matchesSemantics(
isEnabled: true,
isSlider: true,
hasEnabledState: true,
hasIncreaseAction: true,
hasDecreaseAction: true,
value: '30%',
increasedValue: '35%',
decreasedValue: '25%',
rect: const Rect.fromLTRB(225.6, 276.0, 273.6, 324.0),
),
],
),
],
),
);
// TODO(tahatesser): This is a workaround for matching
// the semantics node rects by avoiding floating point errors.
// https://github.com/flutter/flutter/issues/115079
// Get semantics node rects.
final List<Rect> rects = <Rect>[];
semanticsNode.visitChildren((SemanticsNode node) {
node.visitChildren((SemanticsNode node) {
// Round rect values to avoid floating point errors.
rects.add(
Rect.fromLTRB(
node.rect.left.roundToDouble(),
node.rect.top.roundToDouble(),
node.rect.right.roundToDouble(),
node.rect.bottom.roundToDouble(),
),
);
return true;
});
return true;
});
// Test that the semantics node rect sizes are correct.
expect(rects, <Rect>[
const Rect.fromLTRB(75.0, 276.0, 123.0, 324.0),
const Rect.fromLTRB(226.0, 276.0, 274.0, 324.0)
]);
});
testWidgets('Range Slider Semantics - rtl', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Theme(
data: ThemeData.light(),
child: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: RangeSlider(
values: const RangeValues(10.0, 30.0),
max: 100.0,
onChanged: (RangeValues v) { },
),
),
),
),
),
);
await tester.pumpAndSettle();
final SemanticsNode semanticsNode = tester.getSemantics(find.byType(RangeSlider));
expect(
semanticsNode,
matchesSemantics(
scopesRoute: true,
children:<Matcher>[
matchesSemantics(
children: <Matcher>[
matchesSemantics(
isEnabled: true,
isSlider: true,
hasEnabledState: true,
hasIncreaseAction: true,
hasDecreaseAction: true,
value: '10%',
increasedValue: '15%',
decreasedValue: '5%',
),
matchesSemantics(
isEnabled: true,
isSlider: true,
hasEnabledState: true,
hasIncreaseAction: true,
hasDecreaseAction: true,
value: '30%',
increasedValue: '35%',
decreasedValue: '25%',
),
],
),
],
),
);
// TODO(tahatesser): This is a workaround for matching
// the semantics node rects by avoiding floating point errors.
// https://github.com/flutter/flutter/issues/115079
// Get semantics node rects.
final List<Rect> rects = <Rect>[];
semanticsNode.visitChildren((SemanticsNode node) {
node.visitChildren((SemanticsNode node) {
// Round rect values to avoid floating point errors.
rects.add(
Rect.fromLTRB(
node.rect.left.roundToDouble(),
node.rect.top.roundToDouble(),
node.rect.right.roundToDouble(),
node.rect.bottom.roundToDouble(),
),
);
return true;
});
return true;
});
// Test that the semantics node rect sizes are correct.
expect(rects, <Rect>[
const Rect.fromLTRB(526.0, 276.0, 574.0, 324.0),
const Rect.fromLTRB(677.0, 276.0, 725.0, 324.0)
]);
});
testWidgets('Range Slider implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
RangeSlider(
activeColor: Colors.blue,
divisions: 4,
inactiveColor: Colors.grey,
labels: const RangeLabels('lowerValue', 'upperValue'),
max: 100.0,
onChanged: null,
values: const RangeValues(25.0, 75.0),
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
expect(description, <String>[
'valueStart: 25.0',
'valueEnd: 75.0',
'disabled',
'min: 0.0',
'max: 100.0',
'divisions: 4',
'labelStart: "lowerValue"',
'labelEnd: "upperValue"',
'activeColor: MaterialColor(primary value: Color(0xff2196f3))',
'inactiveColor: MaterialColor(primary value: Color(0xff9e9e9e))',
]);
});
testWidgets('Range Slider can be painted in a narrower constraint when track shape is RoundedRectRange', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: SizedBox(
height: 10.0,
width: 0.0,
child: RangeSlider(
values: const RangeValues(0.25, 0.5),
onChanged: null,
),
),
),
),
),
),
);
// _RenderRangeSlider is the last render object in the tree.
final RenderObject renderObject = tester.allRenderObjects.last;
expect(
renderObject,
paints
// left inactive track RRect
..rrect(rrect: RRect.fromLTRBAndCorners(-24.0, 3.0, -12.0, 7.0, topLeft: const Radius.circular(2.0), bottomLeft: const Radius.circular(2.0)))
// active track RRect
..rect(rect: const Rect.fromLTRB(-12.0, 2.0, 0.0, 8.0))
// right inactive track RRect
..rrect(rrect: RRect.fromLTRBAndCorners(0.0, 3.0, 24.0, 7.0, topRight: const Radius.circular(2.0), bottomRight: const Radius.circular(2.0)))
// thumbs
..circle(x: -12.0, y: 5.0, radius: 10.0)
..circle(x: 0.0, y: 5.0, radius: 10.0),
);
});
testWidgets('Range Slider can be painted in a narrower constraint when track shape is Rectangular', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
sliderTheme: const SliderThemeData(
rangeTrackShape: RectangularRangeSliderTrackShape(),
),
),
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: SizedBox(
height: 10.0,
width: 0.0,
child: RangeSlider(
values: const RangeValues(0.25, 0.5),
onChanged: null,
),
),
),
),
),
),
);
// _RenderRangeSlider is the last render object in the tree.
final RenderObject renderObject = tester.allRenderObjects.last;
//There should no gap between the inactive track and active track.
expect(
renderObject,
paints
// left inactive track RRect
..rect(rect: const Rect.fromLTRB(-24.0, 3.0, -12.0, 7.0))
// active track RRect
..rect(rect: const Rect.fromLTRB(-12.0, 3.0, 0.0, 7.0))
// right inactive track RRect
..rect(rect: const Rect.fromLTRB(0.0, 3.0, 24.0, 7.0))
// thumbs
..circle(x: -12.0, y: 5.0, radius: 10.0)
..circle(x: 0.0, y: 5.0, radius: 10.0),
);
});
testWidgets('Update the divisions and values at the same time for RangeSlider', (WidgetTester tester) async {
// Regress test for https://github.com/flutter/flutter/issues/65943
Widget buildFrame(double maxValue) {
return MaterialApp(
home: Material(
child: Center(
child: RangeSlider(
values: const RangeValues(5, 8),
max: maxValue,
divisions: maxValue.toInt(),
onChanged: (RangeValues newValue) {},
),
),
),
);
}
await tester.pumpWidget(buildFrame(10));
// _RenderRangeSlider is the last render object in the tree.
final RenderObject renderObject = tester.allRenderObjects.last;
// Update the divisions from 10 to 15, the thumbs should be paint at the correct position.
await tester.pumpWidget(buildFrame(15));
await tester.pumpAndSettle(); // Finish the animation.
late Rect activeTrackRect;
expect(renderObject, paints..something((Symbol method, List<dynamic> arguments) {
if (method != #drawRect) {
return false;
}
activeTrackRect = arguments[0] as Rect;
return true;
}));
// The 1st thumb should at one-third(5 / 15) of the Slider.
// The 2nd thumb should at (8 / 15) of the Slider.
// The left of the active track shape is the position of the 1st thumb.
// The right of the active track shape is the position of the 2nd thumb.
// 24.0 is the default margin, (800.0 - 24.0 - 24.0) is the slider's width.
expect(nearEqual(activeTrackRect.left, (800.0 - 24.0 - 24.0) * (5 / 15) + 24.0, 0.01), true);
expect(nearEqual(activeTrackRect.right, (800.0 - 24.0 - 24.0) * (8 / 15) + 24.0, 0.01), true);
});
testWidgets('RangeSlider changes mouse cursor when hovered', (WidgetTester tester) async {
const RangeValues values = RangeValues(50, 70);
// Test default cursor.
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: RangeSlider(
values: values,
max: 100.0,
onChanged: (RangeValues values) {},
),
),
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(RangeSlider)));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test custom cursor.
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: RangeSlider(
values: values,
max: 100.0,
mouseCursor: const MaterialStatePropertyAll<MouseCursor?>(SystemMouseCursors.text),
onChanged: (RangeValues values) {},
),
),
),
),
),
),
);
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
});
testWidgets('RangeSlider MaterialStateMouseCursor resolves correctly', (WidgetTester tester) async {
RangeValues values = const RangeValues(50, 70);
const MouseCursor disabledCursor = SystemMouseCursors.basic;
const MouseCursor hoveredCursor = SystemMouseCursors.grab;
const MouseCursor draggedCursor = SystemMouseCursors.move;
Widget buildFrame({ required bool enabled }) {
return MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: RangeSlider(
mouseCursor: MaterialStateProperty.resolveWith<MouseCursor?>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return disabledCursor;
}
if (states.contains(MaterialState.dragged)) {
return draggedCursor;
}
if (states.contains(MaterialState.hovered)) {
return hoveredCursor;
}
return SystemMouseCursors.none;
},
),
values: values,
max: 100.0,
onChanged: enabled
? (RangeValues newValues) {
setState(() {
values = newValues;
});
}
: null,
onChangeStart: enabled ? (RangeValues newValues) {} : null,
onChangeEnd: enabled ? (RangeValues newValues) {} : null,
),
),
);
},
),
),
),
);
}
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: Offset.zero);
await tester.pumpWidget(buildFrame(enabled: false));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), disabledCursor);
await tester.pumpWidget(buildFrame(enabled: true));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.none);
await gesture.moveTo(tester.getCenter(find.byType(RangeSlider))); // start hover
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), hoveredCursor);
await tester.timedDrag(
find.byType(RangeSlider),
const Offset(20.0, 0.0),
const Duration(milliseconds: 100),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), draggedCursor);
});
testWidgets('RangeSlider can be hovered and has correct hover color', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
RangeValues values = const RangeValues(50, 70);
final ThemeData theme = ThemeData();
Widget buildApp({bool enabled = true}) {
return MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100.0,
onChanged: enabled
? (RangeValues newValues) {
setState(() {
values = newValues;
});
}
: null,
),
),
);
},
),
),
);
}
await tester.pumpWidget(buildApp());
// RangeSlider does not have overlay when enabled and not hovered.
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
isNot(paints..circle(color: theme.colorScheme.primary.withOpacity(0.12))),
);
// Start hovering.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(RangeSlider)));
// RangeSlider has overlay when enabled and hovered.
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
paints..circle(color: theme.colorScheme.primary.withOpacity(0.12)),
);
// RangeSlider does not have an overlay when disabled and hovered.
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
isNot(paints..circle(color: theme.colorScheme.primary.withOpacity(0.12))),
);
});
testWidgets('RangeSlider is draggable and has correct dragged color', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
RangeValues values = const RangeValues(50, 70);
final ThemeData theme = ThemeData();
Widget buildApp({bool enabled = true}) {
return MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100.0,
onChanged: enabled
? (RangeValues newValues) {
setState(() {
values = newValues;
});
}
: null,
),
),
);
},
),
),
);
}
await tester.pumpWidget(buildApp());
// RangeSlider does not have overlay when enabled and not dragged.
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
isNot(paints..circle(color: theme.colorScheme.primary.withOpacity(0.12))),
);
// Start dragging.
final TestGesture drag = await tester.startGesture(tester.getCenter(find.byType(RangeSlider)));
await tester.pump(kPressTimeout);
// Less than configured touch slop, more than default touch slop
await drag.moveBy(const Offset(19.0, 0));
await tester.pump();
// RangeSlider has overlay when enabled and dragged.
expect(
Material.of(tester.element(find.byType(RangeSlider))),
paints..circle(color: theme.colorScheme.primary.withOpacity(0.12)),
);
});
testWidgets('RangeSlider overlayColor supports hovered and dragged states', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
RangeValues values = const RangeValues(50, 70);
const Color hoverColor = Color(0xffff0000);
const Color draggedColor = Color(0xff0000ff);
Widget buildApp({bool enabled = true}) {
return MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: RangeSlider(
values: values,
max: 100.0,
overlayColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoverColor;
}
if (states.contains(MaterialState.dragged)) {
return draggedColor;
}
return null;
}),
onChanged: enabled
? (RangeValues newValues) {
setState(() {
values = newValues;
});
}
: null,
onChangeStart: enabled ? (RangeValues newValues) {} : null,
onChangeEnd: enabled ? (RangeValues newValues) {} : null,
),
),
);
},
),
),
);
}
await tester.pumpWidget(buildApp());
// RangeSlider does not have overlay when enabled and not hovered.
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
isNot(paints..circle(color: hoverColor)),
);
// Hover on the range slider but outside the thumb.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getTopLeft(find.byType(RangeSlider)));
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
isNot(paints..circle(color: hoverColor)),
);
// Hover on the thumb.
await gesture.moveTo(tester.getCenter(find.byType(RangeSlider)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
paints..circle(color: hoverColor),
);
// Hover on the slider but outside the thumb.
await gesture.moveTo(tester.getBottomRight(find.byType(RangeSlider)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
isNot(paints..circle(color: hoverColor)),
);
// Reset range slider values.
values = const RangeValues(50, 70);
// RangeSlider does not have overlay when enabled and not dragged.
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
isNot(paints..circle(color: draggedColor)),
);
// Start dragging.
final TestGesture drag = await tester.startGesture(tester.getCenter(find.byType(RangeSlider)));
await tester.pump(kPressTimeout);
// Less than configured touch slop, more than default touch slop.
await drag.moveBy(const Offset(19.0, 0));
await tester.pump();
// RangeSlider has overlay when enabled and dragged.
expect(
Material.of(tester.element(find.byType(RangeSlider))),
paints..circle(color: draggedColor),
);
// Stop dragging.
await drag.up();
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(RangeSlider))),
isNot(paints..circle(color: draggedColor)),
);
});
testWidgets('RangeSlider onChangeStart and onChangeEnd fire once', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/128433
int startFired = 0;
int endFired = 0;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: GestureDetector(
onHorizontalDragUpdate: (_) { },
child: RangeSlider(
values: const RangeValues(40, 80),
max: 100,
onChanged: (RangeValues newValue) { },
onChangeStart: (RangeValues value) {
startFired += 1;
},
onChangeEnd: (RangeValues value) {
endFired += 1;
},
),
),
),
),
),
),
);
await tester.timedDragFrom(
tester.getTopLeft(find.byType(RangeSlider)),
const Offset(100.0, 0.0),
const Duration(milliseconds: 500),
);
expect(startFired, equals(1));
expect(endFired, equals(1));
});
testWidgets('RangeSlider in a ListView does not throw an exception', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/126648
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: ListView(
children: <Widget>[
const SizedBox(
height: 600,
child: Placeholder(),
),
RangeSlider(
values: const RangeValues(40, 80),
max: 100,
onChanged: (RangeValues newValue) { },
),
],
),
),
),
),
);
// No exception should be thrown.
expect(tester.takeException(), null);
});
// This is a regression test for https://github.com/flutter/flutter/issues/141953.
testWidgets('Semantic nodes do not throw an error after clearSemantics', (WidgetTester tester) async {
SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: RangeSlider(
values: const RangeValues(40, 80),
max: 100,
onChanged: (RangeValues newValue) { },
),
),
),
);
// Dispose the semantics to trigger clearSemantics.
semantics.dispose();
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
// Initialize the semantics again.
semantics = SemanticsTester(tester);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
semantics.dispose();
}, semanticsEnabled: false);
}
| flutter/packages/flutter/test/material/range_slider_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/range_slider_test.dart",
"repo_id": "flutter",
"token_count": 43023
} | 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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('SliderThemeData copyWith, ==, hashCode basics', () {
expect(const SliderThemeData(), const SliderThemeData().copyWith());
expect(const SliderThemeData().hashCode, const SliderThemeData().copyWith().hashCode);
});
test('SliderThemeData lerp special cases', () {
const SliderThemeData data = SliderThemeData();
expect(identical(SliderThemeData.lerp(data, data, 0.5), data), true);
});
testWidgets('Default SliderThemeData debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const SliderThemeData().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('SliderThemeData implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const SliderThemeData(
trackHeight: 7.0,
activeTrackColor: Color(0xFF000001),
inactiveTrackColor: Color(0xFF000002),
secondaryActiveTrackColor: Color(0xFF000003),
disabledActiveTrackColor: Color(0xFF000004),
disabledInactiveTrackColor: Color(0xFF000005),
disabledSecondaryActiveTrackColor: Color(0xFF000006),
activeTickMarkColor: Color(0xFF000007),
inactiveTickMarkColor: Color(0xFF000008),
disabledActiveTickMarkColor: Color(0xFF000009),
disabledInactiveTickMarkColor: Color(0xFF000010),
thumbColor: Color(0xFF000011),
overlappingShapeStrokeColor: Color(0xFF000012),
disabledThumbColor: Color(0xFF000013),
overlayColor: Color(0xFF000014),
valueIndicatorColor: Color(0xFF000015),
valueIndicatorStrokeColor: Color(0xFF000015),
overlayShape: RoundSliderOverlayShape(),
tickMarkShape: RoundSliderTickMarkShape(),
thumbShape: RoundSliderThumbShape(),
trackShape: RoundedRectSliderTrackShape(),
valueIndicatorShape: PaddleSliderValueIndicatorShape(),
rangeTickMarkShape: RoundRangeSliderTickMarkShape(),
rangeThumbShape: RoundRangeSliderThumbShape(),
rangeTrackShape: RoundedRectRangeSliderTrackShape(),
rangeValueIndicatorShape: PaddleRangeSliderValueIndicatorShape(),
showValueIndicator: ShowValueIndicator.always,
valueIndicatorTextStyle: TextStyle(color: Colors.black),
mouseCursor: MaterialStateMouseCursor.clickable,
allowedInteraction: SliderInteraction.tapOnly,
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'trackHeight: 7.0',
'activeTrackColor: Color(0xff000001)',
'inactiveTrackColor: Color(0xff000002)',
'secondaryActiveTrackColor: Color(0xff000003)',
'disabledActiveTrackColor: Color(0xff000004)',
'disabledInactiveTrackColor: Color(0xff000005)',
'disabledSecondaryActiveTrackColor: Color(0xff000006)',
'activeTickMarkColor: Color(0xff000007)',
'inactiveTickMarkColor: Color(0xff000008)',
'disabledActiveTickMarkColor: Color(0xff000009)',
'disabledInactiveTickMarkColor: Color(0xff000010)',
'thumbColor: Color(0xff000011)',
'overlappingShapeStrokeColor: Color(0xff000012)',
'disabledThumbColor: Color(0xff000013)',
'overlayColor: Color(0xff000014)',
'valueIndicatorColor: Color(0xff000015)',
'valueIndicatorStrokeColor: Color(0xff000015)',
"overlayShape: Instance of 'RoundSliderOverlayShape'",
"tickMarkShape: Instance of 'RoundSliderTickMarkShape'",
"thumbShape: Instance of 'RoundSliderThumbShape'",
"trackShape: Instance of 'RoundedRectSliderTrackShape'",
"valueIndicatorShape: Instance of 'PaddleSliderValueIndicatorShape'",
"rangeTickMarkShape: Instance of 'RoundRangeSliderTickMarkShape'",
"rangeThumbShape: Instance of 'RoundRangeSliderThumbShape'",
"rangeTrackShape: Instance of 'RoundedRectRangeSliderTrackShape'",
"rangeValueIndicatorShape: Instance of 'PaddleRangeSliderValueIndicatorShape'",
'showValueIndicator: always',
'valueIndicatorTextStyle: TextStyle(inherit: true, color: Color(0xff000000))',
'mouseCursor: WidgetStateMouseCursor(clickable)',
'allowedInteraction: tapOnly'
]);
});
testWidgets('Slider defaults', (WidgetTester tester) async {
debugDisableShadows = false;
final ThemeData theme = ThemeData(useMaterial3: true);
final ColorScheme colorScheme = theme.colorScheme;
const double trackHeight = 4.0;
final Color activeTrackColor = Color(colorScheme.primary.value);
final Color inactiveTrackColor = colorScheme.surfaceContainerHighest;
final Color secondaryActiveTrackColor = colorScheme.primary.withOpacity(0.54);
final Color disabledActiveTrackColor = colorScheme.onSurface.withOpacity(0.38);
final Color disabledInactiveTrackColor = colorScheme.onSurface.withOpacity(0.12);
final Color disabledSecondaryActiveTrackColor = colorScheme.onSurface.withOpacity(0.12);
final Color shadowColor = colorScheme.shadow;
final Color thumbColor = Color(colorScheme.primary.value);
final Color disabledThumbColor = Color.alphaBlend(colorScheme.onSurface.withOpacity(0.38), colorScheme.surface);
final Color activeTickMarkColor = colorScheme.onPrimary.withOpacity(0.38);
final Color inactiveTickMarkColor = colorScheme.onSurfaceVariant.withOpacity(0.38);
final Color disabledActiveTickMarkColor = colorScheme.onSurface.withOpacity(0.38);
final Color disabledInactiveTickMarkColor = colorScheme.onSurface.withOpacity(0.38);
try {
double value = 0.45;
Widget buildApp({
int? divisions,
bool enabled = true,
}) {
final ValueChanged<double>? onChanged = !enabled
? null
: (double d) {
value = d;
};
return MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Theme(
data: theme,
child: Slider(
value: value,
secondaryTrackValue: 0.75,
label: '$value',
divisions: divisions,
onChanged: onChanged,
),
),
),
),
),
);
}
await tester.pumpWidget(buildApp());
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
// Test default track height.
const Radius radius = Radius.circular(trackHeight / 2);
const Radius activatedRadius = Radius.circular((trackHeight + 2) / 2);
expect(
material,
paints
..rrect(rrect: RRect.fromLTRBAndCorners(24.0, 297.0, 362.4, 303.0, topLeft: activatedRadius, bottomLeft: activatedRadius), color: activeTrackColor)
..rrect(rrect: RRect.fromLTRBAndCorners(362.4, 298.0, 776.0, 302.0, topRight: radius, bottomRight: radius), color: inactiveTrackColor),
);
// Test default colors for enabled slider.
expect(material, paints..rrect(color: activeTrackColor)..rrect(color: inactiveTrackColor)..rrect(color: secondaryActiveTrackColor));
expect(material, paints..shadow(color: shadowColor));
expect(material, paints..circle(color: thumbColor));
expect(material, isNot(paints..circle(color: disabledThumbColor)));
expect(material, isNot(paints..rrect(color: disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: disabledSecondaryActiveTrackColor)));
expect(material, isNot(paints..circle(color: activeTickMarkColor)));
expect(material, isNot(paints..circle(color: inactiveTickMarkColor)));
// Test defaults colors for discrete slider.
await tester.pumpWidget(buildApp(divisions: 3));
expect(material, paints..rrect(color: activeTrackColor)..rrect(color: inactiveTrackColor)..rrect(color: secondaryActiveTrackColor));
expect(
material,
paints
..circle(color: activeTickMarkColor)
..circle(color: activeTickMarkColor)
..circle(color: inactiveTickMarkColor)
..circle(color: inactiveTickMarkColor)
..shadow(color: Colors.black)
..circle(color: thumbColor),
);
expect(material, isNot(paints..circle(color: disabledThumbColor)));
expect(material, isNot(paints..rrect(color: disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: disabledSecondaryActiveTrackColor)));
// Test defaults colors for disabled slider.
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
material,
paints
..rrect(color: disabledActiveTrackColor)
..rrect(color: disabledInactiveTrackColor)
..rrect(color: disabledSecondaryActiveTrackColor),
);
expect(material, paints..shadow(color: shadowColor)..circle(color: disabledThumbColor));
expect(material, isNot(paints..circle(color: thumbColor)));
expect(material, isNot(paints..rrect(color: activeTrackColor)));
expect(material, isNot(paints..rrect(color: inactiveTrackColor)));
expect(material, isNot(paints..rrect(color: secondaryActiveTrackColor)));
// Test defaults colors for disabled discrete slider.
await tester.pumpWidget(buildApp(divisions: 3, enabled: false));
expect(
material,
paints
..circle(color: disabledActiveTickMarkColor)
..circle(color: disabledActiveTickMarkColor)
..circle(color: disabledInactiveTickMarkColor)
..circle(color: disabledInactiveTickMarkColor)
..shadow(color: shadowColor)
..circle(color: disabledThumbColor),
);
expect(material, isNot(paints..circle(color: thumbColor)));
expect(material, isNot(paints..rrect(color: activeTrackColor)));
expect(material, isNot(paints..rrect(color: inactiveTrackColor)));
expect(material, isNot(paints..rrect(color: secondaryActiveTrackColor)));
} finally {
debugDisableShadows = true;
}
});
testWidgets('Slider uses the right theme colors for the right components', (WidgetTester tester) async {
debugDisableShadows = false;
try {
const Color customColor1 = Color(0xcafefeed);
const Color customColor2 = Color(0xdeadbeef);
const Color customColor3 = Color(0xdecaface);
final ThemeData theme = ThemeData(
useMaterial3: false,
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
sliderTheme: const SliderThemeData(
disabledThumbColor: Color(0xff000001),
disabledActiveTickMarkColor: Color(0xff000002),
disabledActiveTrackColor: Color(0xff000003),
disabledInactiveTickMarkColor: Color(0xff000004),
disabledInactiveTrackColor: Color(0xff000005),
activeTrackColor: Color(0xff000006),
activeTickMarkColor: Color(0xff000007),
inactiveTrackColor: Color(0xff000008),
inactiveTickMarkColor: Color(0xff000009),
overlayColor: Color(0xff000010),
thumbColor: Color(0xff000011),
valueIndicatorColor: Color(0xff000012),
disabledSecondaryActiveTrackColor: Color(0xff000013),
secondaryActiveTrackColor: Color(0xff000014),
),
);
final SliderThemeData sliderTheme = theme.sliderTheme;
double value = 0.45;
Widget buildApp({
Color? activeColor,
Color? inactiveColor,
Color? secondaryActiveColor,
int? divisions,
bool enabled = true,
}) {
final ValueChanged<double>? onChanged = !enabled
? null
: (double d) {
value = d;
};
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Theme(
data: theme,
child: Slider(
value: value,
secondaryTrackValue: 0.75,
label: '$value',
divisions: divisions,
activeColor: activeColor,
inactiveColor: inactiveColor,
secondaryActiveColor: secondaryActiveColor,
onChanged: onChanged,
),
),
),
),
),
);
}
await tester.pumpWidget(buildApp());
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Check default theme for enabled widget.
expect(material, paints..rrect(color: sliderTheme.activeTrackColor)..rrect(color: sliderTheme.inactiveTrackColor)..rrect(color: sliderTheme.secondaryActiveTrackColor));
expect(material, paints..shadow(color: const Color(0xff000000)));
expect(material, paints..circle(color: sliderTheme.thumbColor));
expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor)));
expect(material, isNot(paints..circle(color: sliderTheme.activeTickMarkColor)));
expect(material, isNot(paints..circle(color: sliderTheme.inactiveTickMarkColor)));
// Test setting only the activeColor.
await tester.pumpWidget(buildApp(activeColor: customColor1));
expect(material, paints..rrect(color: customColor1)..rrect(color: sliderTheme.inactiveTrackColor)..rrect(color: sliderTheme.secondaryActiveTrackColor));
expect(material, paints..shadow(color: Colors.black));
expect(material, paints..circle(color: customColor1));
expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor)));
// Test setting only the inactiveColor.
await tester.pumpWidget(buildApp(inactiveColor: customColor1));
expect(material, paints..rrect(color: sliderTheme.activeTrackColor)..rrect(color: customColor1)..rrect(color: sliderTheme.secondaryActiveTrackColor));
expect(material, paints..shadow(color: Colors.black));
expect(material, paints..circle(color: sliderTheme.thumbColor));
expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor)));
// Test setting only the secondaryActiveColor.
await tester.pumpWidget(buildApp(secondaryActiveColor: customColor1));
expect(material, paints..rrect(color: sliderTheme.activeTrackColor)..rrect(color: sliderTheme.inactiveTrackColor)..rrect(color: customColor1));
expect(material, paints..shadow(color: Colors.black));
expect(material, paints..circle(color: sliderTheme.thumbColor));
expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor)));
// Test setting both activeColor, inactiveColor, and secondaryActiveColor.
await tester.pumpWidget(buildApp(activeColor: customColor1, inactiveColor: customColor2, secondaryActiveColor: customColor3));
expect(material, paints..rrect(color: customColor1)..rrect(color: customColor2)..rrect(color: customColor3));
expect(material, paints..shadow(color: Colors.black));
expect(material, paints..circle(color: customColor1));
expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor)));
// Test colors for discrete slider.
await tester.pumpWidget(buildApp(divisions: 3));
expect(material, paints..rrect(color: sliderTheme.activeTrackColor)..rrect(color: sliderTheme.inactiveTrackColor)..rrect(color: sliderTheme.secondaryActiveTrackColor));
expect(
material,
paints
..circle(color: sliderTheme.activeTickMarkColor)
..circle(color: sliderTheme.activeTickMarkColor)
..circle(color: sliderTheme.inactiveTickMarkColor)
..circle(color: sliderTheme.inactiveTickMarkColor)
..shadow(color: Colors.black)
..circle(color: sliderTheme.thumbColor),
);
expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor)));
// Test colors for discrete slider with inactiveColor and activeColor set.
await tester.pumpWidget(buildApp(
activeColor: customColor1,
inactiveColor: customColor2,
secondaryActiveColor: customColor3,
divisions: 3,
));
expect(material, paints..rrect(color: customColor1)..rrect(color: customColor2)..rrect(color: customColor3));
expect(
material,
paints
..circle(color: customColor2)
..circle(color: customColor2)
..circle(color: customColor1)
..circle(color: customColor1)
..shadow(color: Colors.black)
..circle(color: customColor1),
);
expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(material, isNot(paints..circle(color: sliderTheme.disabledThumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor)));
expect(material, isNot(paints..circle(color: sliderTheme.activeTickMarkColor)));
expect(material, isNot(paints..circle(color: sliderTheme.inactiveTickMarkColor)));
// Test default theme for disabled widget.
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
material,
paints
..rrect(color: sliderTheme.disabledActiveTrackColor)
..rrect(color: sliderTheme.disabledInactiveTrackColor)
..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor),
);
expect(material, paints..shadow(color: Colors.black)..circle(color: sliderTheme.disabledThumbColor));
expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.activeTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.inactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.secondaryActiveTrackColor)));
// Test default theme for disabled discrete widget.
await tester.pumpWidget(buildApp(divisions: 3, enabled: false));
expect(
material,
paints
..circle(color: sliderTheme.disabledActiveTickMarkColor)
..circle(color: sliderTheme.disabledActiveTickMarkColor)
..circle(color: sliderTheme.disabledInactiveTickMarkColor)
..circle(color: sliderTheme.disabledInactiveTickMarkColor)
..shadow(color: Colors.black)
..circle(color: sliderTheme.disabledThumbColor),
);
expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.activeTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.inactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.secondaryActiveTrackColor)));
expect(material, isNot(paints..circle(color: sliderTheme.activeTickMarkColor)));
expect(material, isNot(paints..circle(color: sliderTheme.inactiveTickMarkColor)));
// Test setting the activeColor, inactiveColor and secondaryActiveColor for disabled widget.
await tester.pumpWidget(buildApp(activeColor: customColor1, inactiveColor: customColor2, secondaryActiveColor: customColor3, enabled: false));
expect(
material,
paints
..rrect(color: sliderTheme.disabledActiveTrackColor)
..rrect(color: sliderTheme.disabledInactiveTrackColor)
..rrect(color: sliderTheme.disabledSecondaryActiveTrackColor),
);
expect(material, paints..circle(color: sliderTheme.disabledThumbColor));
expect(material, isNot(paints..circle(color: sliderTheme.thumbColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.activeTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.inactiveTrackColor)));
expect(material, isNot(paints..rrect(color: sliderTheme.secondaryActiveTrackColor)));
// Test that the default value indicator has the right colors.
await tester.pumpWidget(buildApp(divisions: 3));
Offset center = tester.getCenter(find.byType(Slider));
TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(value, equals(2.0 / 3.0));
expect(
valueIndicatorBox,
paints
..path(color: sliderTheme.valueIndicatorColor)
..paragraph(),
);
await gesture.up();
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
// Testing the custom colors are used for the indicator.
await tester.pumpWidget(buildApp(
divisions: 3,
activeColor: customColor1,
inactiveColor: customColor2,
));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(value, equals(2.0 / 3.0));
expect(
valueIndicatorBox,
paints
..rrect(color: const Color(0xfffafafa))
..rrect(color: customColor1) // active track
..rrect(color: customColor2) // inactive track
..circle(color: customColor1.withOpacity(0.12)) // overlay
..circle(color: customColor2) // 1st tick mark
..circle(color: customColor2) // 2nd tick mark
..circle(color: customColor2) // 3rd tick mark
..circle(color: customColor1) // 4th tick mark
..shadow(color: Colors.black)
..circle(color: customColor1) // thumb
..path(color: sliderTheme.valueIndicatorColor), // indicator
);
await gesture.up();
} finally {
debugDisableShadows = true;
}
});
testWidgets('Slider parameters overrides theme properties', (WidgetTester tester) async {
debugDisableShadows = false;
const Color activeTrackColor = Color(0xffff0001);
const Color inactiveTrackColor = Color(0xffff0002);
const Color secondaryActiveTrackColor = Color(0xffff0003);
const Color thumbColor = Color(0xffff0004);
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
sliderTheme: const SliderThemeData(
activeTrackColor: Color(0xff000001),
inactiveTickMarkColor: Color(0xff000002),
secondaryActiveTrackColor: Color(0xff000003),
thumbColor: Color(0xff000004),
),
);
try {
const double value = 0.45;
Widget buildApp({ bool enabled = true }) {
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Slider(
activeColor: activeTrackColor,
inactiveColor: inactiveTrackColor,
secondaryActiveColor: secondaryActiveTrackColor,
thumbColor: thumbColor,
value: value,
secondaryTrackValue: 0.75,
label: '$value',
onChanged: (double value) { },
),
),
),
),
);
}
await tester.pumpWidget(buildApp());
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
// Test Slider parameters.
expect(material, paints..rrect(color: activeTrackColor)..rrect(color: inactiveTrackColor)..rrect(color: secondaryActiveTrackColor));
expect(material, paints..circle(color: thumbColor));
} finally {
debugDisableShadows = true;
}
});
testWidgets('Slider uses ThemeData slider theme if present', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.red,
);
final SliderThemeData sliderTheme = theme.sliderTheme;
final SliderThemeData customTheme = sliderTheme.copyWith(
activeTrackColor: Colors.purple,
inactiveTrackColor: Colors.purple.withAlpha(0x3d),
secondaryActiveTrackColor: Colors.purple.withAlpha(0x8a),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.5, secondaryTrackValue: 0.75, enabled: false));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
expect(
material,
paints
..rrect(color: customTheme.disabledActiveTrackColor)
..rrect(color: customTheme.disabledInactiveTrackColor)
..rrect(color: customTheme.disabledSecondaryActiveTrackColor),
);
});
testWidgets('Slider overrides ThemeData theme if SliderTheme present', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.red,
);
final SliderThemeData sliderTheme = theme.sliderTheme;
final SliderThemeData customTheme = sliderTheme.copyWith(
activeTrackColor: Colors.purple,
inactiveTrackColor: Colors.purple.withAlpha(0x3d),
secondaryActiveTrackColor: Colors.purple.withAlpha(0x8a),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.5, secondaryTrackValue: 0.75, enabled: false));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
expect(
material,
paints
..rrect(color: customTheme.disabledActiveTrackColor)
..rrect(color: customTheme.disabledInactiveTrackColor)
..rrect(color: customTheme.disabledSecondaryActiveTrackColor),
);
});
testWidgets('SliderThemeData generates correct opacities for fromPrimaryColors', (WidgetTester tester) async {
const Color customColor1 = Color(0xcafefeed);
const Color customColor2 = Color(0xdeadbeef);
const Color customColor3 = Color(0xdecaface);
const Color customColor4 = Color(0xfeedcafe);
final SliderThemeData sliderTheme = SliderThemeData.fromPrimaryColors(
primaryColor: customColor1,
primaryColorDark: customColor2,
primaryColorLight: customColor3,
valueIndicatorTextStyle: ThemeData.fallback().textTheme.bodyLarge!.copyWith(color: customColor4),
);
expect(sliderTheme.activeTrackColor, equals(customColor1.withAlpha(0xff)));
expect(sliderTheme.inactiveTrackColor, equals(customColor1.withAlpha(0x3d)));
expect(sliderTheme.secondaryActiveTrackColor, equals(customColor1.withAlpha(0x8a)));
expect(sliderTheme.disabledActiveTrackColor, equals(customColor2.withAlpha(0x52)));
expect(sliderTheme.disabledInactiveTrackColor, equals(customColor2.withAlpha(0x1f)));
expect(sliderTheme.disabledSecondaryActiveTrackColor, equals(customColor2.withAlpha(0x1f)));
expect(sliderTheme.activeTickMarkColor, equals(customColor3.withAlpha(0x8a)));
expect(sliderTheme.inactiveTickMarkColor, equals(customColor1.withAlpha(0x8a)));
expect(sliderTheme.disabledActiveTickMarkColor, equals(customColor3.withAlpha(0x1f)));
expect(sliderTheme.disabledInactiveTickMarkColor, equals(customColor2.withAlpha(0x1f)));
expect(sliderTheme.thumbColor, equals(customColor1.withAlpha(0xff)));
expect(sliderTheme.disabledThumbColor, equals(customColor2.withAlpha(0x52)));
expect(sliderTheme.overlayColor, equals(customColor1.withAlpha(0x1f)));
expect(sliderTheme.valueIndicatorColor, equals(customColor1.withAlpha(0xff)));
expect(sliderTheme.valueIndicatorStrokeColor, equals(customColor1.withAlpha(0xff)));
expect(sliderTheme.valueIndicatorTextStyle!.color, equals(customColor4));
});
testWidgets('SliderThemeData generates correct shapes for fromPrimaryColors', (WidgetTester tester) async {
const Color customColor1 = Color(0xcafefeed);
const Color customColor2 = Color(0xdeadbeef);
const Color customColor3 = Color(0xdecaface);
const Color customColor4 = Color(0xfeedcafe);
final SliderThemeData sliderTheme = SliderThemeData.fromPrimaryColors(
primaryColor: customColor1,
primaryColorDark: customColor2,
primaryColorLight: customColor3,
valueIndicatorTextStyle: ThemeData.fallback().textTheme.bodyLarge!.copyWith(color: customColor4),
);
expect(sliderTheme.overlayShape, const RoundSliderOverlayShape());
expect(sliderTheme.tickMarkShape, const RoundSliderTickMarkShape());
expect(sliderTheme.thumbShape, const RoundSliderThumbShape());
expect(sliderTheme.trackShape, const RoundedRectSliderTrackShape());
expect(sliderTheme.valueIndicatorShape, const PaddleSliderValueIndicatorShape());
expect(sliderTheme.rangeTickMarkShape, const RoundRangeSliderTickMarkShape());
expect(sliderTheme.rangeThumbShape, const RoundRangeSliderThumbShape());
expect(sliderTheme.rangeTrackShape, const RoundedRectRangeSliderTrackShape());
expect(sliderTheme.rangeValueIndicatorShape, const PaddleRangeSliderValueIndicatorShape());
});
testWidgets('SliderThemeData lerps correctly', (WidgetTester tester) async {
final SliderThemeData sliderThemeBlack = SliderThemeData.fromPrimaryColors(
primaryColor: Colors.black,
primaryColorDark: Colors.black,
primaryColorLight: Colors.black,
valueIndicatorTextStyle: ThemeData.fallback().textTheme.bodyLarge!.copyWith(color: Colors.black),
).copyWith(trackHeight: 2.0);
final SliderThemeData sliderThemeWhite = SliderThemeData.fromPrimaryColors(
primaryColor: Colors.white,
primaryColorDark: Colors.white,
primaryColorLight: Colors.white,
valueIndicatorTextStyle: ThemeData.fallback().textTheme.bodyLarge!.copyWith(color: Colors.white),
).copyWith(trackHeight: 6.0);
final SliderThemeData lerp = SliderThemeData.lerp(sliderThemeBlack, sliderThemeWhite, 0.5);
const Color middleGrey = Color(0xff7f7f7f);
expect(lerp.trackHeight, equals(4.0));
expect(lerp.activeTrackColor, equals(middleGrey.withAlpha(0xff)));
expect(lerp.inactiveTrackColor, equals(middleGrey.withAlpha(0x3d)));
expect(lerp.secondaryActiveTrackColor, equals(middleGrey.withAlpha(0x8a)));
expect(lerp.disabledActiveTrackColor, equals(middleGrey.withAlpha(0x52)));
expect(lerp.disabledInactiveTrackColor, equals(middleGrey.withAlpha(0x1f)));
expect(lerp.disabledSecondaryActiveTrackColor, equals(middleGrey.withAlpha(0x1f)));
expect(lerp.activeTickMarkColor, equals(middleGrey.withAlpha(0x8a)));
expect(lerp.inactiveTickMarkColor, equals(middleGrey.withAlpha(0x8a)));
expect(lerp.disabledActiveTickMarkColor, equals(middleGrey.withAlpha(0x1f)));
expect(lerp.disabledInactiveTickMarkColor, equals(middleGrey.withAlpha(0x1f)));
expect(lerp.thumbColor, equals(middleGrey.withAlpha(0xff)));
expect(lerp.disabledThumbColor, equals(middleGrey.withAlpha(0x52)));
expect(lerp.overlayColor, equals(middleGrey.withAlpha(0x1f)));
expect(lerp.valueIndicatorColor, equals(middleGrey.withAlpha(0xff)));
expect(lerp.valueIndicatorStrokeColor, equals(middleGrey.withAlpha(0xff)));
expect(lerp.valueIndicatorTextStyle!.color, equals(middleGrey.withAlpha(0xff)));
});
testWidgets('Default slider track draws correctly', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
);
final SliderThemeData sliderTheme = theme.sliderTheme.copyWith(thumbColor: Colors.red.shade500);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25, secondaryTrackValue: 0.5));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
const Radius radius = Radius.circular(2);
const Radius activatedRadius = Radius.circular(3);
// The enabled slider thumb has track segments that extend to and from
// the center of the thumb.
expect(
material,
paints
..rrect(rrect: RRect.fromLTRBAndCorners(24.0, 297.0, 212.0, 303.0, topLeft: activatedRadius, bottomLeft: activatedRadius), color: sliderTheme.activeTrackColor)
..rrect(rrect: RRect.fromLTRBAndCorners(212.0, 298.0, 776.0, 302.0, topRight: radius, bottomRight: radius), color: sliderTheme.inactiveTrackColor)
..rrect(rrect: RRect.fromLTRBAndCorners(212.0, 298.0, 400.0, 302.0, topRight: radius, bottomRight: radius), color: sliderTheme.secondaryActiveTrackColor),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25, secondaryTrackValue: 0.5, enabled: false));
await tester.pumpAndSettle(); // wait for disable animation
// The disabled slider thumb is the same size as the enabled thumb.
expect(
material,
paints
..rrect(rrect: RRect.fromLTRBAndCorners(24.0, 297.0, 212.0, 303.0, topLeft: activatedRadius, bottomLeft: activatedRadius), color: sliderTheme.disabledActiveTrackColor)
..rrect(rrect: RRect.fromLTRBAndCorners(212.0, 298.0, 776.0, 302.0, topRight: radius, bottomRight: radius), color: sliderTheme.disabledInactiveTrackColor)
..rrect(rrect: RRect.fromLTRBAndCorners(212.0, 298.0, 400.0, 302.0, topRight: radius, bottomRight: radius), color: sliderTheme.disabledSecondaryActiveTrackColor),
);
});
testWidgets('Default slider overlay draws correctly', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
);
final SliderThemeData sliderTheme = theme.sliderTheme.copyWith(thumbColor: Colors.red.shade500);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
// With no touch, paints only the thumb.
expect(
material,
paints
..circle(
color: sliderTheme.thumbColor,
x: 212.0,
y: 300.0,
radius: 10.0,
),
);
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for overlay animation to finish.
await tester.pumpAndSettle();
// After touch, paints thumb and overlay.
expect(
material,
paints
..circle(
color: sliderTheme.overlayColor,
x: 212.0,
y: 300.0,
radius: 24.0,
)
..circle(
color: sliderTheme.thumbColor,
x: 212.0,
y: 300.0,
radius: 10.0,
),
);
await gesture.up();
await tester.pumpAndSettle();
// After the gesture is up and complete, it again paints only the thumb.
expect(
material,
paints
..circle(
color: sliderTheme.thumbColor,
x: 212.0,
y: 300.0,
radius: 10.0,
),
);
});
testWidgets('Slider can use theme overlay with material states', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
);
final SliderThemeData sliderTheme = theme.sliderTheme.copyWith(
overlayColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.focused)) {
return Colors.brown[500]!;
}
return Colors.transparent;
}),
);
final FocusNode focusNode = FocusNode(debugLabel: 'Slider');
addTearDown(focusNode.dispose);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
double value = 0.5;
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: ThemeData(sliderTheme: sliderTheme),
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Slider(
value: value,
onChanged: enabled ? (double newValue) {
setState(() {
value = newValue;
});
} : null,
autofocus: true,
focusNode: focusNode,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
// Check that the overlay shows when focused.
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Slider))),
paints..circle(color: Colors.brown[500]),
);
// Check that the overlay does not show when focused and disabled.
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expect(
Material.of(tester.element(find.byType(Slider))),
isNot(paints..circle(color: Colors.brown[500])),
);
});
testWidgets('Default slider ticker and thumb shape draw correctly', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
);
final SliderThemeData sliderTheme = theme.sliderTheme.copyWith(thumbColor: Colors.red.shade500);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.45));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
expect(material, paints..circle(color: sliderTheme.thumbColor, radius: 10.0));
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.45, enabled: false));
await tester.pumpAndSettle(); // wait for disable animation
expect(material, paints..circle(color: sliderTheme.disabledThumbColor, radius: 10.0));
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.45, divisions: 3));
await tester.pumpAndSettle(); // wait for enable animation
expect(
material,
paints
..circle(color: sliderTheme.activeTickMarkColor)
..circle(color: sliderTheme.activeTickMarkColor)
..circle(color: sliderTheme.inactiveTickMarkColor)
..circle(color: sliderTheme.inactiveTickMarkColor)
..circle(color: sliderTheme.thumbColor, radius: 10.0),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.45, divisions: 3, enabled: false));
await tester.pumpAndSettle(); // wait for disable animation
expect(
material,
paints
..circle(color: sliderTheme.disabledActiveTickMarkColor)
..circle(color: sliderTheme.disabledInactiveTickMarkColor)
..circle(color: sliderTheme.disabledInactiveTickMarkColor)
..circle(color: sliderTheme.disabledInactiveTickMarkColor)
..circle(color: sliderTheme.disabledThumbColor, radius: 10.0),
);
});
testWidgets('Default paddle slider value indicator shape draws correctly', (WidgetTester tester) async {
debugDisableShadows = false;
try {
final ThemeData theme = ThemeData(
useMaterial3: false,
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
);
final SliderThemeData sliderTheme = theme.sliderTheme.copyWith(
thumbColor: Colors.red.shade500,
showValueIndicator: ShowValueIndicator.always,
valueIndicatorShape: const PaddleSliderValueIndicatorShape(),
);
Widget buildApp(String value, { double sliderValue = 0.5, TextScaler textScaler = TextScaler.noScaling }) {
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: Material(
child: Row(
children: <Widget>[
Expanded(
child: SliderTheme(
data: sliderTheme,
child: Slider(
value: sliderValue,
label: value,
divisions: 3,
onChanged: (double d) { },
),
),
),
],
),
),
),
),
);
}
await tester.pumpWidget(buildApp('1'));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
Offset center = tester.getCenter(find.byType(Slider));
TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -40.0),
const Offset(15.9, -40.0),
const Offset(-15.9, -40.0),
],
excludes: <Offset>[const Offset(16.1, -40.0), const Offset(-16.1, -40.0)],
),
);
await gesture.up();
// Test that it expands with a larger label.
await tester.pumpWidget(buildApp('1000'));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -40.0),
const Offset(35.9, -40.0),
const Offset(-35.9, -40.0),
],
excludes: <Offset>[const Offset(36.1, -40.0), const Offset(-36.1, -40.0)],
),
);
await gesture.up();
// Test that it avoids the left edge of the screen.
await tester.pumpWidget(buildApp('1000000', sliderValue: 0.0));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -40.0),
const Offset(92.0, -40.0),
const Offset(-16.0, -40.0),
],
excludes: <Offset>[const Offset(98.1, -40.0), const Offset(-20.1, -40.0)],
),
);
await gesture.up();
// Test that it avoids the right edge of the screen.
await tester.pumpWidget(buildApp('1000000', sliderValue: 1.0));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -40.0),
const Offset(16.0, -40.0),
const Offset(-92.0, -40.0),
],
excludes: <Offset>[const Offset(20.1, -40.0), const Offset(-98.1, -40.0)],
),
);
await gesture.up();
// Test that the neck stretches when the text scale gets smaller.
await tester.pumpWidget(buildApp('1000000', sliderValue: 0.0, textScaler: const TextScaler.linear(0.5)));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -49.0),
const Offset(68.0, -49.0),
const Offset(-24.0, -49.0),
],
excludes: <Offset>[
const Offset(98.0, -32.0), // inside full size, outside small
const Offset(-40.0, -32.0), // inside full size, outside small
const Offset(90.1, -49.0),
const Offset(-40.1, -49.0),
],
),
);
await gesture.up();
// Test that the neck shrinks when the text scale gets larger.
await tester.pumpWidget(buildApp('1000000', sliderValue: 0.0, textScaler: const TextScaler.linear(2.5)));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -38.8),
const Offset(92.0, -38.8),
const Offset(8.0, -23.0), // Inside large, outside scale=1.0
const Offset(-2.0, -23.0), // Inside large, outside scale=1.0
],
excludes: <Offset>[
const Offset(98.5, -38.8),
const Offset(-16.1, -38.8),
],
),
);
await gesture.up();
} finally {
debugDisableShadows = true;
}
});
testWidgets('Default paddle slider value indicator shape draws correctly', (WidgetTester tester) async {
debugDisableShadows = false;
try {
final ThemeData theme = ThemeData(
useMaterial3: false,
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
);
final SliderThemeData sliderTheme = theme.sliderTheme.copyWith(
thumbColor: Colors.red.shade500,
showValueIndicator: ShowValueIndicator.always,
valueIndicatorShape: const PaddleSliderValueIndicatorShape(),
);
Widget buildApp(String value, { double sliderValue = 0.5, TextScaler textScaler = TextScaler.noScaling }) {
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: Material(
child: Row(
children: <Widget>[
Expanded(
child: SliderTheme(
data: sliderTheme,
child: Slider(
value: sliderValue,
label: value,
divisions: 3,
onChanged: (double d) { },
),
),
),
],
),
),
),
),
);
}
await tester.pumpWidget(buildApp('1'));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
Offset center = tester.getCenter(find.byType(Slider));
TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -40.0),
const Offset(15.9, -40.0),
const Offset(-15.9, -40.0),
],
excludes: <Offset>[const Offset(16.1, -40.0), const Offset(-16.1, -40.0)],
),
);
await gesture.up();
// Test that it expands with a larger label.
await tester.pumpWidget(buildApp('1000'));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -40.0),
const Offset(35.9, -40.0),
const Offset(-35.9, -40.0),
],
excludes: <Offset>[const Offset(36.1, -40.0), const Offset(-36.1, -40.0)],
),
);
await gesture.up();
// Test that it avoids the left edge of the screen.
await tester.pumpWidget(buildApp('1000000', sliderValue: 0.0));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -40.0),
const Offset(92.0, -40.0),
const Offset(-16.0, -40.0),
],
excludes: <Offset>[const Offset(98.1, -40.0), const Offset(-20.1, -40.0)],
),
);
await gesture.up();
// Test that it avoids the right edge of the screen.
await tester.pumpWidget(buildApp('1000000', sliderValue: 1.0));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -40.0),
const Offset(16.0, -40.0),
const Offset(-92.0, -40.0),
],
excludes: <Offset>[const Offset(20.1, -40.0), const Offset(-98.1, -40.0)],
),
);
await gesture.up();
// Test that the neck stretches when the text scale gets smaller.
await tester.pumpWidget(buildApp('1000000', sliderValue: 0.0, textScaler: const TextScaler.linear(0.5)));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -49.0),
const Offset(68.0, -49.0),
const Offset(-24.0, -49.0),
],
excludes: <Offset>[
const Offset(98.0, -32.0), // inside full size, outside small
const Offset(-40.0, -32.0), // inside full size, outside small
const Offset(90.1, -49.0),
const Offset(-40.1, -49.0),
],
),
);
await gesture.up();
// Test that the neck shrinks when the text scale gets larger.
await tester.pumpWidget(buildApp('1000000', sliderValue: 0.0, textScaler: const TextScaler.linear(2.5)));
center = tester.getCenter(find.byType(Slider));
gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(
color: sliderTheme.valueIndicatorColor,
includes: <Offset>[
const Offset(0.0, -38.8),
const Offset(92.0, -38.8),
const Offset(8.0, -23.0), // Inside large, outside scale=1.0
const Offset(-2.0, -23.0), // Inside large, outside scale=1.0
],
excludes: <Offset>[
const Offset(98.5, -38.8),
const Offset(-16.1, -38.8),
],
),
);
await gesture.up();
} finally {
debugDisableShadows = true;
}
});
testWidgets('The slider track height can be overridden', (WidgetTester tester) async {
final SliderThemeData sliderTheme = ThemeData().sliderTheme.copyWith(trackHeight: 16);
const Radius radius = Radius.circular(8);
const Radius activatedRadius = Radius.circular(9);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
// Top and bottom are centerY (300) + and - trackRadius (8).
expect(
material,
paints
..rrect(rrect: RRect.fromLTRBAndCorners(24.0, 291.0, 212.0, 309.0, topLeft: activatedRadius, bottomLeft: activatedRadius), color: sliderTheme.activeTrackColor)
..rrect(rrect: RRect.fromLTRBAndCorners(212.0, 292.0, 776.0, 308.0, topRight: radius, bottomRight: radius), color: sliderTheme.inactiveTrackColor),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25, enabled: false));
await tester.pumpAndSettle(); // wait for disable animation
// The disabled thumb is smaller so the active track has to paint longer to
// get to the edge.
expect(
material,
paints
..rrect(rrect: RRect.fromLTRBAndCorners(24.0, 291.0, 212.0, 309.0, topLeft: activatedRadius, bottomLeft: activatedRadius), color: sliderTheme.disabledActiveTrackColor)
..rrect(rrect: RRect.fromLTRBAndCorners(212.0, 292.0, 776.0, 308.0, topRight: radius, bottomRight: radius), color: sliderTheme.disabledInactiveTrackColor),
);
});
testWidgets('The default slider thumb shape sizes can be overridden', (WidgetTester tester) async {
final SliderThemeData sliderTheme = ThemeData().sliderTheme.copyWith(
thumbShape: const RoundSliderThumbShape(
enabledThumbRadius: 7,
disabledThumbRadius: 11,
),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
expect(
material,
paints..circle(x: 212, y: 300, radius: 7, color: sliderTheme.thumbColor),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25, enabled: false));
await tester.pumpAndSettle(); // wait for disable animation
expect(
material,
paints..circle(x: 212, y: 300, radius: 11, color: sliderTheme.disabledThumbColor),
);
});
testWidgets('The default slider thumb shape disabled size can be inferred from the enabled size', (WidgetTester tester) async {
final SliderThemeData sliderTheme = ThemeData().sliderTheme.copyWith(
thumbShape: const RoundSliderThumbShape(
enabledThumbRadius: 9,
),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
expect(
material,
paints..circle(x: 212, y: 300, radius: 9, color: sliderTheme.thumbColor),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.25, enabled: false));
await tester.pumpAndSettle(); // wait for disable animation
expect(
material,
paints..circle(x: 212, y: 300, radius: 9, color: sliderTheme.disabledThumbColor),
);
});
testWidgets('The default slider tick mark shape size can be overridden', (WidgetTester tester) async {
final SliderThemeData sliderTheme = ThemeData().sliderTheme.copyWith(
tickMarkShape: const RoundSliderTickMarkShape(tickMarkRadius: 5),
activeTickMarkColor: const Color(0xfadedead),
inactiveTickMarkColor: const Color(0xfadebeef),
disabledActiveTickMarkColor: const Color(0xfadecafe),
disabledInactiveTickMarkColor: const Color(0xfadeface),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.5, divisions: 2));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
expect(
material,
paints
..circle(x: 26, y: 300, radius: 5, color: sliderTheme.activeTickMarkColor)
..circle(x: 400, y: 300, radius: 5, color: sliderTheme.activeTickMarkColor)
..circle(x: 774, y: 300, radius: 5, color: sliderTheme.inactiveTickMarkColor),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.5, divisions: 2, enabled: false));
await tester.pumpAndSettle();
expect(
material,
paints
..circle(x: 26, y: 300, radius: 5, color: sliderTheme.disabledActiveTickMarkColor)
..circle(x: 400, y: 300, radius: 5, color: sliderTheme.disabledActiveTickMarkColor)
..circle(x: 774, y: 300, radius: 5, color: sliderTheme.disabledInactiveTickMarkColor),
);
});
testWidgets('The default slider overlay shape size can be overridden', (WidgetTester tester) async {
const double uniqueOverlayRadius = 23;
final SliderThemeData sliderTheme = ThemeData().sliderTheme.copyWith(
overlayShape: const RoundSliderOverlayShape(
overlayRadius: uniqueOverlayRadius,
),
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.5));
// Tap center and wait for animation.
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
expect(
material,
paints..circle(
x: center.dx,
y: center.dy,
radius: uniqueOverlayRadius,
color: sliderTheme.overlayColor,
),
);
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
// Regression test for https://github.com/flutter/flutter/issues/74503
testWidgets('The slider track layout correctly when the overlay size is smaller than the thumb size', (WidgetTester tester) async {
final SliderThemeData sliderTheme = ThemeData().sliderTheme.copyWith(
overlayShape: SliderComponentShape.noOverlay,
);
await tester.pumpWidget(_buildApp(sliderTheme, value: 0.5));
final MaterialInkController material = Material.of(
tester.element(find.byType(Slider)),
);
// The track rectangle begins at 10 pixels from the left of the screen and ends 10 pixels from the right
// (790 pixels from the left). The main check here it that the track itself should be centered on
// the 800 pixel-wide screen.
expect(
material,
paints
// active track RRect. Starts 10 pixels from left of screen.
..rrect(rrect: RRect.fromLTRBAndCorners(
10.0,
297.0,
400.0,
303.0,
topLeft: const Radius.circular(3.0),
bottomLeft: const Radius.circular(3.0),
))
// inactive track RRect. Ends 10 pixels from right of screen.
..rrect(rrect: RRect.fromLTRBAndCorners(
400.0,
298.0,
790.0,
302.0,
topRight: const Radius.circular(2.0),
bottomRight: const Radius.circular(2.0),
))
// The thumb.
..circle(x: 400.0, y: 300.0, radius: 10.0),
);
});
// Regression test for https://github.com/flutter/flutter/issues/125467
testWidgets('The RangeSlider track layout correctly when the overlay size is smaller than the thumb size', (WidgetTester tester) async {
final SliderThemeData sliderTheme = ThemeData().sliderTheme.copyWith(
overlayShape: SliderComponentShape.noOverlay,
);
await tester.pumpWidget(_buildRangeApp(sliderTheme, values: const RangeValues(0.0, 1.0)));
final MaterialInkController material = Material.of(
tester.element(find.byType(RangeSlider)),
);
// The track rectangle begins at 10 pixels from the left of the screen and ends 10 pixels from the right
// (790 pixels from the left). The main check here it that the track itself should be centered on
// the 800 pixel-wide screen.
expect(
material,
paints
// active track RRect. Starts 10 pixels from left of screen.
..rrect(rrect: RRect.fromLTRBAndCorners(
10.0,
298.0,
10.0,
302.0,
topLeft: const Radius.circular(2.0),
bottomLeft: const Radius.circular(2.0),
))
// active track RRect Start 10 pixels from left screen.
..rect(rect:const Rect.fromLTRB(10.0, 297.0, 790.0, 303.0),)
// inactive track RRect. Ends 10 pixels from right of screen.
..rrect(rrect: RRect.fromLTRBAndCorners(
790.0,
298.0,
790.0,
302.0,
topRight: const Radius.circular(2.0),
bottomRight: const Radius.circular(2.0),
))
// The thumb Left.
..circle(x: 10.0, y: 300.0, radius: 10.0)
// The thumb Right.
..circle(x: 790.0, y: 300.0, radius: 10.0),
);
});
// Only the thumb, overlay, and tick mark have special shortcuts to provide
// no-op or empty shapes.
//
// The track can also be skipped by providing 0 height.
//
// The value indicator can be skipped by passing the appropriate
// [ShowValueIndicator].
testWidgets('The slider can skip all of its component painting', (WidgetTester tester) async {
// Pump a slider with all shapes skipped.
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
overlayShape: SliderComponentShape.noOverlay,
thumbShape: SliderComponentShape.noThumb,
tickMarkShape: SliderTickMarkShape.noTickMark,
showValueIndicator: ShowValueIndicator.never,
),
value: 0.5,
divisions: 4,
));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
expect(material, paintsExactlyCountTimes(#drawRect, 0));
expect(material, paintsExactlyCountTimes(#drawCircle, 0));
expect(material, paintsExactlyCountTimes(#drawPath, 0));
});
testWidgets('The slider can skip all component painting except the track', (WidgetTester tester) async {
// Pump a slider with just a track.
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
overlayShape: SliderComponentShape.noOverlay,
thumbShape: SliderComponentShape.noThumb,
tickMarkShape: SliderTickMarkShape.noTickMark,
showValueIndicator: ShowValueIndicator.never,
),
value: 0.5,
divisions: 4,
));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
// Only 2 track segments.
expect(material, paintsExactlyCountTimes(#drawRRect, 2));
expect(material, paintsExactlyCountTimes(#drawCircle, 0));
expect(material, paintsExactlyCountTimes(#drawPath, 0));
});
testWidgets('The slider can skip all component painting except the tick marks', (WidgetTester tester) async {
// Pump a slider with just tick marks.
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
overlayShape: SliderComponentShape.noOverlay,
thumbShape: SliderComponentShape.noThumb,
showValueIndicator: ShowValueIndicator.never,
// When the track is hidden to 0 height, a tick mark radius
// must be provided to get a non-zero radius.
tickMarkShape: const RoundSliderTickMarkShape(tickMarkRadius: 1),
),
value: 0.5,
divisions: 4,
));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
// Only 5 tick marks.
expect(material, paintsExactlyCountTimes(#drawRect, 0));
expect(material, paintsExactlyCountTimes(#drawCircle, 5));
expect(material, paintsExactlyCountTimes(#drawPath, 0));
});
testWidgets('The slider can skip all component painting except the thumb', (WidgetTester tester) async {
debugDisableShadows = false;
try {
// Pump a slider with just a thumb.
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
overlayShape: SliderComponentShape.noOverlay,
tickMarkShape: SliderTickMarkShape.noTickMark,
showValueIndicator: ShowValueIndicator.never,
),
value: 0.5,
divisions: 4,
));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
// Only 1 thumb.
expect(material, paintsExactlyCountTimes(#drawRect, 0));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
expect(material, paintsExactlyCountTimes(#drawPath, 0));
} finally {
debugDisableShadows = true;
}
});
testWidgets('The slider can skip all component painting except the overlay', (WidgetTester tester) async {
// Pump a slider with just an overlay.
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
thumbShape: SliderComponentShape.noThumb,
tickMarkShape: SliderTickMarkShape.noTickMark,
showValueIndicator: ShowValueIndicator.never,
),
value: 0.5,
divisions: 4,
));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
// Tap the center of the track and wait for animations to finish.
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
// Only 1 overlay.
expect(material, paintsExactlyCountTimes(#drawRect, 0));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
expect(material, paintsExactlyCountTimes(#drawPath, 0));
await gesture.up();
});
testWidgets('The slider can skip all component painting except the value indicator', (WidgetTester tester) async {
// Pump a slider with just a value indicator.
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
overlayShape: SliderComponentShape.noOverlay,
thumbShape: SliderComponentShape.noThumb,
tickMarkShape: SliderTickMarkShape.noTickMark,
showValueIndicator: ShowValueIndicator.always,
),
value: 0.5,
divisions: 4,
));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Tap the center of the track and wait for animations to finish.
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
// Only 1 value indicator.
expect(material, paintsExactlyCountTimes(#drawRect, 0));
expect(material, paintsExactlyCountTimes(#drawCircle, 0));
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 1));
await gesture.up();
});
testWidgets('PaddleSliderValueIndicatorShape skips all painting at zero scale', (WidgetTester tester) async {
// Pump a slider with just a value indicator.
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
overlayShape: SliderComponentShape.noOverlay,
thumbShape: SliderComponentShape.noThumb,
tickMarkShape: SliderTickMarkShape.noTickMark,
showValueIndicator: ShowValueIndicator.always,
valueIndicatorShape: const PaddleSliderValueIndicatorShape(),
),
value: 0.5,
divisions: 4,
));
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Tap the center of the track to kick off the animation of the value indicator.
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
// Nothing to paint at scale 0.
await tester.pump();
expect(material, paintsExactlyCountTimes(#drawRect, 0));
expect(material, paintsExactlyCountTimes(#drawCircle, 0));
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 0));
// Painting a path for the value indicator.
await tester.pump(const Duration(milliseconds: 16));
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 1));
await gesture.up();
});
testWidgets('Default slider value indicator shape skips all painting at zero scale', (WidgetTester tester) async {
// Pump a slider with just a value indicator.
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
overlayShape: SliderComponentShape.noOverlay,
thumbShape: SliderComponentShape.noThumb,
tickMarkShape: SliderTickMarkShape.noTickMark,
showValueIndicator: ShowValueIndicator.always,
),
value: 0.5,
divisions: 4,
));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Tap the center of the track to kick off the animation of the value indicator.
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
// Nothing to paint at scale 0.
await tester.pump();
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 0));
// Painting a path for the value indicator.
await tester.pump(const Duration(milliseconds: 16));
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 1));
await gesture.up();
});
testWidgets('Default paddle range slider value indicator shape draws correctly', (WidgetTester tester) async {
debugDisableShadows = false;
try {
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
);
final SliderThemeData sliderTheme = theme.sliderTheme.copyWith(
thumbColor: Colors.red.shade500,
showValueIndicator: ShowValueIndicator.always,
rangeValueIndicatorShape: const PaddleRangeSliderValueIndicatorShape(),
);
await tester.pumpWidget(_buildRangeApp(sliderTheme));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(RangeSlider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
// physical model
..rrect()
..rrect(rrect: RRect.fromLTRBAndCorners(
24.0, 298.0, 24.0, 302.0,
topLeft: const Radius.circular(2.0),
bottomLeft: const Radius.circular(2.0),
))
..rect(rect: const Rect.fromLTRB(24.0, 297.0, 24.0, 303.0))
..rrect(rrect: RRect.fromLTRBAndCorners(
24.0, 298.0, 776.0, 302.0,
topRight: const Radius.circular(2.0),
bottomRight: const Radius.circular(2.0),
))
..circle(x: 24.0, y: 300.0)
..shadow(elevation: 1.0)
..circle(x: 24.0, y: 300.0)
..shadow(elevation: 6.0)
..circle(x: 24.0, y: 300.0),
);
await gesture.up();
} finally {
debugDisableShadows = true;
}
});
testWidgets('Default paddle range slider value indicator shape draws correctly with debugDisableShadows', (WidgetTester tester) async {
debugDisableShadows = true;
final ThemeData theme = ThemeData(
platform: TargetPlatform.android,
primarySwatch: Colors.blue,
);
final SliderThemeData sliderTheme = theme.sliderTheme.copyWith(
thumbColor: Colors.red.shade500,
showValueIndicator: ShowValueIndicator.always,
rangeValueIndicatorShape: const PaddleRangeSliderValueIndicatorShape(),
);
await tester.pumpWidget(_buildRangeApp(sliderTheme));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(RangeSlider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
// physical model
..rrect()
..rrect(rrect: RRect.fromLTRBAndCorners(
24.0, 298.0, 24.0, 302.0,
topLeft: const Radius.circular(2.0),
bottomLeft: const Radius.circular(2.0),
))
..rect(rect: const Rect.fromLTRB(24.0, 297.0, 24.0, 303.0))
..rrect(rrect: RRect.fromLTRBAndCorners(
24.0, 298.0, 776.0, 302.0,
topRight: const Radius.circular(2.0),
bottomRight: const Radius.circular(2.0),
))
..circle(x: 24.0, y: 300.0)
..path(strokeWidth: 1.0 * 2.0, color: Colors.black)
..circle(x: 24.0, y: 300.0)
..path(strokeWidth: 6.0 * 2.0, color: Colors.black)
..circle(x: 24.0, y: 300.0),
);
await gesture.up();
});
testWidgets('PaddleRangeSliderValueIndicatorShape skips all painting at zero scale', (WidgetTester tester) async {
debugDisableShadows = false;
try {
// Pump a slider with just a value indicator.
await tester.pumpWidget(_buildRangeApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
rangeValueIndicatorShape: const PaddleRangeSliderValueIndicatorShape(),
),
values: const RangeValues(0, 0.5),
divisions: 4,
));
// final RenderBox sliderBox = tester.firstRenderObject<RenderBox>(find.byType(RangeSlider));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Tap the center of the track to kick off the animation of the value indicator.
final Offset center = tester.getCenter(find.byType(RangeSlider));
final TestGesture gesture = await tester.startGesture(center);
// No value indicator path to paint at scale 0.
await tester.pump();
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 0));
// Painting a path for each value indicator.
await tester.pump(const Duration(milliseconds: 16));
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 2));
await gesture.up();
} finally {
debugDisableShadows = true;
}
});
testWidgets('Default range indicator shape skips all painting at zero scale', (WidgetTester tester) async {
debugDisableShadows = false;
try {
// Pump a slider with just a value indicator.
await tester.pumpWidget(_buildRangeApp(
ThemeData().sliderTheme.copyWith(
trackHeight: 0,
overlayShape: SliderComponentShape.noOverlay,
thumbShape: SliderComponentShape.noThumb,
tickMarkShape: SliderTickMarkShape.noTickMark,
showValueIndicator: ShowValueIndicator.always,
),
values: const RangeValues(0, 0.5),
divisions: 4,
));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Tap the center of the track to kick off the animation of the value indicator.
final Offset center = tester.getCenter(find.byType(RangeSlider));
final TestGesture gesture = await tester.startGesture(center);
// No value indicator path to paint at scale 0.
await tester.pump();
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 0));
// Painting a path for each value indicator.
await tester.pump(const Duration(milliseconds: 16));
expect(valueIndicatorBox, paintsExactlyCountTimes(#drawPath, 2));
await gesture.up();
} finally {
debugDisableShadows = true;
}
});
testWidgets('activeTrackRadius is taken into account when painting the border of the active track', (WidgetTester tester) async {
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
trackShape: const RoundedRectSliderTrackShapeWithCustomAdditionalActiveTrackHeight(
additionalActiveTrackHeight: 10.0
)
)
));
await tester.pumpAndSettle();
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
expect(
find.byType(Slider),
paints
..rrect(rrect: RRect.fromLTRBAndCorners(
24.0, 293.0, 24.0, 307.0,
topLeft: const Radius.circular(7.0),
bottomLeft: const Radius.circular(7.0),
))
..rrect(rrect: RRect.fromLTRBAndCorners(
24.0, 298.0, 776.0, 302.0,
topRight: const Radius.circular(2.0),
bottomRight: const Radius.circular(2.0),
)),
);
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
testWidgets('The mouse cursor is themeable', (WidgetTester tester) async {
await tester.pumpWidget(_buildApp(
ThemeData().sliderTheme.copyWith(
mouseCursor: const MaterialStatePropertyAll<MouseCursor>(SystemMouseCursors.text),
)
));
await tester.pumpAndSettle();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Slider)));
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
});
testWidgets('SliderTheme.allowedInteraction is themeable', (WidgetTester tester) async {
double value = 0.0;
Widget buildApp({
bool isAllowedInteractionInThemeNull = false,
bool isAllowedInteractionInSliderNull = false,
}) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SliderTheme(
data: ThemeData().sliderTheme.copyWith(
allowedInteraction: isAllowedInteractionInThemeNull
? null
: SliderInteraction.slideOnly,
),
child: StatefulBuilder(
builder: (_, void Function(void Function()) setState) {
return Slider(
value: value,
allowedInteraction: isAllowedInteractionInSliderNull
? null
: SliderInteraction.tapOnly,
onChanged: (double newValue) {
setState(() {
value = newValue;
});
},
);
}
),
),
),
),
);
}
final TestGesture gesture = await tester.createGesture();
// when theme and parameter are specified, parameter is used [tapOnly].
await tester.pumpWidget(buildApp());
// tap is allowed.
value = 0.0;
await gesture.down(tester.getCenter(find.byType(Slider)));
await tester.pump();
expect(value, equals(0.5)); // changes
await gesture.up();
// slide isn't allowed.
value = 0.0;
await gesture.down(tester.getCenter(find.byType(Slider)));
await tester.pump();
await gesture.moveBy(const Offset(50, 0));
expect(value, equals(0.0)); // no change
await gesture.up();
// when only parameter is specified, parameter is used [tapOnly].
await tester.pumpWidget(buildApp(isAllowedInteractionInThemeNull: true));
// tap is allowed.
value = 0.0;
await gesture.down(tester.getCenter(find.byType(Slider)));
await tester.pump();
expect(value, equals(0.5)); // changes
await gesture.up();
// slide isn't allowed.
value = 0.0;
await gesture.down(tester.getCenter(find.byType(Slider)));
await tester.pump();
await gesture.moveBy(const Offset(50, 0));
expect(value, equals(0.0)); // no change
await gesture.up();
// when theme is specified but parameter is null, theme is used [slideOnly].
await tester.pumpWidget(buildApp(isAllowedInteractionInSliderNull: true));
// tap isn't allowed.
value = 0.0;
await gesture.down(tester.getCenter(find.byType(Slider)));
await tester.pump();
expect(value, equals(0.0)); // no change
await gesture.up();
// slide isn't allowed.
value = 0.0;
await gesture.down(tester.getCenter(find.byType(Slider)));
await tester.pump();
await gesture.moveBy(const Offset(50, 0));
expect(value, greaterThan(0.0)); // changes
await gesture.up();
// when both theme and parameter are null, default is used [tapAndSlide].
await tester.pumpWidget(buildApp(
isAllowedInteractionInSliderNull: true,
isAllowedInteractionInThemeNull: true,
));
// tap is allowed.
value = 0.0;
await gesture.down(tester.getCenter(find.byType(Slider)));
await tester.pump();
expect(value, equals(0.5));
await gesture.up();
// slide is allowed.
value = 0.0;
await gesture.down(tester.getCenter(find.byType(Slider)));
await tester.pump();
await gesture.moveBy(const Offset(50, 0));
expect(value, greaterThan(0.0)); // changes
await gesture.up();
});
testWidgets('Default value indicator color', (WidgetTester tester) async {
debugDisableShadows = false;
try {
final ThemeData theme = ThemeData(
useMaterial3: true,
platform: TargetPlatform.android,
);
Widget buildApp(String value, { double sliderValue = 0.5, TextScaler textScaler = TextScaler.noScaling }) {
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: Material(
child: Row(
children: <Widget>[
Expanded(
child: Slider(
value: sliderValue,
label: value,
divisions: 3,
onChanged: (double d) { },
),
),
],
),
),
),
),
);
}
await tester.pumpWidget(buildApp('1'));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..rrect(color: const Color(0xfffef7ff))
..rrect(color: const Color(0xff6750a4))
..rrect(color: const Color(0xffe6e0e9))
..path(color: Color(theme.colorScheme.primary.value))
);
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
} finally {
debugDisableShadows = true;
}
});
testWidgets('RectangularSliderValueIndicatorShape supports SliderTheme.valueIndicatorStrokeColor', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
sliderTheme: const SliderThemeData(
showValueIndicator: ShowValueIndicator.always,
valueIndicatorShape: RectangularSliderValueIndicatorShape(),
valueIndicatorColor: Color(0xff000001),
valueIndicatorStrokeColor: Color(0xff000002),
),
);
const double value = 0.5;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Slider(
value: value,
label: '$value',
onChanged: (double newValue) {},
),
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(Slider));
await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor),
);
});
testWidgets('PaddleSliderValueIndicatorShape supports SliderTheme.valueIndicatorStrokeColor', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
sliderTheme: const SliderThemeData(
showValueIndicator: ShowValueIndicator.always,
valueIndicatorShape: PaddleSliderValueIndicatorShape(),
valueIndicatorColor: Color(0xff000001),
valueIndicatorStrokeColor: Color(0xff000002),
),
);
const double value = 0.5;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Slider(
value: value,
label: '$value',
onChanged: (double newValue) {},
),
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(Slider));
await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor),
);
});
testWidgets('DropSliderValueIndicatorShape supports SliderTheme.valueIndicatorStrokeColor', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
sliderTheme: const SliderThemeData(
showValueIndicator: ShowValueIndicator.always,
valueIndicatorShape: DropSliderValueIndicatorShape(),
valueIndicatorColor: Color(0xff000001),
valueIndicatorStrokeColor: Color(0xff000002),
),
);
const double value = 0.5;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Slider(
value: value,
label: '$value',
onChanged: (double newValue) {},
),
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(Slider));
await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor),
);
});
testWidgets('RectangularRangeSliderValueIndicatorShape supports SliderTheme.valueIndicatorStrokeColor', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
sliderTheme: const SliderThemeData(
showValueIndicator: ShowValueIndicator.always,
rangeValueIndicatorShape: RectangularRangeSliderValueIndicatorShape(),
valueIndicatorColor: Color(0xff000001),
valueIndicatorStrokeColor: Color(0xff000002),
)
);
RangeValues values = const RangeValues(0, 0.5);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: RangeSlider(
values: values,
labels: RangeLabels(
values.start.toString(),
values.end.toString(),
),
onChanged: (RangeValues val) {
values = val;
},
),
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(RangeSlider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor)
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor)
);
await gesture.up();
});
testWidgets('RectangularRangeSliderValueIndicatorShape supports SliderTheme.valueIndicatorStrokeColor on overlapping indicator', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
sliderTheme: const SliderThemeData(
showValueIndicator: ShowValueIndicator.always,
rangeValueIndicatorShape: RectangularRangeSliderValueIndicatorShape(),
valueIndicatorColor: Color(0xff000001),
valueIndicatorStrokeColor: Color(0xff000002),
overlappingShapeStrokeColor: Color(0xff000003),
)
);
RangeValues values = const RangeValues(0.0, 0.0);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: RangeSlider(
values: values,
labels: RangeLabels(
values.start.toString(),
values.end.toString(),
),
onChanged: (RangeValues val) {
values = val;
},
),
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(RangeSlider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor)
..path(color: theme.sliderTheme.overlappingShapeStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor)
);
await gesture.up();
});
testWidgets('PaddleRangeSliderValueIndicatorShape supports SliderTheme.valueIndicatorStrokeColor', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
sliderTheme: const SliderThemeData(
showValueIndicator: ShowValueIndicator.always,
rangeValueIndicatorShape: PaddleRangeSliderValueIndicatorShape(),
valueIndicatorColor: Color(0xff000001),
valueIndicatorStrokeColor: Color(0xff000002),
)
);
RangeValues values = const RangeValues(0, 0.5);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: RangeSlider(
values: values,
labels: RangeLabels(
values.start.toString(),
values.end.toString(),
),
onChanged: (RangeValues val) {
values = val;
},
),
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(RangeSlider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor)
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor)
);
await gesture.up();
});
testWidgets('PaddleRangeSliderValueIndicatorShape supports SliderTheme.valueIndicatorStrokeColor on overlapping indicator', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
sliderTheme: const SliderThemeData(
showValueIndicator: ShowValueIndicator.always,
rangeValueIndicatorShape: PaddleRangeSliderValueIndicatorShape(),
valueIndicatorColor: Color(0xff000001),
valueIndicatorStrokeColor: Color(0xff000002),
overlappingShapeStrokeColor: Color(0xff000003),
)
);
RangeValues values = const RangeValues(0, 0);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: RangeSlider(
values: values,
labels: RangeLabels(
values.start.toString(),
values.end.toString(),
),
onChanged: (RangeValues val) {
values = val;
},
),
),
),
),
);
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(RangeSlider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.colorScheme.shadow) // shadow
..path(color: theme.sliderTheme.valueIndicatorStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor)
..path(color: theme.sliderTheme.overlappingShapeStrokeColor)
..path(color: theme.sliderTheme.valueIndicatorColor)
);
await gesture.up();
});
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('Slider defaults', (WidgetTester tester) async {
debugDisableShadows = false;
final ThemeData theme = ThemeData(useMaterial3: false);
const double trackHeight = 4.0;
final ColorScheme colorScheme = theme.colorScheme;
final Color activeTrackColor = Color(colorScheme.primary.value);
final Color inactiveTrackColor = colorScheme.primary.withOpacity(0.24);
final Color secondaryActiveTrackColor = colorScheme.primary.withOpacity(0.54);
final Color disabledActiveTrackColor = colorScheme.onSurface.withOpacity(0.32);
final Color disabledInactiveTrackColor = colorScheme.onSurface.withOpacity(0.12);
final Color disabledSecondaryActiveTrackColor = colorScheme.onSurface.withOpacity(0.12);
final Color shadowColor = colorScheme.shadow;
final Color thumbColor = Color(colorScheme.primary.value);
final Color disabledThumbColor = Color.alphaBlend(colorScheme.onSurface.withOpacity(.38), colorScheme.surface);
final Color activeTickMarkColor = colorScheme.onPrimary.withOpacity(0.54);
final Color inactiveTickMarkColor = colorScheme.primary.withOpacity(0.54);
final Color disabledActiveTickMarkColor = colorScheme.onPrimary.withOpacity(0.12);
final Color disabledInactiveTickMarkColor = colorScheme.onSurface.withOpacity(0.12);
final Color valueIndicatorColor = Color.alphaBlend(colorScheme.onSurface.withOpacity(0.60), colorScheme.surface.withOpacity(0.90));
try {
double value = 0.45;
Widget buildApp({
int? divisions,
bool enabled = true,
}) {
final ValueChanged<double>? onChanged = !enabled
? null
: (double d) {
value = d;
};
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Slider(
value: value,
secondaryTrackValue: 0.75,
label: '$value',
divisions: divisions,
onChanged: onChanged,
),
),
),
),
);
}
await tester.pumpWidget(buildApp());
final MaterialInkController material = Material.of(tester.element(find.byType(Slider)));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
// Test default track height.
const Radius radius = Radius.circular(trackHeight / 2);
const Radius activatedRadius = Radius.circular((trackHeight + 2) / 2);
expect(
material,
paints
..rrect(rrect: RRect.fromLTRBAndCorners(24.0, 297.0, 362.4, 303.0, topLeft: activatedRadius, bottomLeft: activatedRadius), color: activeTrackColor)
..rrect(rrect: RRect.fromLTRBAndCorners(362.4, 298.0, 776.0, 302.0, topRight: radius, bottomRight: radius), color: inactiveTrackColor),
);
// Test default colors for enabled slider.
expect(material, paints..rrect(color: activeTrackColor)..rrect(color: inactiveTrackColor)..rrect(color: secondaryActiveTrackColor));
expect(material, paints..shadow(color: shadowColor));
expect(material, paints..circle(color: thumbColor));
expect(material, isNot(paints..circle(color: disabledThumbColor)));
expect(material, isNot(paints..rrect(color: disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: disabledSecondaryActiveTrackColor)));
expect(material, isNot(paints..circle(color: activeTickMarkColor)));
expect(material, isNot(paints..circle(color: inactiveTickMarkColor)));
// Test defaults colors for discrete slider.
await tester.pumpWidget(buildApp(divisions: 3));
expect(material, paints..rrect(color: activeTrackColor)..rrect(color: inactiveTrackColor)..rrect(color: secondaryActiveTrackColor));
expect(
material,
paints
..circle(color: activeTickMarkColor)
..circle(color: activeTickMarkColor)
..circle(color: inactiveTickMarkColor)
..circle(color: inactiveTickMarkColor)
..shadow(color: Colors.black)
..circle(color: thumbColor),
);
expect(material, isNot(paints..circle(color: disabledThumbColor)));
expect(material, isNot(paints..rrect(color: disabledActiveTrackColor)));
expect(material, isNot(paints..rrect(color: disabledInactiveTrackColor)));
expect(material, isNot(paints..rrect(color: disabledSecondaryActiveTrackColor)));
// Test defaults colors for disabled slider.
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
material,
paints
..rrect(color: disabledActiveTrackColor)
..rrect(color: disabledInactiveTrackColor)
..rrect(color: disabledSecondaryActiveTrackColor),
);
expect(material, paints..shadow(color: Colors.black)..circle(color: disabledThumbColor));
expect(material, isNot(paints..circle(color: thumbColor)));
expect(material, isNot(paints..rrect(color: activeTrackColor)));
expect(material, isNot(paints..rrect(color: inactiveTrackColor)));
expect(material, isNot(paints..rrect(color: secondaryActiveTrackColor)));
// Test defaults colors for disabled discrete slider.
await tester.pumpWidget(buildApp(divisions: 3, enabled: false));
expect(
material,
paints
..circle(color: disabledActiveTickMarkColor)
..circle(color: disabledActiveTickMarkColor)
..circle(color: disabledInactiveTickMarkColor)
..circle(color: disabledInactiveTickMarkColor)
..shadow(color: Colors.black)
..circle(color: disabledThumbColor),
);
expect(material, isNot(paints..circle(color: thumbColor)));
expect(material, isNot(paints..rrect(color: activeTrackColor)));
expect(material, isNot(paints..rrect(color: inactiveTrackColor)));
expect(material, isNot(paints..rrect(color: secondaryActiveTrackColor)));
expect(material, isNot(paints..circle(color: activeTickMarkColor)));
expect(material, isNot(paints..circle(color: inactiveTickMarkColor)));
// Test the default color for value indicator.
await tester.pumpWidget(buildApp(divisions: 3));
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(value, equals(2.0 / 3.0));
expect(
valueIndicatorBox,
paints
..path(color: valueIndicatorColor)
..paragraph(),
);
await gesture.up();
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
} finally {
debugDisableShadows = true;
}
});
testWidgets('Default value indicator color', (WidgetTester tester) async {
debugDisableShadows = false;
try {
final ThemeData theme = ThemeData(
useMaterial3: false,
platform: TargetPlatform.android,
);
Widget buildApp(String value, { double sliderValue = 0.5, TextScaler textScaler = TextScaler.noScaling }) {
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: Material(
child: Row(
children: <Widget>[
Expanded(
child: Slider(
value: sliderValue,
label: value,
divisions: 3,
onChanged: (double d) { },
),
),
],
),
),
),
),
);
}
await tester.pumpWidget(buildApp('1'));
final RenderBox valueIndicatorBox = tester.renderObject(find.byType(Overlay));
final Offset center = tester.getCenter(find.byType(Slider));
final TestGesture gesture = await tester.startGesture(center);
// Wait for value indicator animation to finish.
await tester.pumpAndSettle();
expect(
valueIndicatorBox,
paints
..rrect(color: const Color(0xfffafafa))
..rrect(color: const Color(0xff2196f3))
..rrect(color: const Color(0x3d2196f3))
// Test that the value indicator text is painted with the correct color.
..path(color: const Color(0xf55f5f5f))
);
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
} finally {
debugDisableShadows = true;
}
});
});
}
class RoundedRectSliderTrackShapeWithCustomAdditionalActiveTrackHeight extends RoundedRectSliderTrackShape {
const RoundedRectSliderTrackShapeWithCustomAdditionalActiveTrackHeight({required this.additionalActiveTrackHeight});
final double additionalActiveTrackHeight;
@override
void paint(
PaintingContext context,
Offset offset, {
required RenderBox parentBox,
required SliderThemeData sliderTheme,
required Animation<double> enableAnimation,
required TextDirection textDirection,
required Offset thumbCenter,
Offset? secondaryOffset,
bool isDiscrete = false,
bool isEnabled = false,
double additionalActiveTrackHeight = 2.0,
}) {
super.paint(context, offset, parentBox: parentBox, sliderTheme: sliderTheme, enableAnimation: enableAnimation, textDirection: textDirection, thumbCenter: thumbCenter, secondaryOffset: secondaryOffset, additionalActiveTrackHeight: this.additionalActiveTrackHeight);
}
}
Widget _buildApp(
SliderThemeData sliderTheme, {
double value = 0.0,
double? secondaryTrackValue,
bool enabled = true,
int? divisions,
FocusNode? focusNode,
}) {
final ValueChanged<double>? onChanged = enabled ? (double d) => value = d : null;
return MaterialApp(
home: Scaffold(
body: Center(
child: SliderTheme(
data: sliderTheme,
child: Slider(
value: value,
secondaryTrackValue: secondaryTrackValue,
label: '$value',
onChanged: onChanged,
divisions: divisions,
focusNode: focusNode,
),
),
),
),
);
}
Widget _buildRangeApp(
SliderThemeData sliderTheme, {
RangeValues values = const RangeValues(0, 0),
bool enabled = true,
int? divisions,
}) {
final ValueChanged<RangeValues>? onChanged = enabled ? (RangeValues d) => values = d : null;
return MaterialApp(
home: Scaffold(
body: Center(
child: SliderTheme(
data: sliderTheme,
child: RangeSlider(
values: values,
labels: RangeLabels(values.start.toString(), values.end.toString()),
onChanged: onChanged,
divisions: divisions,
),
),
),
),
);
}
| flutter/packages/flutter/test/material/slider_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/slider_theme_test.dart",
"repo_id": "flutter",
"token_count": 44384
} | 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.
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
// Regression test for https://github.com/flutter/flutter/issues/87099
testWidgets('TextField.autofocus should skip the element that never layout', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Navigator(
pages: const <Page<void>>[_APage(), _BPage()],
onPopPage: (Route<dynamic> route, dynamic result) {
return false;
},
),
),
),
);
expect(tester.takeException(), isNull);
});
testWidgets('Dialog interaction', (WidgetTester tester) async {
expect(tester.testTextInput.isVisible, isFalse);
final FocusNode focusNode = FocusNode(debugLabel: 'Editable Text Node');
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextField(
focusNode: focusNode,
autofocus: true,
),
),
),
),
);
expect(tester.testTextInput.isVisible, isTrue);
expect(focusNode.hasPrimaryFocus, isTrue);
final BuildContext context = tester.element(find.byType(TextField));
showDialog<void>(
context: context,
builder: (BuildContext context) => const SimpleDialog(title: Text('Dialog')),
);
await tester.pump();
expect(tester.testTextInput.isVisible, isFalse);
Navigator.of(tester.element(find.text('Dialog'))).pop();
await tester.pump();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(tester.testTextInput.isVisible, isTrue);
await tester.pumpWidget(Container());
expect(tester.testTextInput.isVisible, isFalse);
});
testWidgets('Request focus shows keyboard', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextField(
focusNode: focusNode,
),
),
),
),
);
expect(tester.testTextInput.isVisible, isFalse);
FocusScope.of(tester.element(find.byType(TextField))).requestFocus(focusNode);
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
await tester.pumpWidget(Container());
expect(tester.testTextInput.isVisible, isFalse);
});
testWidgets('Autofocus shows keyboard', (WidgetTester tester) async {
expect(tester.testTextInput.isVisible, isFalse);
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Center(
child: TextField(
autofocus: true,
),
),
),
),
);
expect(tester.testTextInput.isVisible, isTrue);
await tester.pumpWidget(Container());
expect(tester.testTextInput.isVisible, isFalse);
});
testWidgets('Tap shows keyboard', (WidgetTester tester) async {
expect(tester.testTextInput.isVisible, isFalse);
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Center(
child: TextField(),
),
),
),
);
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byType(TextField));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
// Prevent the gesture recognizer from recognizing the next tap as a
// double-tap.
await tester.pump(const Duration(seconds: 1));
tester.testTextInput.hide();
final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText));
state.connectionClosed();
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byType(TextField));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
await tester.pumpWidget(Container());
expect(tester.testTextInput.isVisible, isFalse);
});
testWidgets('Focus triggers keep-alive', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: ListView(
children: <Widget>[
TextField(
focusNode: focusNode,
),
Container(
height: 1000.0,
),
],
),
),
),
);
expect(find.byType(TextField), findsOneWidget);
expect(tester.testTextInput.isVisible, isFalse);
FocusScope.of(tester.element(find.byType(TextField))).requestFocus(focusNode);
await tester.pump();
expect(find.byType(TextField), findsOneWidget);
expect(tester.testTextInput.isVisible, isTrue);
await tester.drag(find.byType(TextField), const Offset(0.0, -1000.0));
await tester.pump();
expect(find.byType(TextField, skipOffstage: false), findsOneWidget);
expect(tester.testTextInput.isVisible, isTrue);
focusNode.unfocus();
await tester.pump();
expect(find.byType(TextField), findsNothing);
expect(tester.testTextInput.isVisible, isFalse);
});
testWidgets('Focus keep-alive works with GlobalKey reparenting', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
Widget makeTest(String? prefix) {
return MaterialApp(
home: Material(
child: ListView(
children: <Widget>[
TextField(
focusNode: focusNode,
decoration: InputDecoration(
prefixText: prefix,
),
),
Container(
height: 1000.0,
),
],
),
),
);
}
await tester.pumpWidget(makeTest(null));
FocusScope.of(tester.element(find.byType(TextField))).requestFocus(focusNode);
await tester.pump();
expect(find.byType(TextField), findsOneWidget);
await tester.drag(find.byType(TextField), const Offset(0.0, -1000.0));
await tester.pump();
expect(find.byType(TextField, skipOffstage: false), findsOneWidget);
await tester.pumpWidget(makeTest('test'));
await tester.pump(); // in case the AutomaticKeepAlive widget thinks it needs a cleanup frame
expect(find.byType(TextField, skipOffstage: false), findsOneWidget);
});
testWidgets('TextField with decoration:null', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/16880
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Center(
child: TextField(
decoration: null,
),
),
),
),
);
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byType(TextField));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
});
testWidgets('Sibling FocusScopes', (WidgetTester tester) async {
expect(tester.testTextInput.isVisible, isFalse);
final FocusScopeNode focusScopeNode0 = FocusScopeNode();
addTearDown(focusScopeNode0.dispose);
final FocusScopeNode focusScopeNode1 = FocusScopeNode();
addTearDown(focusScopeNode1.dispose);
final Key textField0 = UniqueKey();
final Key textField1 = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FocusScope(
node: focusScopeNode0,
child: Builder(
builder: (BuildContext context) => TextField(key: textField0),
),
),
FocusScope(
node: focusScopeNode1,
child: Builder(
builder: (BuildContext context) => TextField(key: textField1),
),
),
],
),
),
),
),
);
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byKey(textField0));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
tester.testTextInput.hide();
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byKey(textField1));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
await tester.tap(find.byKey(textField0));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
await tester.tap(find.byKey(textField1));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
tester.testTextInput.hide();
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byKey(textField0));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
await tester.pumpWidget(Container());
expect(tester.testTextInput.isVisible, isFalse);
});
testWidgets('Sibling Navigators', (WidgetTester tester) async {
expect(tester.testTextInput.isVisible, isFalse);
final Key textField0 = UniqueKey();
final Key textField1 = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: Column(
children: <Widget>[
Expanded(
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return TextField(key: textField0);
},
settings: settings,
);
},
),
),
Expanded(
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return TextField(key: textField1);
},
settings: settings,
);
},
),
),
],
),
),
),
),
);
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byKey(textField0));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
tester.testTextInput.hide();
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byKey(textField1));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
await tester.tap(find.byKey(textField0));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
await tester.tap(find.byKey(textField1));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
tester.testTextInput.hide();
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byKey(textField0));
await tester.idle();
expect(tester.testTextInput.isVisible, isTrue);
await tester.pumpWidget(Container());
expect(tester.testTextInput.isVisible, isFalse);
});
testWidgets('A Focused text-field will lose focus when clicking outside of its hitbox with a mouse on desktop', (WidgetTester tester) async {
final FocusNode focusNodeA = FocusNode();
addTearDown(focusNodeA.dispose);
final FocusNode focusNodeB = FocusNode();
addTearDown(focusNodeB.dispose);
final Key key = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: ListView(
children: <Widget>[
TextField(
focusNode: focusNodeA,
),
Container(
key: key,
height: 200,
),
TextField(
focusNode: focusNodeB,
),
],
),
),
),
);
final TestGesture down1 = await tester.startGesture(tester.getCenter(find.byType(TextField).first), kind: PointerDeviceKind.mouse);
await tester.pump();
await tester.pumpAndSettle();
await down1.up();
await down1.removePointer();
expect(focusNodeA.hasFocus, true);
expect(focusNodeB.hasFocus, false);
// Click on the container to not hit either text field.
final TestGesture down2 = await tester.startGesture(tester.getCenter(find.byKey(key)), kind: PointerDeviceKind.mouse);
await tester.pump();
await tester.pumpAndSettle();
await down2.up();
await down2.removePointer();
expect(focusNodeA.hasFocus, false);
expect(focusNodeB.hasFocus, false);
// Second text field can still gain focus.
final TestGesture down3 = await tester.startGesture(tester.getCenter(find.byType(TextField).last), kind: PointerDeviceKind.mouse);
await tester.pump();
await tester.pumpAndSettle();
await down3.up();
await down3.removePointer();
expect(focusNodeA.hasFocus, false);
expect(focusNodeB.hasFocus, true);
}, variant: TargetPlatformVariant.desktop());
testWidgets('A Focused text-field will not lose focus when clicking on its decoration', (WidgetTester tester) async {
final FocusNode focusNodeA = FocusNode();
addTearDown(focusNodeA.dispose);
final Key iconKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: ListView(
children: <Widget>[
TextField(
focusNode: focusNodeA,
decoration: InputDecoration(
icon: Icon(Icons.copy_all, key: iconKey),
),
),
],
),
),
),
);
final TestGesture down1 = await tester.startGesture(tester.getCenter(find.byType(TextField).first), kind: PointerDeviceKind.mouse);
await tester.pump();
await down1.removePointer();
expect(focusNodeA.hasFocus, true);
// Click on the icon which has a different RO than the text field's focus node context
final TestGesture down2 = await tester.startGesture(tester.getCenter(find.byKey(iconKey)), kind: PointerDeviceKind.mouse);
await tester.pump();
await tester.pumpAndSettle();
await down2.up();
await down2.removePointer();
expect(focusNodeA.hasFocus, true);
}, variant: TargetPlatformVariant.desktop());
testWidgets('A Focused text-field will lose focus when clicking outside of its hitbox with a mouse on desktop after tab navigation', (WidgetTester tester) async {
final FocusNode focusNodeA = FocusNode(debugLabel: 'A');
addTearDown(focusNodeA.dispose);
final FocusNode focusNodeB = FocusNode(debugLabel: 'B');
addTearDown(focusNodeB.dispose);
final Key key = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: ListView(
children: <Widget>[
const TextField(),
const TextField(),
TextField(
focusNode: focusNodeA,
),
Container(
key: key,
height: 200,
),
TextField(
focusNode: focusNodeB,
),
],
),
),
),
);
// Tab over to the 3rd text field.
for (int i = 0; i < 3; i += 1) {
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
}
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
);
await gesture.up();
await gesture.removePointer();
}
expect(focusNodeA.hasFocus, true);
expect(focusNodeB.hasFocus, false);
// Click on the container to not hit either text field.
await click(find.byKey(key));
await tester.pump();
expect(focusNodeA.hasFocus, false);
expect(focusNodeB.hasFocus, false);
// Second text field can still gain focus.
await click(find.byType(TextField).last);
await tester.pump();
expect(focusNodeA.hasFocus, false);
expect(focusNodeB.hasFocus, true);
}, variant: TargetPlatformVariant.desktop());
}
class _APage extends Page<void> {
const _APage();
@override
Route<void> createRoute(BuildContext context) => PageRouteBuilder<void>(
settings: this,
pageBuilder: (_, __, ___) => const TextField(autofocus: true),
);
}
class _BPage extends Page<void> {
const _BPage();
@override
Route<void> createRoute(BuildContext context) => PageRouteBuilder<void>(
settings: this,
pageBuilder: (_, __, ___) => const Text('B'),
);
}
| flutter/packages/flutter/test/material/text_field_focus_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/text_field_focus_test.dart",
"repo_id": "flutter",
"token_count": 7543
} | 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('TimePickerThemeData copyWith, ==, hashCode basics', () {
expect(const TimePickerThemeData(), const TimePickerThemeData().copyWith());
expect(const TimePickerThemeData().hashCode, const TimePickerThemeData().copyWith().hashCode);
});
test('TimePickerThemeData lerp special cases', () {
const TimePickerThemeData data = TimePickerThemeData();
expect(identical(TimePickerThemeData.lerp(data, data, 0.5), data), true);
});
test('TimePickerThemeData has null fields by default', () {
const TimePickerThemeData timePickerTheme = TimePickerThemeData();
expect(timePickerTheme.backgroundColor, null);
expect(timePickerTheme.cancelButtonStyle, null);
expect(timePickerTheme.confirmButtonStyle, null);
expect(timePickerTheme.dayPeriodBorderSide, null);
expect(timePickerTheme.dayPeriodColor, null);
expect(timePickerTheme.dayPeriodShape, null);
expect(timePickerTheme.dayPeriodTextColor, null);
expect(timePickerTheme.dayPeriodTextStyle, null);
expect(timePickerTheme.dialBackgroundColor, null);
expect(timePickerTheme.dialHandColor, null);
expect(timePickerTheme.dialTextColor, null);
expect(timePickerTheme.dialTextStyle, null);
expect(timePickerTheme.elevation, null);
expect(timePickerTheme.entryModeIconColor, null);
expect(timePickerTheme.helpTextStyle, null);
expect(timePickerTheme.hourMinuteColor, null);
expect(timePickerTheme.hourMinuteShape, null);
expect(timePickerTheme.hourMinuteTextColor, null);
expect(timePickerTheme.hourMinuteTextStyle, null);
expect(timePickerTheme.inputDecorationTheme, null);
expect(timePickerTheme.entryModeIconColor, null);
expect(timePickerTheme.padding, null);
expect(timePickerTheme.shape, null);
expect(timePickerTheme.timeSelectorSeparatorColor, null);
expect(timePickerTheme.timeSelectorSeparatorTextStyle, null);
});
testWidgets('Default TimePickerThemeData debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const TimePickerThemeData().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('TimePickerThemeData implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const TimePickerThemeData(
backgroundColor: Color(0xfffffff0),
cancelButtonStyle: ButtonStyle(foregroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffff1))),
confirmButtonStyle: ButtonStyle(foregroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffff2))),
dayPeriodBorderSide: BorderSide(color: Color(0xfffffff3)),
dayPeriodColor: Color(0x00000000),
dayPeriodShape: RoundedRectangleBorder(
side: BorderSide(color: Color(0xfffffff5)),
),
dayPeriodTextColor: Color(0xfffffff6),
dayPeriodTextStyle: TextStyle(color: Color(0xfffffff7)),
dialBackgroundColor: Color(0xfffffff8),
dialHandColor: Color(0xfffffff9),
dialTextColor: Color(0xfffffffa),
dialTextStyle: TextStyle(color: Color(0xfffffffb)),
elevation: 1.0,
entryModeIconColor: Color(0xfffffffc),
helpTextStyle: TextStyle(color: Color(0xfffffffd)),
hourMinuteColor: Color(0xfffffffe),
hourMinuteShape: RoundedRectangleBorder(
side: BorderSide(color: Color(0xffffffff)),
),
hourMinuteTextColor: Color(0xfffffff0),
hourMinuteTextStyle: TextStyle(color: Color(0xfffffff1)),
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(color: Color(0xfffffff2)),
),
padding: EdgeInsets.all(1.0),
shape: RoundedRectangleBorder(
side: BorderSide(color: Color(0xfffffff3)),
),
timeSelectorSeparatorColor: WidgetStatePropertyAll<Color>(Color(0xfffffff4)),
timeSelectorSeparatorTextStyle: WidgetStatePropertyAll<TextStyle>(TextStyle(color: Color(0xfffffff5))),
).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(0xfffffff0)',
'cancelButtonStyle: ButtonStyle#00000(foregroundColor: WidgetStatePropertyAll(Color(0xfffffff1)))',
'confirmButtonStyle: ButtonStyle#00000(foregroundColor: WidgetStatePropertyAll(Color(0xfffffff2)))',
'dayPeriodBorderSide: BorderSide(color: Color(0xfffffff3))',
'dayPeriodColor: Color(0x00000000)',
'dayPeriodShape: RoundedRectangleBorder(BorderSide(color: Color(0xfffffff5)), BorderRadius.zero)',
'dayPeriodTextColor: Color(0xfffffff6)',
'dayPeriodTextStyle: TextStyle(inherit: true, color: Color(0xfffffff7))',
'dialBackgroundColor: Color(0xfffffff8)',
'dialHandColor: Color(0xfffffff9)',
'dialTextColor: Color(0xfffffffa)',
'dialTextStyle: TextStyle(inherit: true, color: Color(0xfffffffb))',
'elevation: 1.0',
'entryModeIconColor: Color(0xfffffffc)',
'helpTextStyle: TextStyle(inherit: true, color: Color(0xfffffffd))',
'hourMinuteColor: Color(0xfffffffe)',
'hourMinuteShape: RoundedRectangleBorder(BorderSide(color: Color(0xffffffff)), BorderRadius.zero)',
'hourMinuteTextColor: Color(0xfffffff0)',
'hourMinuteTextStyle: TextStyle(inherit: true, color: Color(0xfffffff1))',
'inputDecorationTheme: InputDecorationTheme#ff861(labelStyle: TextStyle(inherit: true, color: Color(0xfffffff2)))',
'padding: EdgeInsets.all(1.0)',
'shape: RoundedRectangleBorder(BorderSide(color: Color(0xfffffff3)), BorderRadius.zero)',
'timeSelectorSeparatorColor: WidgetStatePropertyAll(Color(0xfffffff4))',
'timeSelectorSeparatorTextStyle: WidgetStatePropertyAll(TextStyle(inherit: true, color: Color(0xfffffff5)))'
]));
});
testWidgets('Material2 - Passing no TimePickerThemeData uses defaults', (WidgetTester tester) async {
final ThemeData defaultTheme = ThemeData(useMaterial3: false);
await tester.pumpWidget(_TimePickerLauncher(themeData: defaultTheme));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final Material dialogMaterial = _dialogMaterial(tester);
expect(dialogMaterial.color, defaultTheme.colorScheme.surface);
expect(
dialogMaterial.shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
);
final RenderBox dial = tester.firstRenderObject<RenderBox>(find.byType(CustomPaint));
expect(
dial,
paints
..circle(color: defaultTheme.colorScheme.onSurface.withOpacity(0.08)) // Dial background color.
..circle(color: Color(defaultTheme.colorScheme.primary.value))
);
final RenderParagraph hourText = _textRenderParagraph(tester, '7');
expect(
hourText.text.style,
Typography.material2014().englishLike.displayMedium!
.merge(Typography.material2014().black.displayMedium)
.copyWith(color: defaultTheme.colorScheme.primary)
);
final RenderParagraph minuteText = _textRenderParagraph(tester, '15');
expect(
minuteText.text.style,
Typography.material2014().englishLike.displayMedium!
.merge(Typography.material2014().black.displayMedium)
.copyWith(color: defaultTheme.colorScheme.onSurface),
);
final RenderParagraph amText = _textRenderParagraph(tester, 'AM');
expect(
amText.text.style,
Typography.material2014().englishLike.titleMedium!
.merge(Typography.material2014().black.titleMedium)
.copyWith(color: defaultTheme.colorScheme.primary),
);
final RenderParagraph pmText = _textRenderParagraph(tester, 'PM');
expect(
pmText.text.style,
Typography.material2014().englishLike.titleMedium!
.merge(Typography.material2014().black.titleMedium)
.copyWith(color: defaultTheme.colorScheme.onSurface.withOpacity(0.6)),
);
final RenderParagraph helperText = _textRenderParagraph(tester, 'SELECT TIME');
expect(
helperText.text.style,
Typography.material2014().englishLike.labelSmall!
.merge(Typography.material2014().black.labelSmall),
);
final CustomPaint dialPaint = tester.widget(findDialPaint);
final dynamic dialPainter = dialPaint.painter;
// ignore: avoid_dynamic_calls
final List<dynamic> primaryLabels = dialPainter.primaryLabels as List<dynamic>;
expect(
// ignore: avoid_dynamic_calls
primaryLabels.first.painter.text.style,
Typography.material2014().englishLike.bodyLarge!
.merge(Typography.material2014().black.bodyLarge)
.copyWith(color: defaultTheme.colorScheme.onSurface),
);
// ignore: avoid_dynamic_calls
final List<dynamic> selectedLabels = dialPainter.selectedLabels as List<dynamic>;
expect(
// ignore: avoid_dynamic_calls
selectedLabels.first.painter.text.style,
Typography.material2014().englishLike.bodyLarge!
.merge(Typography.material2014().white.bodyLarge)
.copyWith(color: defaultTheme.colorScheme.onPrimary),
);
final Material hourMaterial = _textMaterial(tester, '7');
expect(hourMaterial.color, defaultTheme.colorScheme.primary.withOpacity(0.12));
expect(
hourMaterial.shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
);
final Material minuteMaterial = _textMaterial(tester, '15');
expect(minuteMaterial.color, defaultTheme.colorScheme.onSurface.withOpacity(0.12));
expect(
minuteMaterial.shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
);
final Material amMaterial = _textMaterial(tester, 'AM');
expect(amMaterial.color, defaultTheme.colorScheme.primary.withOpacity(0.12));
final Material pmMaterial = _textMaterial(tester, 'PM');
expect(pmMaterial.color, Colors.transparent);
final Color expectedBorderColor = Color.alphaBlend(
defaultTheme.colorScheme.onSurface.withOpacity(0.38),
defaultTheme.colorScheme.surface,
);
final Material dayPeriodMaterial = _dayPeriodMaterial(tester);
expect(
dayPeriodMaterial.shape,
RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
side: BorderSide(color: expectedBorderColor),
),
);
final Container dayPeriodDivider = _dayPeriodDivider(tester);
expect(
dayPeriodDivider.decoration,
BoxDecoration(border: Border(left: BorderSide(color: expectedBorderColor))),
);
final IconButton entryModeIconButton = _entryModeIconButton(tester);
expect(
entryModeIconButton.color,
defaultTheme.colorScheme.onSurface.withOpacity(0.6),
);
final ButtonStyle cancelButtonStyle = _actionButtonStyle(tester, 'CANCEL');
expect(cancelButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString()));
final ButtonStyle confirmButtonStyle = _actionButtonStyle(tester, 'OK');
expect(confirmButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString()));
});
testWidgets('Material3 - Passing no TimePickerThemeData uses defaults', (WidgetTester tester) async {
final ThemeData defaultTheme = ThemeData(useMaterial3: true);
await tester.pumpWidget(_TimePickerLauncher(themeData: defaultTheme));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final Material dialogMaterial = _dialogMaterial(tester);
expect(dialogMaterial.color, defaultTheme.colorScheme.surfaceContainerHigh);
expect(
dialogMaterial.shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))),
);
final RenderBox dial = tester.firstRenderObject<RenderBox>(find.byType(CustomPaint));
expect(
dial,
paints
..circle(color: defaultTheme.colorScheme.surfaceContainerHighest) // Dial background color.
..circle(color: Color(defaultTheme.colorScheme.primary.value)), // Dial hand color.
);
final RenderParagraph hourText = _textRenderParagraph(tester, '7');
expect(
hourText.text.style,
Typography.material2021().englishLike.displayLarge!
.merge(Typography.material2021().black.displayLarge)
.copyWith(
color: defaultTheme.colorScheme.onPrimaryContainer,
decorationColor: defaultTheme.colorScheme.onSurface,
),
);
final RenderParagraph minuteText = _textRenderParagraph(tester, '15');
expect(
minuteText.text.style,
Typography.material2021().englishLike.displayLarge!
.merge(Typography.material2021().black.displayLarge)
.copyWith(
color: defaultTheme.colorScheme.onSurface,
decorationColor: defaultTheme.colorScheme.onSurface,
),
);
final RenderParagraph amText = _textRenderParagraph(tester, 'AM');
expect(
amText.text.style,
Typography.material2021().englishLike.titleMedium!
.merge(Typography.material2021().black.titleMedium)
.copyWith(
color: defaultTheme.colorScheme.onTertiaryContainer,
decorationColor: defaultTheme.colorScheme.onSurface,
),
);
final RenderParagraph pmText = _textRenderParagraph(tester, 'PM');
expect(
pmText.text.style,
Typography.material2021().englishLike.titleMedium!
.merge(Typography.material2021().black.titleMedium)
.copyWith(
color: defaultTheme.colorScheme.onSurfaceVariant,
decorationColor: defaultTheme.colorScheme.onSurface,
)
);
final RenderParagraph helperText = _textRenderParagraph(tester, 'Select time');
expect(
helperText.text.style,
Typography.material2021().englishLike.bodyMedium!
.merge(Typography.material2021().black.bodyMedium)
.copyWith(
color: defaultTheme.colorScheme.onSurface,
decorationColor: defaultTheme.colorScheme.onSurface,
),
);
final CustomPaint dialPaint = tester.widget(findDialPaint);
final dynamic dialPainter = dialPaint.painter;
// ignore: avoid_dynamic_calls
final List<dynamic> primaryLabels = dialPainter.primaryLabels as List<dynamic>;
expect(
// ignore: avoid_dynamic_calls
primaryLabels.first.painter.text.style,
Typography.material2021().englishLike.bodyLarge!
.merge(Typography.material2021().black.bodyLarge)
.copyWith(
color: defaultTheme.colorScheme.onSurface,
decorationColor: defaultTheme.colorScheme.onSurface,
),
);
// ignore: avoid_dynamic_calls
final List<dynamic> selectedLabels = dialPainter.selectedLabels as List<dynamic>;
expect(
// ignore: avoid_dynamic_calls
selectedLabels.first.painter.text.style,
Typography.material2021().englishLike.bodyLarge!
.merge(Typography.material2021().black.bodyLarge)
.copyWith(
color: defaultTheme.colorScheme.onPrimary,
decorationColor: defaultTheme.colorScheme.onSurface,
),
);
final Material hourMaterial = _textMaterial(tester, '7');
expect(hourMaterial.color, defaultTheme.colorScheme.primaryContainer);
expect(
hourMaterial.shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0)))
);
final Material minuteMaterial = _textMaterial(tester, '15');
expect(minuteMaterial.color, defaultTheme.colorScheme.surfaceContainerHighest);
expect(
minuteMaterial.shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
);
final Material amMaterial = _textMaterial(tester, 'AM');
expect(amMaterial.color, defaultTheme.colorScheme.tertiaryContainer);
final Material pmMaterial = _textMaterial(tester, 'PM');
expect(pmMaterial.color, Colors.transparent);
final Material dayPeriodMaterial = _dayPeriodMaterial(tester);
expect(
dayPeriodMaterial.shape,
RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: defaultTheme.colorScheme.outline),
),
);
final Container dayPeriodDivider = _dayPeriodDivider(tester);
expect(
dayPeriodDivider.decoration,
BoxDecoration(border: Border(left: BorderSide(color: defaultTheme.colorScheme.outline))),
);
final IconButton entryModeIconButton = _entryModeIconButton(tester);
expect(entryModeIconButton.color, null);
final ButtonStyle cancelButtonStyle = _actionButtonStyle(tester, 'Cancel');
expect(cancelButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString()));
final ButtonStyle confirmButtonStyle = _actionButtonStyle(tester, 'OK');
expect(confirmButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString()));
});
testWidgets('Material2 - Passing no TimePickerThemeData uses defaults - input mode', (WidgetTester tester) async {
final ThemeData defaultTheme = ThemeData(useMaterial3: false);
await tester.pumpWidget(_TimePickerLauncher(themeData: defaultTheme, entryMode: TimePickerEntryMode.input));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final InputDecoration hourDecoration = _textField(tester, '7').decoration!;
expect(hourDecoration.filled, true);
expect(
hourDecoration.fillColor,
MaterialStateColor.resolveWith((Set<MaterialState> states) =>
defaultTheme.colorScheme.onSurface.withOpacity(0.12))
);
expect(
hourDecoration.enabledBorder,
const OutlineInputBorder(borderSide: BorderSide(color: Colors.transparent))
);
expect(
hourDecoration.errorBorder,
OutlineInputBorder(borderSide: BorderSide(color: defaultTheme.colorScheme.error, width: 2))
);
expect(
hourDecoration.focusedBorder,
OutlineInputBorder(borderSide: BorderSide(color: defaultTheme.colorScheme.primary, width: 2))
);
expect(
hourDecoration.focusedErrorBorder,
OutlineInputBorder(borderSide: BorderSide(color: defaultTheme.colorScheme.error, width: 2))
);
expect(
hourDecoration.hintStyle,
Typography.material2014().englishLike.displayMedium!
.merge(defaultTheme.textTheme.displayMedium!.copyWith(color: defaultTheme.colorScheme.onSurface.withOpacity(0.36)))
);
final ButtonStyle cancelButtonStyle = _actionButtonStyle(tester, 'CANCEL');
expect(cancelButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString()));
final ButtonStyle confirmButtonStyle= _actionButtonStyle(tester, 'OK');
expect(confirmButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString()));
});
testWidgets('Material3 - Passing no TimePickerThemeData uses defaults - input mode', (WidgetTester tester) async {
final ThemeData defaultTheme = ThemeData(useMaterial3: true);
await tester.pumpWidget(_TimePickerLauncher(themeData: defaultTheme, entryMode: TimePickerEntryMode.input));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final TextStyle hourTextStyle = _textField(tester, '7').style!;
expect(
hourTextStyle,
Typography.material2021().englishLike.displayMedium!
.merge(Typography.material2021().black.displayMedium)
.copyWith(
color: defaultTheme.colorScheme.onSurface,
decorationColor: defaultTheme.colorScheme.onSurface,
),
);
final TextStyle minuteTextStyle = _textField(tester, '15').style!;
expect(
minuteTextStyle,
Typography.material2021().englishLike.displayMedium!
.merge(Typography.material2021().black.displayMedium)
.copyWith(
color: defaultTheme.colorScheme.onSurface,
decorationColor: defaultTheme.colorScheme.onSurface,
),
);
final InputDecoration hourDecoration = _textField(tester, '7').decoration!;
expect(hourDecoration.filled, true);
expect(hourDecoration.fillColor, defaultTheme.colorScheme.surfaceContainerHighest);
expect(
hourDecoration.enabledBorder,
const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide(color: Colors.transparent)),
);
expect(
hourDecoration.errorBorder,
OutlineInputBorder(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide(color: defaultTheme.colorScheme.error, width: 2.0)),
);
expect(
hourDecoration.focusedBorder,
OutlineInputBorder(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide(color: defaultTheme.colorScheme.primary, width: 2.0)),
);
expect(
hourDecoration.focusedErrorBorder,
OutlineInputBorder(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide(color: defaultTheme.colorScheme.error, width: 2.0)),
);
expect(
hourDecoration.hintStyle,
TextStyle(color: defaultTheme.colorScheme.onSurface.withOpacity(0.36))
);
final ButtonStyle cancelButtonStyle = _actionButtonStyle(tester, 'Cancel');
expect(cancelButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString()));
final ButtonStyle confirmButtonStyle = _actionButtonStyle(tester, 'OK');
expect(confirmButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString()));
});
testWidgets('Material2 - Time picker uses values from TimePickerThemeData', (WidgetTester tester) async {
final TimePickerThemeData timePickerTheme = _timePickerTheme();
final ThemeData theme = ThemeData(timePickerTheme: timePickerTheme, useMaterial3: false);
await tester.pumpWidget(_TimePickerLauncher(themeData: theme));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final Material dialogMaterial = _dialogMaterial(tester);
expect(dialogMaterial.color, timePickerTheme.backgroundColor);
expect(dialogMaterial.shape, timePickerTheme.shape);
final RenderBox dial = tester.firstRenderObject<RenderBox>(find.byType(CustomPaint));
expect(
dial,
paints
..circle(color: Color(timePickerTheme.dialBackgroundColor!.value)) // Dial background color.
..circle(color: Color(timePickerTheme.dialHandColor!.value)), // Dial hand color.
);
final RenderParagraph hourText = _textRenderParagraph(tester, '7');
expect(
hourText.text.style,
Typography.material2014().englishLike.bodyMedium!
.merge(Typography.material2014().black.bodyMedium)
.merge(timePickerTheme.hourMinuteTextStyle)
.copyWith(color: _selectedColor),
);
final RenderParagraph minuteText = _textRenderParagraph(tester, '15');
expect(
minuteText.text.style,
Typography.material2014().englishLike.bodyMedium!
.merge(Typography.material2014().black.bodyMedium)
.merge(timePickerTheme.hourMinuteTextStyle)
.copyWith(color: _unselectedColor),
);
final RenderParagraph amText = _textRenderParagraph(tester, 'AM');
expect(
amText.text.style,
Typography.material2014().englishLike.titleMedium!
.merge(Typography.material2014().black.titleMedium)
.merge(timePickerTheme.dayPeriodTextStyle)
.copyWith(color: _selectedColor),
);
final RenderParagraph pmText = _textRenderParagraph(tester, 'PM');
expect(
pmText.text.style,
Typography.material2014().englishLike.titleMedium!
.merge(Typography.material2014().black.titleMedium)
.merge(timePickerTheme.dayPeriodTextStyle)
.copyWith(color: _unselectedColor),
);
final RenderParagraph helperText = _textRenderParagraph(tester, 'SELECT TIME');
expect(
helperText.text.style,
Typography.material2014().englishLike.bodyMedium!
.merge(Typography.material2014().black.bodyMedium)
.merge(timePickerTheme.helpTextStyle),
);
final CustomPaint dialPaint = tester.widget(findDialPaint);
final dynamic dialPainter = dialPaint.painter;
// ignore: avoid_dynamic_calls
final List<dynamic> primaryLabels = dialPainter.primaryLabels as List<dynamic>;
expect(
// ignore: avoid_dynamic_calls
primaryLabels.first.painter.text.style,
Typography.material2014().englishLike.bodyLarge!
.merge(Typography.material2014().black.bodyLarge)
.copyWith(color: _unselectedColor),
);
// ignore: avoid_dynamic_calls
final List<dynamic> selectedLabels = dialPainter.selectedLabels as List<dynamic>;
expect(
// ignore: avoid_dynamic_calls
selectedLabels.first.painter.text.style,
Typography.material2014().englishLike.bodyLarge!
.merge(Typography.material2014().white.bodyLarge)
.copyWith(color: _selectedColor),
);
final Material hourMaterial = _textMaterial(tester, '7');
expect(hourMaterial.color, _selectedColor);
expect(hourMaterial.shape, timePickerTheme.hourMinuteShape);
final Material minuteMaterial = _textMaterial(tester, '15');
expect(minuteMaterial.color, _unselectedColor);
expect(minuteMaterial.shape, timePickerTheme.hourMinuteShape);
final Material amMaterial = _textMaterial(tester, 'AM');
expect(amMaterial.color, _selectedColor);
final Material pmMaterial = _textMaterial(tester, 'PM');
expect(pmMaterial.color, _unselectedColor);
final Material dayPeriodMaterial = _dayPeriodMaterial(tester);
expect(
dayPeriodMaterial.shape,
timePickerTheme.dayPeriodShape!.copyWith(side: timePickerTheme.dayPeriodBorderSide),
);
final Container dayPeriodDivider = _dayPeriodDivider(tester);
expect(
dayPeriodDivider.decoration,
BoxDecoration(border: Border(left: timePickerTheme.dayPeriodBorderSide!)),
);
final IconButton entryModeIconButton = _entryModeIconButton(tester);
expect(
entryModeIconButton.color,
timePickerTheme.entryModeIconColor,
);
final ButtonStyle cancelButtonStyle = _actionButtonStyle(tester, 'CANCEL');
expect(cancelButtonStyle.toString(), equalsIgnoringHashCodes(timePickerTheme.cancelButtonStyle.toString()));
final ButtonStyle confirmButtonStyle = _actionButtonStyle(tester, 'OK');
expect(confirmButtonStyle.toString(), equalsIgnoringHashCodes(timePickerTheme.confirmButtonStyle.toString()));
});
testWidgets('Material3 - Time picker uses values from TimePickerThemeData', (WidgetTester tester) async {
final TimePickerThemeData timePickerTheme = _timePickerTheme();
final ThemeData theme = ThemeData(timePickerTheme: timePickerTheme, useMaterial3: true);
await tester.pumpWidget(_TimePickerLauncher(themeData: theme));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final Material dialogMaterial = _dialogMaterial(tester);
expect(dialogMaterial.color, timePickerTheme.backgroundColor);
expect(dialogMaterial.shape, timePickerTheme.shape);
final RenderBox dial = tester.firstRenderObject<RenderBox>(find.byType(CustomPaint));
expect(
dial,
paints
..circle(color: Color(timePickerTheme.dialBackgroundColor!.value)) // Dial background color.
..circle(color: Color(timePickerTheme.dialHandColor!.value)), // Dial hand color.
);
final RenderParagraph hourText = _textRenderParagraph(tester, '7');
expect(
hourText.text.style,
Typography.material2021().englishLike.bodyMedium!
.merge(Typography.material2021().black.bodyMedium)
.merge(timePickerTheme.hourMinuteTextStyle)
.copyWith(color: _selectedColor, decorationColor: const Color(0xff1d1b20)),
);
final RenderParagraph minuteText = _textRenderParagraph(tester, '15');
expect(
minuteText.text.style,
Typography.material2021().englishLike.bodyMedium!
.merge(Typography.material2021().black.bodyMedium)
.merge(timePickerTheme.hourMinuteTextStyle)
.copyWith(color: _unselectedColor, decorationColor: const Color(0xff1d1b20)),
);
final RenderParagraph amText = _textRenderParagraph(tester, 'AM');
expect(
amText.text.style,
Typography.material2021().englishLike.bodyMedium!
.merge(Typography.material2021().black.bodyMedium)
.merge(timePickerTheme.hourMinuteTextStyle)
.copyWith(color: _selectedColor, decorationColor: const Color(0xff1d1b20)),
);
final RenderParagraph pmText = _textRenderParagraph(tester, 'PM');
expect(
pmText.text.style,
Typography.material2021().englishLike.bodyMedium!
.merge(Typography.material2021().black.bodyMedium)
.merge(timePickerTheme.hourMinuteTextStyle)
.copyWith(color: _unselectedColor, decorationColor: const Color(0xff1d1b20)),
);
final RenderParagraph helperText = _textRenderParagraph(tester, 'Select time');
expect(
helperText.text.style,
Typography.material2021().englishLike.bodyMedium!
.merge(Typography.material2021().black.bodyMedium)
.merge(timePickerTheme.helpTextStyle).copyWith(
color: theme.colorScheme.onSurface,
decorationColor: theme.colorScheme.onSurface
),
);
final CustomPaint dialPaint = tester.widget(findDialPaint);
final dynamic dialPainter = dialPaint.painter;
// ignore: avoid_dynamic_calls
final List<dynamic> primaryLabels = dialPainter.primaryLabels as List<dynamic>;
expect(
// ignore: avoid_dynamic_calls
primaryLabels.first.painter.text.style,
Typography.material2021().englishLike.bodyLarge!
.merge(Typography.material2021().black.bodyLarge)
.copyWith(color: _unselectedColor, decorationColor: theme.colorScheme.onSurface),
);
// ignore: avoid_dynamic_calls
final List<dynamic> selectedLabels = dialPainter.selectedLabels as List<dynamic>;
expect(
// ignore: avoid_dynamic_calls
selectedLabels.first.painter.text.style,
Typography.material2021().englishLike.bodyLarge!
.merge(Typography.material2021().black.bodyLarge)
.copyWith(color: _selectedColor, decorationColor: theme.colorScheme.onSurface),
);
final Material hourMaterial = _textMaterial(tester, '7');
expect(hourMaterial.color, _selectedColor);
expect(hourMaterial.shape, timePickerTheme.hourMinuteShape);
final Material minuteMaterial = _textMaterial(tester, '15');
expect(minuteMaterial.color, _unselectedColor);
expect(minuteMaterial.shape, timePickerTheme.hourMinuteShape);
final Material amMaterial = _textMaterial(tester, 'AM');
expect(amMaterial.color, _selectedColor);
final Material pmMaterial = _textMaterial(tester, 'PM');
expect(pmMaterial.color, _unselectedColor);
final Material dayPeriodMaterial = _dayPeriodMaterial(tester);
expect(
dayPeriodMaterial.shape,
timePickerTheme.dayPeriodShape!.copyWith(side: timePickerTheme.dayPeriodBorderSide),
);
final Container dayPeriodDivider = _dayPeriodDivider(tester);
expect(
dayPeriodDivider.decoration,
BoxDecoration(border: Border(left: timePickerTheme.dayPeriodBorderSide!)),
);
final IconButton entryModeIconButton = _entryModeIconButton(tester);
expect(entryModeIconButton.color, null);
final ButtonStyle cancelButtonStyle = _actionButtonStyle(tester, 'Cancel');
expect(cancelButtonStyle.toString(), equalsIgnoringHashCodes(timePickerTheme.cancelButtonStyle.toString()));
final ButtonStyle confirmButtonStyle = _actionButtonStyle(tester, 'OK');
expect(confirmButtonStyle.toString(), equalsIgnoringHashCodes(timePickerTheme.confirmButtonStyle.toString()));
});
testWidgets('Time picker uses values from TimePickerThemeData with InputDecorationTheme - input mode', (WidgetTester tester) async {
final TimePickerThemeData timePickerTheme = _timePickerTheme(includeInputDecoration: true);
final ThemeData theme = ThemeData(timePickerTheme: timePickerTheme);
await tester.pumpWidget(_TimePickerLauncher(themeData: theme, entryMode: TimePickerEntryMode.input));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final InputDecoration hourDecoration = _textField(tester, '7').decoration!;
expect(hourDecoration.filled, timePickerTheme.inputDecorationTheme!.filled);
expect(hourDecoration.fillColor, timePickerTheme.inputDecorationTheme!.fillColor);
expect(hourDecoration.enabledBorder, timePickerTheme.inputDecorationTheme!.enabledBorder);
expect(hourDecoration.errorBorder, timePickerTheme.inputDecorationTheme!.errorBorder);
expect(hourDecoration.focusedBorder, timePickerTheme.inputDecorationTheme!.focusedBorder);
expect(hourDecoration.focusedErrorBorder, timePickerTheme.inputDecorationTheme!.focusedErrorBorder);
expect(hourDecoration.hintStyle, timePickerTheme.inputDecorationTheme!.hintStyle);
});
testWidgets('Time picker uses values from TimePickerThemeData without InputDecorationTheme - input mode', (WidgetTester tester) async {
final TimePickerThemeData timePickerTheme = _timePickerTheme();
final ThemeData theme = ThemeData(timePickerTheme: timePickerTheme);
await tester.pumpWidget(_TimePickerLauncher(themeData: theme, entryMode: TimePickerEntryMode.input));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final InputDecoration hourDecoration = _textField(tester, '7').decoration!;
expect(hourDecoration.fillColor?.value, timePickerTheme.hourMinuteColor?.value);
});
testWidgets('Time picker dayPeriodColor does the right thing with non-MaterialStateColor', (WidgetTester tester) async {
final TimePickerThemeData timePickerTheme = _timePickerTheme().copyWith(dayPeriodColor: Colors.red);
final ThemeData theme = ThemeData(timePickerTheme: timePickerTheme);
await tester.pumpWidget(_TimePickerLauncher(themeData: theme, entryMode: TimePickerEntryMode.input));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final Material amMaterial = _textMaterial(tester, 'AM');
expect(amMaterial.color, Colors.red);
final Material pmMaterial = _textMaterial(tester, 'PM');
expect(pmMaterial.color, Colors.transparent);
});
testWidgets('Time picker dayPeriodColor does the right thing with MaterialStateColor', (WidgetTester tester) async {
final MaterialStateColor testColor = MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return Colors.green;
}
return Colors.blue;
});
final TimePickerThemeData timePickerTheme = _timePickerTheme().copyWith(dayPeriodColor: testColor);
final ThemeData theme = ThemeData(timePickerTheme: timePickerTheme);
await tester.pumpWidget(_TimePickerLauncher(themeData: theme, entryMode: TimePickerEntryMode.input));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final Material amMaterial = _textMaterial(tester, 'AM');
expect(amMaterial.color, Colors.green);
final Material pmMaterial = _textMaterial(tester, 'PM');
expect(pmMaterial.color, Colors.blue);
});
testWidgets('Time selector separator color uses the timeSelectorSeparatorColor value', (WidgetTester tester) async {
final TimePickerThemeData timePickerTheme = _timePickerTheme().copyWith(
timeSelectorSeparatorColor: const MaterialStatePropertyAll<Color>(Color(0xff00ff00))
);
final ThemeData theme = ThemeData(timePickerTheme: timePickerTheme);
await tester.pumpWidget(_TimePickerLauncher(themeData: theme, entryMode: TimePickerEntryMode.input));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final RenderParagraph paragraph = tester.renderObject(find.text(':'));
expect(paragraph.text.style!.color, const Color(0xff00ff00));
});
testWidgets('Time selector separator text style uses the timeSelectorSeparatorTextStyle value', (WidgetTester tester) async {
final TimePickerThemeData timePickerTheme = _timePickerTheme().copyWith(
timeSelectorSeparatorTextStyle: const MaterialStatePropertyAll<TextStyle>(
TextStyle(
fontSize: 35.0,
fontStyle: FontStyle.italic,
),
),
);
final ThemeData theme = ThemeData(timePickerTheme: timePickerTheme);
await tester.pumpWidget(_TimePickerLauncher(themeData: theme, entryMode: TimePickerEntryMode.input));
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
final RenderParagraph paragraph = tester.renderObject(find.text(':'));
expect(paragraph.text.style!.fontSize, 35.0);
expect(paragraph.text.style!.fontStyle, FontStyle.italic);
});
}
final Color _selectedColor = Colors.green[100]!;
final Color _unselectedColor = Colors.green[200]!;
TimePickerThemeData _timePickerTheme({bool includeInputDecoration = false}) {
Color getColor(Set<MaterialState> states) {
return states.contains(MaterialState.selected) ? _selectedColor : _unselectedColor;
}
final MaterialStateColor materialStateColor = MaterialStateColor.resolveWith(getColor);
return TimePickerThemeData(
backgroundColor: Colors.orange,
cancelButtonStyle: TextButton.styleFrom(foregroundColor: Colors.red),
confirmButtonStyle: TextButton.styleFrom(foregroundColor: Colors.green),
hourMinuteTextColor: materialStateColor,
hourMinuteColor: materialStateColor,
dayPeriodTextColor: materialStateColor,
dayPeriodColor: materialStateColor,
dialHandColor: Colors.brown,
dialBackgroundColor: Colors.pinkAccent,
dialTextColor: materialStateColor,
entryModeIconColor: Colors.red,
hourMinuteTextStyle: const TextStyle(fontSize: 8.0),
dayPeriodTextStyle: const TextStyle(fontSize: 8.0),
helpTextStyle: const TextStyle(fontSize: 8.0),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))),
hourMinuteShape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))),
dayPeriodShape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))),
dayPeriodBorderSide: const BorderSide(color: Colors.blueAccent),
inputDecorationTheme: includeInputDecoration ? const InputDecorationTheme(
filled: true,
fillColor: Colors.purple,
enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.blue)),
errorBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.green)),
focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.yellow)),
focusedErrorBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
hintStyle: TextStyle(fontSize: 8),
) : null,
);
}
class _TimePickerLauncher extends StatelessWidget {
const _TimePickerLauncher({
this.themeData,
this.entryMode = TimePickerEntryMode.dial,
});
final ThemeData? themeData;
final TimePickerEntryMode entryMode;
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: themeData,
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () async {
await showTimePicker(
context: context,
initialEntryMode: entryMode,
initialTime: const TimeOfDay(hour: 7, minute: 15),
);
},
);
},
),
),
),
);
}
}
Material _dialogMaterial(WidgetTester tester) {
return tester.widget<Material>(find.descendant(of: find.byType(Dialog), matching: find.byType(Material)).first);
}
Material _textMaterial(WidgetTester tester, String text) {
return tester.widget<Material>(find.ancestor(of: find.text(text), matching: find.byType(Material)).first);
}
TextField _textField(WidgetTester tester, String text) {
return tester.widget<TextField>(find.ancestor(of: find.text(text), matching: find.byType(TextField)).first);
}
Material _dayPeriodMaterial(WidgetTester tester) {
return tester.widget<Material>(find.descendant(of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DayPeriodControl'), matching: find.byType(Material)).first);
}
Container _dayPeriodDivider(WidgetTester tester) {
return tester.widget<Container>(find.descendant(of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DayPeriodControl'), matching: find.byType(Container)).at(0));
}
IconButton _entryModeIconButton(WidgetTester tester) {
return tester.widget<IconButton>(find.descendant(of: find.byType(Dialog), matching: find.byType(IconButton)).first);
}
RenderParagraph _textRenderParagraph(WidgetTester tester, String text) {
return tester.element<StatelessElement>(find.text(text).first).renderObject! as RenderParagraph;
}
final Finder findDialPaint = find.descendant(
of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_Dial'),
matching: find.byWidgetPredicate((Widget w) => w is CustomPaint),
);
ButtonStyle _actionButtonStyle(WidgetTester tester, String text) {
return tester.widget<TextButton>(find.widgetWithText(TextButton, text)).style!;
}
| flutter/packages/flutter/test/material/time_picker_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/time_picker_theme_test.dart",
"repo_id": "flutter",
"token_count": 15139
} | 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:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> main() async {
final ui.Image image = await createTestImage();
testWidgets('didHaveMemoryPressure clears imageCache', (WidgetTester tester) async {
imageCache.putIfAbsent(1, () => OneFrameImageStreamCompleter(
Future<ImageInfo>.value(ImageInfo(
image: image,
)),
));
await tester.idle();
expect(imageCache.currentSize, 1);
final ByteData message = const JSONMessageCodec().encodeMessage(<String, dynamic>{'type': 'memoryPressure'})!;
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/system', message, (_) { });
expect(imageCache.currentSize, 0);
});
test('evict clears live references', () async {
final TestPaintingBinding binding = TestPaintingBinding();
expect(binding.imageCache.clearCount, 0);
expect(binding.imageCache.liveClearCount, 0);
binding.evict('/path/to/asset.png');
expect(binding.imageCache.clearCount, 1);
expect(binding.imageCache.liveClearCount, 1);
});
test('ShaderWarmUp is null by default', () {
expect(PaintingBinding.shaderWarmUp, null);
});
}
class TestBindingBase implements BindingBase {
@override
void initInstances() {}
@override
bool debugCheckZone(String entryPoint) { return true; }
@override
void initServiceExtensions() {}
@override
Future<void> lockEvents(Future<void> Function() callback) async {}
@override
bool get locked => throw UnimplementedError();
@override
Future<void> performReassemble() {
throw UnimplementedError();
}
@override
void postEvent(String eventKind, Map<String, dynamic> eventData) {}
@override
Future<void> reassembleApplication() {
throw UnimplementedError();
}
@override
void registerBoolServiceExtension({required String name, required AsyncValueGetter<bool> getter, required AsyncValueSetter<bool> setter}) {}
@override
void registerNumericServiceExtension({required String name, required AsyncValueGetter<double> getter, required AsyncValueSetter<double> setter}) {}
@override
void registerServiceExtension({required String name, required ServiceExtensionCallback callback}) {}
@override
void registerSignalServiceExtension({required String name, required AsyncCallback callback}) {}
@override
void registerStringServiceExtension({required String name, required AsyncValueGetter<String> getter, required AsyncValueSetter<String> setter}) {}
@override
void unlocked() {}
@override
ui.SingletonFlutterWindow get window => throw UnimplementedError();
@override
ui.PlatformDispatcher get platformDispatcher => throw UnimplementedError();
}
class TestPaintingBinding extends TestBindingBase with SchedulerBinding, ServicesBinding, PaintingBinding {
@override
final FakeImageCache imageCache = FakeImageCache();
@override
ImageCache createImageCache() => imageCache;
}
class FakeImageCache extends ImageCache {
int clearCount = 0;
int liveClearCount = 0;
@override
void clear() {
clearCount += 1;
super.clear();
}
@override
void clearLiveImages() {
liveClearCount += 1;
super.clearLiveImages();
}
}
| flutter/packages/flutter/test/painting/binding_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/binding_test.dart",
"repo_id": "flutter",
"token_count": 1119
} | 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 'dart:ui' as ui show Codec;
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
/// An image provider implementation for testing that is using a [ui.Codec]
/// that it was given at construction time (typically the job of real image
/// providers is to resolve some data and instantiate a [ui.Codec] from it).
class FakeImageProvider extends ImageProvider<FakeImageProvider> {
const FakeImageProvider(this._codec, { this.scale = 1.0 });
final ui.Codec _codec;
/// The scale to place in the [ImageInfo] object of the image.
final double scale;
@override
Future<FakeImageProvider> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<FakeImageProvider>(this);
}
@override
ImageStreamCompleter loadImage(FakeImageProvider key, ImageDecoderCallback decode) {
assert(key == this);
return MultiFrameImageStreamCompleter(
codec: SynchronousFuture<ui.Codec>(_codec),
scale: scale,
);
}
}
| flutter/packages/flutter/test/painting/fake_image_provider.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/fake_image_provider.dart",
"repo_id": "flutter",
"token_count": 343
} | 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 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/scheduler.dart' show SchedulerBinding, timeDilation;
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import '../image_data.dart';
import 'fake_codec.dart';
import 'mocks_for_image_cache.dart';
class FakeFrameInfo implements FrameInfo {
const FakeFrameInfo(this._duration, this._image);
final Duration _duration;
final Image _image;
@override
Duration get duration => _duration;
@override
Image get image => _image;
FakeFrameInfo clone() {
return FakeFrameInfo(
_duration,
_image.clone(),
);
}
}
class MockCodec implements Codec {
@override
late int frameCount;
@override
late int repetitionCount;
int numFramesAsked = 0;
Completer<FrameInfo> _nextFrameCompleter = Completer<FrameInfo>();
@override
Future<FrameInfo> getNextFrame() {
numFramesAsked += 1;
return _nextFrameCompleter.future;
}
void completeNextFrame(FrameInfo frameInfo) {
_nextFrameCompleter.complete(frameInfo);
_nextFrameCompleter = Completer<FrameInfo>();
}
void failNextFrame(String err) {
_nextFrameCompleter.completeError(err);
}
@override
void dispose() { }
}
class FakeEventReportingImageStreamCompleter extends ImageStreamCompleter {
FakeEventReportingImageStreamCompleter({Stream<ImageChunkEvent>? chunkEvents}) {
if (chunkEvents != null) {
chunkEvents.listen((ImageChunkEvent event) {
reportImageChunkEvent(event);
},
);
}
}
}
void main() {
// TODO(polina-c): make sure images are disposed, https://github.com/flutter/flutter/issues/141388 [leaks-to-clean]
LeakTesting.settings = LeakTesting.settings.withIgnoredAll();
late Image image20x10;
late Image image200x100;
setUp(() async {
image20x10 = await createTestImage(width: 20, height: 10);
image200x100 = await createTestImage(width: 200, height: 100);
});
testWidgets('Codec future fails', (WidgetTester tester) async {
final Completer<Codec> completer = Completer<Codec>();
MultiFrameImageStreamCompleter(
codec: completer.future,
scale: 1.0,
);
completer.completeError('failure message');
await tester.idle();
expect(tester.takeException(), 'failure message');
});
testWidgets('Decoding starts when a listener is added after codec is ready', (WidgetTester tester) async {
final Completer<Codec> completer = Completer<Codec>();
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 1;
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: completer.future,
scale: 1.0,
);
completer.complete(mockCodec);
await tester.idle();
expect(mockCodec.numFramesAsked, 0);
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
await tester.idle();
expect(mockCodec.numFramesAsked, 1);
});
testWidgets('Decoding starts when a codec is ready after a listener is added', (WidgetTester tester) async {
final Completer<Codec> completer = Completer<Codec>();
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 1;
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: completer.future,
scale: 1.0,
);
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
await tester.idle();
expect(mockCodec.numFramesAsked, 0);
completer.complete(mockCodec);
await tester.idle();
expect(mockCodec.numFramesAsked, 1);
});
testWidgets('Decoding does not crash when disposed', (WidgetTester tester) async {
final Completer<Codec> completer = Completer<Codec>();
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 1;
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: completer.future,
scale: 1.0,
);
completer.complete(mockCodec);
await tester.idle();
expect(mockCodec.numFramesAsked, 0);
void listener(ImageInfo image, bool synchronousCall) { }
final ImageStreamListener streamListener = ImageStreamListener(listener);
imageStream.addListener(streamListener);
await tester.idle();
expect(mockCodec.numFramesAsked, 1);
final FrameInfo frame = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
mockCodec.completeNextFrame(frame);
imageStream.removeListener(streamListener);
await tester.idle();
});
testWidgets('Chunk events of base ImageStreamCompleter are delivered', (WidgetTester tester) async {
final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[];
final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>();
final ImageStreamCompleter imageStream = FakeEventReportingImageStreamCompleter(
chunkEvents: streamController.stream,
);
imageStream.addListener(ImageStreamListener(
(ImageInfo image, bool synchronousCall) { },
onChunk: (ImageChunkEvent event) {
chunkEvents.add(event);
},
));
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3));
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3));
await tester.idle();
expect(chunkEvents.length, 2);
expect(chunkEvents[0].cumulativeBytesLoaded, 1);
expect(chunkEvents[0].expectedTotalBytes, 3);
expect(chunkEvents[1].cumulativeBytesLoaded, 2);
expect(chunkEvents[1].expectedTotalBytes, 3);
});
testWidgets('Chunk events of base ImageStreamCompleter are not buffered before listener registration', (WidgetTester tester) async {
final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[];
final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>();
final ImageStreamCompleter imageStream = FakeEventReportingImageStreamCompleter(
chunkEvents: streamController.stream,
);
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3));
await tester.idle();
imageStream.addListener(ImageStreamListener(
(ImageInfo image, bool synchronousCall) { },
onChunk: (ImageChunkEvent event) {
chunkEvents.add(event);
},
));
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3));
await tester.idle();
expect(chunkEvents.length, 1);
expect(chunkEvents[0].cumulativeBytesLoaded, 2);
expect(chunkEvents[0].expectedTotalBytes, 3);
});
testWidgets('Chunk events of MultiFrameImageStreamCompleter are delivered', (WidgetTester tester) async {
final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[];
final Completer<Codec> completer = Completer<Codec>();
final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: completer.future,
chunkEvents: streamController.stream,
scale: 1.0,
);
imageStream.addListener(ImageStreamListener(
(ImageInfo image, bool synchronousCall) { },
onChunk: (ImageChunkEvent event) {
chunkEvents.add(event);
},
));
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3));
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3));
await tester.idle();
expect(chunkEvents.length, 2);
expect(chunkEvents[0].cumulativeBytesLoaded, 1);
expect(chunkEvents[0].expectedTotalBytes, 3);
expect(chunkEvents[1].cumulativeBytesLoaded, 2);
expect(chunkEvents[1].expectedTotalBytes, 3);
});
testWidgets('Chunk events of MultiFrameImageStreamCompleter are not buffered before listener registration', (WidgetTester tester) async {
final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[];
final Completer<Codec> completer = Completer<Codec>();
final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: completer.future,
chunkEvents: streamController.stream,
scale: 1.0,
);
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3));
await tester.idle();
imageStream.addListener(ImageStreamListener(
(ImageInfo image, bool synchronousCall) { },
onChunk: (ImageChunkEvent event) {
chunkEvents.add(event);
},
));
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3));
await tester.idle();
expect(chunkEvents.length, 1);
expect(chunkEvents[0].cumulativeBytesLoaded, 2);
expect(chunkEvents[0].expectedTotalBytes, 3);
});
testWidgets('Chunk errors are reported', (WidgetTester tester) async {
final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[];
final Completer<Codec> completer = Completer<Codec>();
final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: completer.future,
chunkEvents: streamController.stream,
scale: 1.0,
);
imageStream.addListener(ImageStreamListener(
(ImageInfo image, bool synchronousCall) { },
onChunk: (ImageChunkEvent event) {
chunkEvents.add(event);
},
));
streamController.addError(Error());
streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3));
await tester.idle();
expect(tester.takeException(), isNotNull);
expect(chunkEvents.length, 1);
expect(chunkEvents[0].cumulativeBytesLoaded, 2);
expect(chunkEvents[0].expectedTotalBytes, 3);
});
testWidgets('getNextFrame future fails', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
codecCompleter.complete(mockCodec);
// MultiFrameImageStreamCompleter only sets an error handler for the next
// frame future after the codec future has completed.
// Idling here lets the MultiFrameImageStreamCompleter advance and set the
// error handler for the nextFrame future.
await tester.idle();
mockCodec.failNextFrame('frame completion error');
await tester.idle();
expect(tester.takeException(), 'frame completion error');
});
testWidgets('ImageStream emits frame (static image)', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
final List<ImageInfo> emittedImages = <ImageInfo>[];
imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) {
emittedImages.add(image);
}));
codecCompleter.complete(mockCodec);
await tester.idle();
final FrameInfo frame = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
mockCodec.completeNextFrame(frame);
await tester.idle();
expect(emittedImages.every((ImageInfo info) => info.image.isCloneOf(frame.image)), true);
});
testWidgets('ImageStream emits frames (animated images)', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 2;
mockCodec.repetitionCount = -1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
final List<ImageInfo> emittedImages = <ImageInfo>[];
imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) {
emittedImages.add(image);
}));
codecCompleter.complete(mockCodec);
await tester.idle();
final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
mockCodec.completeNextFrame(frame1);
await tester.idle();
// We are waiting for the next animation tick, so at this point no frames
// should have been emitted.
expect(emittedImages.length, 0);
await tester.pump();
expect(emittedImages.single.image.isCloneOf(frame1.image), true);
final FrameInfo frame2 = FakeFrameInfo(const Duration(milliseconds: 400), image200x100);
mockCodec.completeNextFrame(frame2);
await tester.pump(const Duration(milliseconds: 100));
// The duration for the current frame was 200ms, so we don't emit the next
// frame yet even though it is ready.
expect(emittedImages.length, 1);
await tester.pump(const Duration(milliseconds: 100));
expect(emittedImages[0].image.isCloneOf(frame1.image), true);
expect(emittedImages[1].image.isCloneOf(frame2.image), true);
// Let the pending timer for the next frame to complete so we can cleanly
// quit the test without pending timers.
await tester.pump(const Duration(milliseconds: 400));
});
testWidgets('animation wraps back', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 2;
mockCodec.repetitionCount = -1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
final List<ImageInfo> emittedImages = <ImageInfo>[];
imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) {
emittedImages.add(image);
}));
codecCompleter.complete(mockCodec);
await tester.idle();
final FakeFrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
final FakeFrameInfo frame2 = FakeFrameInfo(const Duration(milliseconds: 400), image200x100);
mockCodec.completeNextFrame(frame1.clone());
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // first animation frame shows on first app frame.
mockCodec.completeNextFrame(frame2.clone());
await tester.idle(); // let nextFrameFuture complete
await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame.
mockCodec.completeNextFrame(frame1.clone());
await tester.idle(); // let nextFrameFuture complete
await tester.pump(const Duration(milliseconds: 400)); // emit 3rd frame
expect(emittedImages[0].image.isCloneOf(frame1.image), true);
expect(emittedImages[1].image.isCloneOf(frame2.image), true);
expect(emittedImages[2].image.isCloneOf(frame1.image), true);
// Let the pending timer for the next frame to complete so we can cleanly
// quit the test without pending timers.
await tester.pump(const Duration(milliseconds: 200));
});
testWidgets("animation doesn't repeat more than specified", (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 2;
mockCodec.repetitionCount = 0;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
final List<ImageInfo> emittedImages = <ImageInfo>[];
imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) {
emittedImages.add(image);
}));
codecCompleter.complete(mockCodec);
await tester.idle();
final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
final FrameInfo frame2 = FakeFrameInfo(const Duration(milliseconds: 400), image200x100);
mockCodec.completeNextFrame(frame1);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // first animation frame shows on first app frame.
mockCodec.completeNextFrame(frame2);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame.
mockCodec.completeNextFrame(frame1);
// allow another frame to complete (but we shouldn't be asking for it as
// this animation should not repeat.
await tester.idle();
await tester.pump(const Duration(milliseconds: 400));
expect(emittedImages[0].image.isCloneOf(frame1.image), true);
expect(emittedImages[1].image.isCloneOf(frame2.image), true);
});
testWidgets('frames are only decoded when there are listeners', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 2;
mockCodec.repetitionCount = -1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
final ImageStreamCompleterHandle handle = imageStream.keepAlive();
codecCompleter.complete(mockCodec);
await tester.idle();
final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
final FrameInfo frame2 = FakeFrameInfo(const Duration(milliseconds: 400), image200x100);
mockCodec.completeNextFrame(frame1);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // first animation frame shows on first app frame.
mockCodec.completeNextFrame(frame2);
imageStream.removeListener(ImageStreamListener(listener));
await tester.idle(); // let nextFrameFuture complete
await tester.pump(const Duration(milliseconds: 400)); // emit 2nd frame.
// Decoding of the 3rd frame should not start as there are no registered
// listeners to the stream
expect(mockCodec.numFramesAsked, 2);
imageStream.addListener(ImageStreamListener(listener));
await tester.idle(); // let nextFrameFuture complete
expect(mockCodec.numFramesAsked, 3);
handle.dispose();
});
testWidgets('multiple stream listeners', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 2;
mockCodec.repetitionCount = -1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
final List<ImageInfo> emittedImages1 = <ImageInfo>[];
void listener1(ImageInfo image, bool synchronousCall) {
emittedImages1.add(image);
}
final List<ImageInfo> emittedImages2 = <ImageInfo>[];
void listener2(ImageInfo image, bool synchronousCall) {
emittedImages2.add(image);
}
imageStream.addListener(ImageStreamListener(listener1));
imageStream.addListener(ImageStreamListener(listener2));
codecCompleter.complete(mockCodec);
await tester.idle();
final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
final FrameInfo frame2 = FakeFrameInfo(const Duration(milliseconds: 400), image200x100);
mockCodec.completeNextFrame(frame1);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // first animation frame shows on first app frame.
expect(emittedImages1.single.image.isCloneOf(frame1.image), true);
expect(emittedImages2.single.image.isCloneOf(frame1.image), true);
mockCodec.completeNextFrame(frame2);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // next app frame will schedule a timer.
imageStream.removeListener(ImageStreamListener(listener1));
await tester.pump(const Duration(milliseconds: 400)); // emit 2nd frame.
expect(emittedImages1.single.image.isCloneOf(frame1.image), true);
expect(emittedImages2[0].image.isCloneOf(frame1.image), true);
expect(emittedImages2[1].image.isCloneOf(frame2.image), true);
});
testWidgets('timer is canceled when listeners are removed', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 2;
mockCodec.repetitionCount = -1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
codecCompleter.complete(mockCodec);
await tester.idle();
final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
final FrameInfo frame2 = FakeFrameInfo(const Duration(milliseconds: 400), image200x100);
mockCodec.completeNextFrame(frame1);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // first animation frame shows on first app frame.
mockCodec.completeNextFrame(frame2);
await tester.idle(); // let nextFrameFuture complete
await tester.pump();
imageStream.removeListener(ImageStreamListener(listener));
// The test framework will fail this if there are pending timers at this
// point.
});
testWidgets('timeDilation affects animation frame timers', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 2;
mockCodec.repetitionCount = -1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
codecCompleter.complete(mockCodec);
await tester.idle();
final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
final FrameInfo frame2 = FakeFrameInfo(const Duration(milliseconds: 400), image200x100);
mockCodec.completeNextFrame(frame1);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // first animation frame shows on first app frame.
timeDilation = 2.0;
mockCodec.completeNextFrame(frame2);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // schedule next app frame
await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame.
// Decoding of the 3rd frame should not start after 200 ms, as time is
// dilated by a factor of 2.
expect(mockCodec.numFramesAsked, 2);
await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame.
expect(mockCodec.numFramesAsked, 3);
timeDilation = 1.0; // restore time dilation, or it will affect other tests
});
testWidgets('error handlers can intercept errors', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter streamUnderTest = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
dynamic capturedException;
void errorListener(dynamic exception, StackTrace? stackTrace) {
capturedException = exception;
}
streamUnderTest.addListener(ImageStreamListener(
(ImageInfo image, bool synchronousCall) { },
onError: errorListener,
));
codecCompleter.complete(mockCodec);
// MultiFrameImageStreamCompleter only sets an error handler for the next
// frame future after the codec future has completed.
// Idling here lets the MultiFrameImageStreamCompleter advance and set the
// error handler for the nextFrame future.
await tester.idle();
mockCodec.failNextFrame('frame completion error');
await tester.idle();
// No exception is passed up.
expect(tester.takeException(), isNull);
expect(capturedException, 'frame completion error');
});
testWidgets('remove and add listener ', (WidgetTester tester) async {
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 3;
mockCodec.repetitionCount = 0;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
codecCompleter.complete(mockCodec);
await tester.idle(); // let nextFrameFuture complete
imageStream.addListener(ImageStreamListener(listener));
imageStream.removeListener(ImageStreamListener(listener));
final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10);
mockCodec.completeNextFrame(frame1);
await tester.idle(); // let nextFrameFuture complete
await tester.pump(); // first animation frame shows on first app frame.
await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame.
});
testWidgets('ImageStreamListener hashCode and equals', (WidgetTester tester) async {
void handleImage(ImageInfo image, bool synchronousCall) { }
void handleImageDifferently(ImageInfo image, bool synchronousCall) { }
void handleError(dynamic error, StackTrace? stackTrace) { }
void handleChunk(ImageChunkEvent event) { }
void compare({
required ImageListener onImage1,
required ImageListener onImage2,
ImageChunkListener? onChunk1,
ImageChunkListener? onChunk2,
ImageErrorListener? onError1,
ImageErrorListener? onError2,
bool areEqual = true,
}) {
final ImageStreamListener l1 = ImageStreamListener(onImage1, onChunk: onChunk1, onError: onError1);
final ImageStreamListener l2 = ImageStreamListener(onImage2, onChunk: onChunk2, onError: onError2);
Matcher comparison(dynamic expected) => areEqual ? equals(expected) : isNot(equals(expected));
expect(l1, comparison(l2));
expect(l1.hashCode, comparison(l2.hashCode));
}
compare(onImage1: handleImage, onImage2: handleImage);
compare(onImage1: handleImage, onImage2: handleImageDifferently, areEqual: false);
compare(onImage1: handleImage, onChunk1: handleChunk, onImage2: handleImage, onChunk2: handleChunk);
compare(onImage1: handleImage, onChunk1: handleChunk, onError1: handleError, onImage2: handleImage, onChunk2: handleChunk, onError2: handleError);
compare(onImage1: handleImage, onChunk1: handleChunk, onImage2: handleImage, areEqual: false);
compare(onImage1: handleImage, onChunk1: handleChunk, onError1: handleError, onImage2: handleImage, areEqual: false);
compare(onImage1: handleImage, onChunk1: handleChunk, onError1: handleError, onImage2: handleImage, onChunk2: handleChunk, areEqual: false);
compare(onImage1: handleImage, onChunk1: handleChunk, onError1: handleError, onImage2: handleImage, onError2: handleError, areEqual: false);
});
testWidgets('Keep alive handles do not drive frames or prevent last listener callbacks', (WidgetTester tester) async {
final Image image10x10 = (await tester.runAsync(() => createTestImage(width: 10, height: 10)))!;
final MockCodec mockCodec = MockCodec();
mockCodec.frameCount = 2;
mockCodec.repetitionCount = -1;
final Completer<Codec> codecCompleter = Completer<Codec>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
int onImageCount = 0;
void activeListener(ImageInfo image, bool synchronousCall) {
onImageCount += 1;
}
bool lastListenerDropped = false;
imageStream.addOnLastListenerRemovedCallback(() {
lastListenerDropped = true;
});
expect(lastListenerDropped, false);
final ImageStreamCompleterHandle handle = imageStream.keepAlive();
expect(lastListenerDropped, false);
SchedulerBinding.instance.debugAssertNoTransientCallbacks('Only passive listeners');
codecCompleter.complete(mockCodec);
await tester.idle();
expect(onImageCount, 0);
final FakeFrameInfo frame1 = FakeFrameInfo(Duration.zero, image20x10);
mockCodec.completeNextFrame(frame1);
await tester.idle();
SchedulerBinding.instance.debugAssertNoTransientCallbacks('Only passive listeners');
await tester.pump();
expect(onImageCount, 0);
imageStream.addListener(ImageStreamListener(activeListener));
final FakeFrameInfo frame2 = FakeFrameInfo(Duration.zero, image10x10);
mockCodec.completeNextFrame(frame2);
await tester.idle();
expect(SchedulerBinding.instance.transientCallbackCount, 1);
await tester.pump();
expect(onImageCount, 1);
imageStream.removeListener(ImageStreamListener(activeListener));
expect(lastListenerDropped, true);
mockCodec.completeNextFrame(frame1);
await tester.idle();
expect(SchedulerBinding.instance.transientCallbackCount, 1);
await tester.pump();
expect(onImageCount, 1);
SchedulerBinding.instance.debugAssertNoTransientCallbacks('Only passive listeners');
mockCodec.completeNextFrame(frame2);
await tester.idle();
SchedulerBinding.instance.debugAssertNoTransientCallbacks('Only passive listeners');
await tester.pump();
expect(onImageCount, 1);
handle.dispose();
});
test('MultiFrameImageStreamCompleter - one frame image should only be decoded once', () async {
final FakeCodec oneFrameCodec = await FakeCodec.fromData(Uint8List.fromList(kTransparentImage));
final Completer<Codec> codecCompleter = Completer<Codec>();
final Completer<void> decodeCompleter = Completer<void>();
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
codec: codecCompleter.future,
scale: 1.0,
);
final ImageStreamListener imageListener = ImageStreamListener((ImageInfo info, bool syncCall) {
decodeCompleter.complete();
});
imageStream.keepAlive(); // do not dispose
imageStream.addListener(imageListener);
codecCompleter.complete(oneFrameCodec);
await decodeCompleter.future;
imageStream.removeListener(imageListener);
expect(oneFrameCodec.numFramesAsked, 1);
// Adding a new listener for decoded imageSteam, the one frame image should
// not be decoded again.
imageStream.addListener(ImageStreamListener((ImageInfo info, bool syncCall) {}));
expect(oneFrameCodec.numFramesAsked, 1);
}); // https://github.com/flutter/flutter/issues/82532
test('Multi-frame complete unsubscribes to chunk events when disposed', () async {
final FakeCodec codec = await FakeCodec.fromData(Uint8List.fromList(kTransparentImage));
final StreamController<ImageChunkEvent> chunkStream = StreamController<ImageChunkEvent>();
final MultiFrameImageStreamCompleter completer = MultiFrameImageStreamCompleter(
codec: Future<Codec>.value(codec),
scale: 1.0,
chunkEvents: chunkStream.stream,
);
expect(chunkStream.hasListener, true);
chunkStream.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3));
final ImageStreamListener listener = ImageStreamListener((ImageInfo info, bool syncCall) {});
// Cause the completer to dispose.
completer.addListener(listener);
completer.removeListener(listener);
expect(chunkStream.hasListener, false);
// The above expectation should cover this, but the point of this test is to
// make sure the completer does not assert that it's disposed and still
// receiving chunk events. Streams from the network can keep sending data
// even after evicting an image from the cache, for example.
chunkStream.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3));
});
test('ImageStream, setCompleter before addListener - synchronousCall should be true', () async {
final Image image = await createTestImage(width: 100, height: 100);
final OneFrameImageStreamCompleter imageStreamCompleter =
OneFrameImageStreamCompleter(SynchronousFuture<ImageInfo>(TestImageInfo(1, image: image)));
final ImageStream imageStream = ImageStream();
imageStream.setCompleter(imageStreamCompleter);
bool? synchronouslyCalled;
imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) {
synchronouslyCalled = synchronousCall;
}));
expect(synchronouslyCalled, true);
});
test('ImageStream, setCompleter after addListener - synchronousCall should be false', () async {
final Image image = await createTestImage(width: 100, height: 100);
final OneFrameImageStreamCompleter imageStreamCompleter =
OneFrameImageStreamCompleter(SynchronousFuture<ImageInfo>(TestImageInfo(1, image: image)));
final ImageStream imageStream = ImageStream();
bool? synchronouslyCalled;
imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) {
synchronouslyCalled = synchronousCall;
}));
imageStream.setCompleter(imageStreamCompleter);
expect(synchronouslyCalled, false);
});
test('ImageStreamCompleterHandle dispatches memory events', () async {
await expectLater(
await memoryEvents(
() {
final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>();
addTearDown(streamController.close);
final ImageStreamCompleterHandle imageStreamCompleterHandle = FakeEventReportingImageStreamCompleter(
chunkEvents: streamController.stream,
).keepAlive();
imageStreamCompleterHandle.dispose();
},
ImageStreamCompleterHandle,
),
areCreateAndDispose,
);
});
testWidgets('ImageInfo dispatches memory events', (WidgetTester tester) async {
await expectLater(
await memoryEvents(
() async {
final ImageInfo info = ImageInfo(image: image20x10);
info.dispose();
},
ImageInfo,
),
areCreateAndDispose,
);
});
}
| flutter/packages/flutter/test/painting/image_stream_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/image_stream_test.dart",
"repo_id": "flutter",
"token_count": 11813
} | 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.
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('StrutStyle diagnostics test', () {
const StrutStyle s0 = StrutStyle(
fontFamily: 'Serif',
fontSize: 14,
);
expect(
s0.toString(),
equals('StrutStyle(family: Serif, size: 14.0)'),
);
const StrutStyle s1 = StrutStyle(
fontFamily: 'Serif',
fontSize: 14,
forceStrutHeight: true,
);
expect(s1.fontFamily, 'Serif');
expect(s1.fontSize, 14.0);
expect(s1, equals(s1));
expect(
s1.toString(),
equals('StrutStyle(family: Serif, size: 14.0, <strut height forced>)'),
);
const StrutStyle s2 = StrutStyle(
fontFamily: 'Serif',
fontSize: 14,
forceStrutHeight: false,
);
expect(
s2.toString(),
equals('StrutStyle(family: Serif, size: 14.0, <strut height normal>)'),
);
const StrutStyle s3 = StrutStyle();
expect(
s3.toString(),
equals('StrutStyle'),
);
const StrutStyle s4 = StrutStyle(
forceStrutHeight: false,
);
expect(
s4.toString(),
equals('StrutStyle(<strut height normal>)'),
);
const StrutStyle s5 = StrutStyle(
forceStrutHeight: true,
);
expect(
s5.toString(),
equals('StrutStyle(<strut height forced>)'),
);
});
}
| flutter/packages/flutter/test/painting/strut_style_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/strut_style_test.dart",
"repo_id": "flutter",
"token_count": 659
} | 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/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('RenderAspectRatio: Intrinsic sizing 2.0', () {
final RenderAspectRatio box = RenderAspectRatio(aspectRatio: 2.0);
expect(box.getMinIntrinsicWidth(200.0), 400.0);
expect(box.getMinIntrinsicWidth(400.0), 800.0);
expect(box.getMaxIntrinsicWidth(200.0), 400.0);
expect(box.getMaxIntrinsicWidth(400.0), 800.0);
expect(box.getMinIntrinsicHeight(200.0), 100.0);
expect(box.getMinIntrinsicHeight(400.0), 200.0);
expect(box.getMaxIntrinsicHeight(200.0), 100.0);
expect(box.getMaxIntrinsicHeight(400.0), 200.0);
expect(box.getMinIntrinsicWidth(double.infinity), 0.0);
expect(box.getMaxIntrinsicWidth(double.infinity), 0.0);
expect(box.getMinIntrinsicHeight(double.infinity), 0.0);
expect(box.getMaxIntrinsicHeight(double.infinity), 0.0);
});
test('RenderAspectRatio: Intrinsic sizing 0.5', () {
final RenderAspectRatio box = RenderAspectRatio(aspectRatio: 0.5);
expect(box.getMinIntrinsicWidth(200.0), 100.0);
expect(box.getMinIntrinsicWidth(400.0), 200.0);
expect(box.getMaxIntrinsicWidth(200.0), 100.0);
expect(box.getMaxIntrinsicWidth(400.0), 200.0);
expect(box.getMinIntrinsicHeight(200.0), 400.0);
expect(box.getMinIntrinsicHeight(400.0), 800.0);
expect(box.getMaxIntrinsicHeight(200.0), 400.0);
expect(box.getMaxIntrinsicHeight(400.0), 800.0);
expect(box.getMinIntrinsicWidth(double.infinity), 0.0);
expect(box.getMaxIntrinsicWidth(double.infinity), 0.0);
expect(box.getMinIntrinsicHeight(double.infinity), 0.0);
expect(box.getMaxIntrinsicHeight(double.infinity), 0.0);
});
test('RenderAspectRatio: Intrinsic sizing 2.0', () {
final RenderAspectRatio box = RenderAspectRatio(
aspectRatio: 2.0,
child: RenderSizedBox(const Size(90.0, 70.0)),
);
expect(box.getMinIntrinsicWidth(200.0), 400.0);
expect(box.getMinIntrinsicWidth(400.0), 800.0);
expect(box.getMaxIntrinsicWidth(200.0), 400.0);
expect(box.getMaxIntrinsicWidth(400.0), 800.0);
expect(box.getMinIntrinsicHeight(200.0), 100.0);
expect(box.getMinIntrinsicHeight(400.0), 200.0);
expect(box.getMaxIntrinsicHeight(200.0), 100.0);
expect(box.getMaxIntrinsicHeight(400.0), 200.0);
expect(box.getMinIntrinsicWidth(double.infinity), 90.0);
expect(box.getMaxIntrinsicWidth(double.infinity), 90.0);
expect(box.getMinIntrinsicHeight(double.infinity), 70.0);
expect(box.getMaxIntrinsicHeight(double.infinity), 70.0);
});
test('RenderAspectRatio: Intrinsic sizing 0.5', () {
final RenderAspectRatio box = RenderAspectRatio(
aspectRatio: 0.5,
child: RenderSizedBox(const Size(90.0, 70.0)),
);
expect(box.getMinIntrinsicWidth(200.0), 100.0);
expect(box.getMinIntrinsicWidth(400.0), 200.0);
expect(box.getMaxIntrinsicWidth(200.0), 100.0);
expect(box.getMaxIntrinsicWidth(400.0), 200.0);
expect(box.getMinIntrinsicHeight(200.0), 400.0);
expect(box.getMinIntrinsicHeight(400.0), 800.0);
expect(box.getMaxIntrinsicHeight(200.0), 400.0);
expect(box.getMaxIntrinsicHeight(400.0), 800.0);
expect(box.getMinIntrinsicWidth(double.infinity), 90.0);
expect(box.getMaxIntrinsicWidth(double.infinity), 90.0);
expect(box.getMinIntrinsicHeight(double.infinity), 70.0);
expect(box.getMaxIntrinsicHeight(double.infinity), 70.0);
});
test('RenderAspectRatio: Unbounded', () {
final RenderBox box = RenderConstrainedOverflowBox(
maxWidth: double.infinity,
maxHeight: double.infinity,
child: RenderAspectRatio(
aspectRatio: 0.5,
child: RenderSizedBox(const Size(90.0, 70.0)),
),
);
final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[];
layout(box, onErrors: () {
errors.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterErrorDetails());
});
expect(errors, hasLength(2));
expect(errors.first.exception, isFlutterError);
expect(
(errors.first.exception as FlutterError).toStringDeep(),
'FlutterError\n'
' RenderAspectRatio has unbounded constraints.\n'
' This RenderAspectRatio was given an aspect ratio of 0.5 but was\n'
' given both unbounded width and unbounded height constraints.\n'
' Because both constraints were unbounded, this render object\n'
" doesn't know how much size to consume.\n",
);
// The second error message is a generic message generated by the Dart VM. Not worth testing.
});
test('RenderAspectRatio: Sizing', () {
RenderConstrainedOverflowBox outside;
RenderAspectRatio inside;
layout(outside = RenderConstrainedOverflowBox(
child: inside = RenderAspectRatio(aspectRatio: 1.0),
));
pumpFrame();
expect(inside.size, const Size(800.0, 600.0));
outside.minWidth = 0.0;
outside.minHeight = 0.0;
outside.maxWidth = 100.0;
outside.maxHeight = 90.0;
pumpFrame();
expect(inside.size, const Size(90.0, 90.0));
outside.maxWidth = 90.0;
outside.maxHeight = 100.0;
pumpFrame();
expect(inside.size, const Size(90.0, 90.0));
outside.maxWidth = double.infinity;
outside.maxHeight = 90.0;
pumpFrame();
expect(inside.size, const Size(90.0, 90.0));
outside.maxWidth = 90.0;
outside.maxHeight = double.infinity;
pumpFrame();
expect(inside.size, const Size(90.0, 90.0));
inside.aspectRatio = 2.0;
outside.maxWidth = 100.0;
outside.maxHeight = 90.0;
pumpFrame();
expect(inside.size, const Size(100.0, 50.0));
outside.maxWidth = 90.0;
outside.maxHeight = 100.0;
pumpFrame();
expect(inside.size, const Size(90.0, 45.0));
outside.maxWidth = double.infinity;
outside.maxHeight = 90.0;
pumpFrame();
expect(inside.size, const Size(180.0, 90.0));
outside.maxWidth = 90.0;
outside.maxHeight = double.infinity;
pumpFrame();
expect(inside.size, const Size(90.0, 45.0));
outside.minWidth = 80.0;
outside.minHeight = 80.0;
outside.maxWidth = 100.0;
outside.maxHeight = 90.0;
pumpFrame();
expect(inside.size, const Size(100.0, 80.0));
outside.maxWidth = 90.0;
outside.maxHeight = 100.0;
pumpFrame();
expect(inside.size, const Size(90.0, 80.0));
outside.maxWidth = double.infinity;
outside.maxHeight = 90.0;
pumpFrame();
expect(inside.size, const Size(180.0, 90.0));
outside.maxWidth = 90.0;
outside.maxHeight = double.infinity;
pumpFrame();
expect(inside.size, const Size(90.0, 80.0));
});
}
| flutter/packages/flutter/test/rendering/aspect_ratio_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/aspect_ratio_test.dart",
"repo_id": "flutter",
"token_count": 2805
} | 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 'dart:async';
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_test/flutter_test.dart';
void main() {
final TestRenderBinding binding = TestRenderBinding();
test('Flutter dispatches first frame event on the web only', () async {
final Completer<void> completer = Completer<void>();
const MethodChannel firstFrameChannel = MethodChannel('flutter/service_worker');
binding.defaultBinaryMessenger.setMockMethodCallHandler(firstFrameChannel, (MethodCall methodCall) async {
completer.complete();
return null;
});
binding.handleBeginFrame(Duration.zero);
binding.handleDrawFrame();
await expectLater(completer.future, completes);
}, skip: !kIsWeb); // [intended] the test is only makes sense on the web.
}
class TestRenderBinding extends BindingBase
with SchedulerBinding,
ServicesBinding,
GestureBinding,
SemanticsBinding,
RendererBinding,
TestDefaultBinaryMessengerBinding { }
| flutter/packages/flutter/test/rendering/first_frame_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/first_frame_test.dart",
"repo_id": "flutter",
"token_count": 425
} | 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.
// THIS TEST IS SENSITIVE TO LINE NUMBERS AT THE TOP OF THIS FILE
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class RenderFoo extends RenderShiftedBox {
RenderFoo({ RenderBox? child }) : super(child);
@override
void performLayout() {
child?.layout(const BoxConstraints( // THIS MUST BE LINE 17
minWidth: 100.0, maxWidth: 50.0,
));
}
}
class Foo extends SingleChildRenderObjectWidget {
const Foo({ super.key, super.child });
@override
RenderFoo createRenderObject(BuildContext context) {
return RenderFoo();
}
}
// END OF SENSITIVE SECTION
void main() {
testWidgets('Stack parsing in non-normalized constraints error', (WidgetTester tester) async {
await tester.pumpWidget(const Foo(child: Placeholder()), duration: Duration.zero, phase: EnginePhase.layout);
final Object? exception = tester.takeException();
final String text = exception.toString();
expect(text, contains('BoxConstraints has non-normalized width constraints.'));
expect(text, contains('which probably computed the invalid constraints in question:\n RenderFoo.performLayout ('));
expect(text, contains('non_normalized_constraints_test.dart:'));
}, skip: kIsWeb); // [intended] stack traces on web are insufficiently predictable
}
| flutter/packages/flutter/test/rendering/non_normalized_constraints_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/non_normalized_constraints_test.dart",
"repo_id": "flutter",
"token_count": 478
} | 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/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('RelativeRect.==', () {
const RelativeRect r = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
expect(r, RelativeRect.fromSize(const Rect.fromLTWH(10.0, 20.0, 0.0, 0.0), const Size(40.0, 60.0)));
});
test('RelativeRect.fromDirectional', () {
final RelativeRect r1 = RelativeRect.fromDirectional(
textDirection: TextDirection.ltr,
start: 10.0,
top: 20.0,
end: 30.0,
bottom: 40.0,
);
final RelativeRect r2 = RelativeRect.fromDirectional(
textDirection: TextDirection.rtl,
start: 10.0,
top: 20.0,
end: 30.0,
bottom: 40.0,
);
expect(r1, const RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0));
expect(r2, const RelativeRect.fromLTRB(30.0, 20.0, 10.0, 40.0));
});
test('RelativeRect.shift', () {
const RelativeRect r1 = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
final RelativeRect r2 = r1.shift(const Offset(5.0, 50.0));
expect(r2, const RelativeRect.fromLTRB(15.0, 70.0, 25.0, -10.0));
});
test('RelativeRect.inflate', () {
const RelativeRect r1 = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
final RelativeRect r2 = r1.inflate(5.0);
expect(r2, const RelativeRect.fromLTRB(5.0, 15.0, 25.0, 35.0));
});
test('RelativeRect.deflate', () {
const RelativeRect r1 = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
final RelativeRect r2 = r1.deflate(5.0);
expect(r2, const RelativeRect.fromLTRB(15.0, 25.0, 35.0, 45.0));
});
test('RelativeRect.intersect', () {
const RelativeRect r1 = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
const RelativeRect r2 = RelativeRect.fromLTRB(0.0, 30.0, 60.0, 0.0);
final RelativeRect r3 = r1.intersect(r2);
final RelativeRect r4 = r2.intersect(r1);
expect(r3, r4);
expect(r3, const RelativeRect.fromLTRB(10.0, 30.0, 60.0, 40.0));
});
test('RelativeRect.toRect', () {
const RelativeRect r1 = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
final Rect r2 = r1.toRect(const Rect.fromLTRB(10.0, 20.0, 90.0, 180.0));
expect(r2, const Rect.fromLTRB(10.0, 20.0, 50.0, 120.0));
});
test('RelativeRect.toSize', () {
const RelativeRect r1 = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
final Size r2 = r1.toSize(const Size(80.0, 160.0));
expect(r2, const Size(40.0, 100.0));
});
test('RelativeRect.lerp', () {
const RelativeRect r1 = RelativeRect.fill;
const RelativeRect r2 = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
final RelativeRect r3 = RelativeRect.lerp(r1, r2, 0.5)!;
expect(r3, const RelativeRect.fromLTRB(5.0, 10.0, 15.0, 20.0));
});
test('RelativeRect.lerp identical a,b', () {
expect(RelativeRect.lerp(null, null, 0), null);
const RelativeRect rect = RelativeRect.fill;
expect(identical(RelativeRect.lerp(rect, rect, 0.5), rect), true);
});
}
| flutter/packages/flutter/test/rendering/relative_rect_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/relative_rect_test.dart",
"repo_id": "flutter",
"token_count": 1357
} | 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/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vector_math/vector_math_64.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('RenderViewport basic test - no children', () {
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
);
expect(root, hasAGoodToStringDeep);
expect(
root.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderViewport#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n'
' needs compositing\n'
' parentData: MISSING\n'
' constraints: MISSING\n'
' size: MISSING\n'
' axisDirection: down\n'
' crossAxisDirection: right\n'
' offset: _FixedViewportOffset#00000(offset: 0.0)\n'
' anchor: 0.0\n',
),
);
layout(root);
root.offset = ViewportOffset.fixed(900.0);
expect(root, hasAGoodToStringDeep);
expect(
root.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderViewport#00000 NEEDS-LAYOUT NEEDS-PAINT\n'
' needs compositing\n'
' parentData: <none>\n'
' constraints: BoxConstraints(w=800.0, h=600.0)\n'
' size: Size(800.0, 600.0)\n'
' axisDirection: down\n'
' crossAxisDirection: right\n'
' offset: _FixedViewportOffset#00000(offset: 900.0)\n'
' anchor: 0.0\n',
),
);
pumpFrame();
});
test('RenderViewport basic test - down', () {
RenderBox a, b, c, d, e;
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: a = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: b = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: c = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: d = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: e = RenderSizedBox(const Size(100.0, 400.0))),
],
);
expect(root, hasAGoodToStringDeep);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(root, hasAGoodToStringDeep);
expect(
root.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderViewport#00000 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n'
' │ needs compositing\n'
' │ parentData: <none>\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ axisDirection: down\n'
' │ crossAxisDirection: right\n'
' │ offset: _FixedViewportOffset#00000(offset: 0.0)\n'
' │ anchor: 0.0\n'
' │\n'
' ├─center child: RenderSliverToBoxAdapter#00000 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n'
' │ │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n'
' │ │ constraints: SliverConstraints(AxisDirection.down,\n'
' │ │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n'
' │ │ 0.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0,\n'
' │ │ crossAxisExtent: 800.0, crossAxisDirection:\n'
' │ │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n'
' │ │ remainingCacheExtent: 850.0, cacheOrigin: 0.0)\n'
' │ │ geometry: SliverGeometry(scrollExtent: 400.0, paintExtent: 400.0,\n'
' │ │ maxPaintExtent: 400.0, cacheExtent: 400.0)\n'
' │ │\n'
' │ └─child: RenderSizedBox#00000 NEEDS-PAINT\n'
' │ parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, 0.0<=h<=Infinity)\n'
' │ size: Size(800.0, 400.0)\n'
' │\n'
' ├─child 1: RenderSliverToBoxAdapter#00000 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n'
' │ │ parentData: paintOffset=Offset(0.0, 400.0) (can use size)\n'
' │ │ constraints: SliverConstraints(AxisDirection.down,\n'
' │ │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n'
' │ │ 0.0, precedingScrollExtent: 400.0, remainingPaintExtent: 200.0,\n'
' │ │ crossAxisExtent: 800.0, crossAxisDirection:\n'
' │ │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n'
' │ │ remainingCacheExtent: 450.0, cacheOrigin: 0.0)\n'
' │ │ geometry: SliverGeometry(scrollExtent: 400.0, paintExtent: 200.0,\n'
' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true, cacheExtent:\n'
' │ │ 400.0)\n'
' │ │\n'
' │ └─child: RenderSizedBox#00000 NEEDS-PAINT\n'
' │ parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, 0.0<=h<=Infinity)\n'
' │ size: Size(800.0, 400.0)\n'
' │\n'
' ├─child 2: RenderSliverToBoxAdapter#00000 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n'
' │ │ parentData: paintOffset=Offset(0.0, 800.0) (can use size)\n'
' │ │ constraints: SliverConstraints(AxisDirection.down,\n'
' │ │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n'
' │ │ 0.0, precedingScrollExtent: 800.0, remainingPaintExtent: 0.0,\n'
' │ │ crossAxisExtent: 800.0, crossAxisDirection:\n'
' │ │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n'
' │ │ remainingCacheExtent: 50.0, cacheOrigin: 0.0)\n'
' │ │ geometry: SliverGeometry(scrollExtent: 400.0, hidden,\n'
' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true, cacheExtent:\n'
' │ │ 50.0)\n'
' │ │\n'
' │ └─child: RenderSizedBox#00000 NEEDS-PAINT\n'
' │ parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, 0.0<=h<=Infinity)\n'
' │ size: Size(800.0, 400.0)\n'
' │\n'
' ├─child 3: RenderSliverToBoxAdapter#00000 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n'
' │ │ parentData: paintOffset=Offset(0.0, 1200.0) (can use size)\n'
' │ │ constraints: SliverConstraints(AxisDirection.down,\n'
' │ │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n'
' │ │ 0.0, precedingScrollExtent: 1200.0, remainingPaintExtent: 0.0,\n'
' │ │ crossAxisExtent: 800.0, crossAxisDirection:\n'
' │ │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n'
' │ │ remainingCacheExtent: 0.0, cacheOrigin: 0.0)\n'
' │ │ geometry: SliverGeometry(scrollExtent: 400.0, hidden,\n'
' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true)\n'
' │ │\n'
' │ └─child: RenderSizedBox#00000 NEEDS-PAINT\n'
' │ parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, 0.0<=h<=Infinity)\n'
' │ size: Size(800.0, 400.0)\n'
' │\n'
' └─child 4: RenderSliverToBoxAdapter#00000 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n'
' │ parentData: paintOffset=Offset(0.0, 1600.0) (can use size)\n'
' │ constraints: SliverConstraints(AxisDirection.down,\n'
' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n'
' │ 0.0, precedingScrollExtent: 1600.0, remainingPaintExtent: 0.0,\n'
' │ crossAxisExtent: 800.0, crossAxisDirection:\n'
' │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n'
' │ remainingCacheExtent: 0.0, cacheOrigin: 0.0)\n'
' │ geometry: SliverGeometry(scrollExtent: 400.0, hidden,\n'
' │ maxPaintExtent: 400.0, hasVisualOverflow: true)\n'
' │\n'
' └─child: RenderSizedBox#00000 NEEDS-PAINT\n'
' parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n'
' constraints: BoxConstraints(w=800.0, 0.0<=h<=Infinity)\n'
' size: Size(800.0, 400.0)\n',
),
);
expect(a.localToGlobal(Offset.zero), Offset.zero);
expect(b.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, 800.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, 1200.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, 1600.0));
expect(a.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 400.0));
expect(b.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 800.0));
expect(c.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 1200.0));
expect(d.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 1600.0));
expect(e.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 2000.0));
root.offset = ViewportOffset.fixed(200.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, -200.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, 200.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, 600.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, 1000.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, 1400.0));
root.offset = ViewportOffset.fixed(600.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, -600.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, -200.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, 200.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, 600.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, 1000.0));
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, -900.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, -500.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, -100.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, 300.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, 700.0));
final BoxHitTestResult result = BoxHitTestResult();
root.hitTest(result, position: const Offset(130.0, 150.0));
expect(result.path.first.target, equals(c));
});
test('RenderViewport basic test - up', () {
RenderBox a, b, c, d, e;
final RenderViewport root = RenderViewport(
axisDirection: AxisDirection.up,
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: a = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: b = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: c = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: d = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: e = RenderSizedBox(const Size(100.0, 400.0))),
],
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(a.localToGlobal(Offset.zero), const Offset(0.0, 200.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, -200.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, -600.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, -1000.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, -1400.0));
root.offset = ViewportOffset.fixed(200.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(b.localToGlobal(Offset.zero), Offset.zero);
expect(c.localToGlobal(Offset.zero), const Offset(0.0, -400.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, -800.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, -1200.0));
root.offset = ViewportOffset.fixed(600.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, 800.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(c.localToGlobal(Offset.zero), Offset.zero);
expect(d.localToGlobal(Offset.zero), const Offset(0.0, -400.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, -800.0));
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, 1100.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, 700.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, 300.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, -100.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, -500.0));
final BoxHitTestResult result = BoxHitTestResult();
root.hitTest(result, position: const Offset(150.0, 350.0));
expect(result.path.first.target, equals(c));
});
Offset getPaintOrigin(RenderObject render) {
final Vector3 transformed3 = render.getTransformTo(null).perspectiveTransform(Vector3(0.0, 0.0, 0.0));
return Offset(transformed3.x, transformed3.y);
}
test('RenderViewport basic test - right', () {
RenderBox a, b, c, d, e;
final RenderViewport root = RenderViewport(
axisDirection: AxisDirection.right,
crossAxisDirection: AxisDirection.down,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: a = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: b = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: c = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: d = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: e = RenderSizedBox(const Size(400.0, 100.0))),
],
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
final RenderSliver sliverA = a.parent! as RenderSliver;
final RenderSliver sliverB = b.parent! as RenderSliver;
final RenderSliver sliverC = c.parent! as RenderSliver;
final RenderSliver sliverD = d.parent! as RenderSliver;
final RenderSliver sliverE = e.parent! as RenderSliver;
expect(a.localToGlobal(Offset.zero), Offset.zero);
expect(b.localToGlobal(Offset.zero), const Offset(400.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(800.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(1200.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(1600.0, 0.0));
expect(getPaintOrigin(sliverA), Offset.zero);
expect(getPaintOrigin(sliverB), const Offset(400.0, 0.0));
expect(getPaintOrigin(sliverC), const Offset(800.0, 0.0));
expect(getPaintOrigin(sliverD), const Offset(1200.0, 0.0));
expect(getPaintOrigin(sliverE), const Offset(1600.0, 0.0));
root.offset = ViewportOffset.fixed(200.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(-200.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(200.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(1000.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(1400.0, 0.0));
expect(getPaintOrigin(sliverA), Offset.zero);
expect(getPaintOrigin(sliverB), const Offset(200.0, 0.0));
expect(getPaintOrigin(sliverC), const Offset(600.0, 0.0));
expect(getPaintOrigin(sliverD), const Offset(1000.0, 0.0));
expect(getPaintOrigin(sliverE), const Offset(1400.0, 0.0));
root.offset = ViewportOffset.fixed(600.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(-600.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(-200.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(200.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(1000.0, 0.0));
expect(getPaintOrigin(sliverA), Offset.zero);
expect(getPaintOrigin(sliverB), Offset.zero);
expect(getPaintOrigin(sliverC), const Offset(200.0, 0.0));
expect(getPaintOrigin(sliverD), const Offset(600.0, 0.0));
expect(getPaintOrigin(sliverE), const Offset(1000.0, 0.0));
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(-900.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(-500.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(-100.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(300.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(700.0, 0.0));
expect(getPaintOrigin(sliverA), Offset.zero);
expect(getPaintOrigin(sliverB), Offset.zero);
expect(getPaintOrigin(sliverC), Offset.zero);
expect(getPaintOrigin(sliverD), const Offset(300.0, 0.0));
expect(getPaintOrigin(sliverE), const Offset(700.0, 0.0));
final BoxHitTestResult result = BoxHitTestResult();
root.hitTest(result, position: const Offset(150.0, 450.0));
expect(result.path.first.target, equals(c));
});
test('RenderViewport basic test - left', () {
RenderBox a, b, c, d, e;
final RenderViewport root = RenderViewport(
axisDirection: AxisDirection.left,
crossAxisDirection: AxisDirection.down,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: a = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: b = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: c = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: d = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: e = RenderSizedBox(const Size(400.0, 100.0))),
],
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(a.localToGlobal(Offset.zero), const Offset(400.0, 0.0));
expect(b.localToGlobal(Offset.zero), Offset.zero);
expect(c.localToGlobal(Offset.zero), const Offset(-400.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(-800.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(-1200.0, 0.0));
root.offset = ViewportOffset.fixed(200.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(200.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(-200.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(-600.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(-1000.0, 0.0));
root.offset = ViewportOffset.fixed(600.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(1000.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(200.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(-200.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(-600.0, 0.0));
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(1300.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(900.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(500.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(100.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(-300.0, 0.0));
final BoxHitTestResult result = BoxHitTestResult();
root.hitTest(result, position: const Offset(550.0, 150.0));
expect(result.path.first.target, equals(c));
});
// TODO(ianh): test anchor
// TODO(ianh): test center
// TODO(ianh): test semantics
test('RenderShrinkWrappingViewport basic test - no children', () {
final RenderShrinkWrappingViewport root = RenderShrinkWrappingViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
);
expect(root, hasAGoodToStringDeep);
layout(root);
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
});
test('RenderShrinkWrappingViewport basic test - down', () {
RenderBox a, b, c, d, e;
final RenderShrinkWrappingViewport root = RenderShrinkWrappingViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: a = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: b = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: c = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: d = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: e = RenderSizedBox(const Size(100.0, 400.0))),
],
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(a.localToGlobal(Offset.zero), Offset.zero);
expect(b.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, 800.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, 1200.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, 1600.0));
expect(a.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 400.0));
expect(b.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 800.0));
expect(c.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 1200.0));
expect(d.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 1600.0));
expect(e.localToGlobal(const Offset(800.0, 400.0)), const Offset(800.0, 2000.0));
root.offset = ViewportOffset.fixed(200.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, -200.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, 200.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, 600.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, 1000.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, 1400.0));
root.offset = ViewportOffset.fixed(600.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, -600.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, -200.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, 200.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, 600.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, 1000.0));
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, -900.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, -500.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, -100.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, 300.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, 700.0));
final BoxHitTestResult result = BoxHitTestResult();
root.hitTest(result, position: const Offset(130.0, 150.0));
expect(result.path.first.target, equals(c));
});
test('RenderShrinkWrappingViewport basic test - up', () {
RenderBox a, b, c, d, e;
final RenderShrinkWrappingViewport root = RenderShrinkWrappingViewport(
axisDirection: AxisDirection.up,
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: a = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: b = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: c = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: d = RenderSizedBox(const Size(100.0, 400.0))),
RenderSliverToBoxAdapter(child: e = RenderSizedBox(const Size(100.0, 400.0))),
],
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(a.localToGlobal(Offset.zero), const Offset(0.0, 200.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, -200.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, -600.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, -1000.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, -1400.0));
root.offset = ViewportOffset.fixed(200.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(b.localToGlobal(Offset.zero), Offset.zero);
expect(c.localToGlobal(Offset.zero), const Offset(0.0, -400.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, -800.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, -1200.0));
root.offset = ViewportOffset.fixed(600.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, 800.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(c.localToGlobal(Offset.zero), Offset.zero);
expect(d.localToGlobal(Offset.zero), const Offset(0.0, -400.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, -800.0));
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(0.0, 1100.0));
expect(b.localToGlobal(Offset.zero), const Offset(0.0, 700.0));
expect(c.localToGlobal(Offset.zero), const Offset(0.0, 300.0));
expect(d.localToGlobal(Offset.zero), const Offset(0.0, -100.0));
expect(e.localToGlobal(Offset.zero), const Offset(0.0, -500.0));
final BoxHitTestResult result = BoxHitTestResult();
root.hitTest(result, position: const Offset(150.0, 350.0));
expect(result.path.first.target, equals(c));
});
test('RenderShrinkWrappingViewport basic test - right', () {
RenderBox a, b, c, d, e;
final RenderShrinkWrappingViewport root = RenderShrinkWrappingViewport(
axisDirection: AxisDirection.right,
crossAxisDirection: AxisDirection.down,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: a = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: b = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: c = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: d = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: e = RenderSizedBox(const Size(400.0, 100.0))),
],
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(a.localToGlobal(Offset.zero), Offset.zero);
expect(b.localToGlobal(Offset.zero), const Offset(400.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(800.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(1200.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(1600.0, 0.0));
root.offset = ViewportOffset.fixed(200.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(-200.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(200.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(1000.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(1400.0, 0.0));
root.offset = ViewportOffset.fixed(600.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(-600.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(-200.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(200.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(1000.0, 0.0));
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(-900.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(-500.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(-100.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(300.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(700.0, 0.0));
final BoxHitTestResult result = BoxHitTestResult();
root.hitTest(result, position: const Offset(150.0, 450.0));
expect(result.path.first.target, equals(c));
});
test('RenderShrinkWrappingViewport basic test - left', () {
RenderBox a, b, c, d, e;
final RenderShrinkWrappingViewport root = RenderShrinkWrappingViewport(
axisDirection: AxisDirection.left,
crossAxisDirection: AxisDirection.down,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: a = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: b = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: c = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: d = RenderSizedBox(const Size(400.0, 100.0))),
RenderSliverToBoxAdapter(child: e = RenderSizedBox(const Size(400.0, 100.0))),
],
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(a.localToGlobal(Offset.zero), const Offset(400.0, 0.0));
expect(b.localToGlobal(Offset.zero), Offset.zero);
expect(c.localToGlobal(Offset.zero), const Offset(-400.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(-800.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(-1200.0, 0.0));
root.offset = ViewportOffset.fixed(200.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(200.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(-200.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(-600.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(-1000.0, 0.0));
root.offset = ViewportOffset.fixed(600.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(1000.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(200.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(-200.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(-600.0, 0.0));
root.offset = ViewportOffset.fixed(900.0);
pumpFrame();
expect(a.localToGlobal(Offset.zero), const Offset(1300.0, 0.0));
expect(b.localToGlobal(Offset.zero), const Offset(900.0, 0.0));
expect(c.localToGlobal(Offset.zero), const Offset(500.0, 0.0));
expect(d.localToGlobal(Offset.zero), const Offset(100.0, 0.0));
expect(e.localToGlobal(Offset.zero), const Offset(-300.0, 0.0));
final BoxHitTestResult result = BoxHitTestResult();
root.hitTest(result, position: const Offset(550.0, 150.0));
expect(result.path.first.target, equals(c));
});
test('RenderShrinkWrappingViewport shrinkwrap test - 1 child', () {
RenderBox child;
final RenderBox root = RenderPositionedBox(
child: child = RenderShrinkWrappingViewport(
axisDirection: AxisDirection.left,
crossAxisDirection: AxisDirection.down,
offset: ViewportOffset.fixed(200.0),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: RenderSizedBox(const Size(400.0, 100.0))),
],
),
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(child.size.width, equals(400.0));
expect(child.size.height, equals(600.0));
});
test('RenderShrinkWrappingViewport shrinkwrap test - 2 children', () {
RenderBox child;
final RenderBox root = RenderPositionedBox(
child: child = RenderShrinkWrappingViewport(
axisDirection: AxisDirection.right,
crossAxisDirection: AxisDirection.down,
offset: ViewportOffset.fixed(200.0),
children: <RenderSliver>[
RenderSliverToBoxAdapter(child: RenderSizedBox(const Size(300.0, 100.0))),
RenderSliverToBoxAdapter(child: RenderSizedBox(const Size(150.0, 100.0))),
],
),
);
layout(root);
expect(root.size.width, equals(800.0));
expect(root.size.height, equals(600.0));
expect(child.size.width, equals(450.0));
expect(child.size.height, equals(600.0));
});
test('SliverGeometry toString', () {
expect(
SliverGeometry.zero.toString(),
equals('SliverGeometry(scrollExtent: 0.0, hidden, maxPaintExtent: 0.0)'),
);
expect(
const SliverGeometry(
scrollExtent: 100.0,
paintExtent: 50.0,
layoutExtent: 20.0,
visible: true,
).toString(),
equals(
'SliverGeometry(scrollExtent: 100.0, paintExtent: 50.0, layoutExtent: 20.0, maxPaintExtent: 0.0, cacheExtent: 20.0)',
),
);
expect(
const SliverGeometry(
scrollExtent: 100.0,
layoutExtent: 20.0,
).toString(),
equals(
'SliverGeometry(scrollExtent: 100.0, hidden, layoutExtent: 20.0, maxPaintExtent: 0.0, cacheExtent: 20.0)',
),
);
});
test('Sliver paintBounds and semanticBounds - vertical', () {
const double height = 150.0;
final RenderSliver sliver = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, height)),
);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
sliver,
],
);
layout(root);
final Rect expectedRect = Rect.fromLTWH(0.0, 0.0, root.size.width, height);
expect(sliver.paintBounds, expectedRect);
expect(sliver.semanticBounds, expectedRect);
});
test('Sliver paintBounds and semanticBounds - horizontal', () {
const double width = 150.0;
final RenderSliver sliver = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(width, 400.0)),
);
final RenderViewport root = RenderViewport(
axisDirection: AxisDirection.right,
crossAxisDirection: AxisDirection.down,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
sliver,
],
);
layout(root);
final Rect expectedRect = Rect.fromLTWH(0.0, 0.0, width, root.size.height);
expect(sliver.paintBounds, expectedRect);
expect(sliver.semanticBounds, expectedRect);
});
test('precedingScrollExtent is 0.0 for first Sliver in list', () {
const double viewportWidth = 800.0;
final RenderSliver sliver = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(viewportWidth, 150.0)),
);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
sliver,
],
);
layout(root);
expect(sliver.constraints.precedingScrollExtent, 0.0);
});
test('precedingScrollExtent accumulates over multiple Slivers', () {
const double viewportWidth = 800.0;
final RenderSliver sliver1 = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(viewportWidth, 150.0)),
);
final RenderSliver sliver2 = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(viewportWidth, 150.0)),
);
final RenderSliver sliver3 = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(viewportWidth, 150.0)),
);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
sliver1,
sliver2,
sliver3,
],
);
layout(root);
// The 3rd Sliver comes after 300.0px of preceding scroll extent by first 2 Slivers.
expect(sliver3.constraints.precedingScrollExtent, 300.0);
});
test('precedingScrollExtent is not impacted by scrollOffset', () {
const double viewportWidth = 800.0;
final RenderSliver sliver1 = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(viewportWidth, 150.0)),
);
final RenderSliver sliver2 = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(viewportWidth, 150.0)),
);
final RenderSliver sliver3 = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(viewportWidth, 150.0)),
);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.fixed(100.0),
children: <RenderSliver>[
sliver1,
sliver2,
sliver3,
],
);
layout(root);
// The 3rd Sliver comes after 300.0px of preceding scroll extent by first 2 Slivers.
// In this test a ViewportOffset is applied to simulate a scrollOffset. That
// offset is not expected to impact the precedingScrollExtent.
expect(sliver3.constraints.precedingScrollExtent, 300.0);
});
group('hit testing', () {
test('SliverHitTestResult wrapping HitTestResult', () {
final HitTestEntry entry1 = HitTestEntry(_DummyHitTestTarget());
final HitTestEntry entry2 = HitTestEntry(_DummyHitTestTarget());
final HitTestEntry entry3 = HitTestEntry(_DummyHitTestTarget());
final Matrix4 transform = Matrix4.translationValues(40.0, 150.0, 0.0);
final HitTestResult wrapped = MyHitTestResult()
..publicPushTransform(transform);
wrapped.add(entry1);
expect(wrapped.path, equals(<HitTestEntry>[entry1]));
expect(entry1.transform, transform);
final SliverHitTestResult wrapping = SliverHitTestResult.wrap(wrapped);
expect(wrapping.path, equals(<HitTestEntry>[entry1]));
expect(wrapping.path, same(wrapped.path));
wrapping.add(entry2);
expect(wrapping.path, equals(<HitTestEntry>[entry1, entry2]));
expect(wrapped.path, equals(<HitTestEntry>[entry1, entry2]));
expect(entry2.transform, transform);
wrapped.add(entry3);
expect(wrapping.path, equals(<HitTestEntry>[entry1, entry2, entry3]));
expect(wrapped.path, equals(<HitTestEntry>[entry1, entry2, entry3]));
expect(entry3.transform, transform);
});
test('addWithAxisOffset', () {
final SliverHitTestResult result = SliverHitTestResult();
final List<double> mainAxisPositions = <double>[];
final List<double> crossAxisPositions = <double>[];
const Offset paintOffsetDummy = Offset.zero;
bool isHit = result.addWithAxisOffset(
paintOffset: paintOffsetDummy,
mainAxisOffset: 0.0,
crossAxisOffset: 0.0,
mainAxisPosition: 0.0,
crossAxisPosition: 0.0,
hitTest: (SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
mainAxisPositions.add(mainAxisPosition);
crossAxisPositions.add(crossAxisPosition);
return true;
},
);
expect(isHit, isTrue);
expect(mainAxisPositions.single, 0.0);
expect(crossAxisPositions.single, 0.0);
mainAxisPositions.clear();
crossAxisPositions.clear();
isHit = result.addWithAxisOffset(
paintOffset: paintOffsetDummy,
mainAxisOffset: 5.0,
crossAxisOffset: 6.0,
mainAxisPosition: 10.0,
crossAxisPosition: 20.0,
hitTest: (SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
mainAxisPositions.add(mainAxisPosition);
crossAxisPositions.add(crossAxisPosition);
return false;
},
);
expect(isHit, isFalse);
expect(mainAxisPositions.single, 10.0 - 5.0);
expect(crossAxisPositions.single, 20.0 - 6.0);
mainAxisPositions.clear();
crossAxisPositions.clear();
isHit = result.addWithAxisOffset(
paintOffset: paintOffsetDummy,
mainAxisOffset: -5.0,
crossAxisOffset: -6.0,
mainAxisPosition: 10.0,
crossAxisPosition: 20.0,
hitTest: (SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
mainAxisPositions.add(mainAxisPosition);
crossAxisPositions.add(crossAxisPosition);
return false;
},
);
expect(isHit, isFalse);
expect(mainAxisPositions.single, 10.0 + 5.0);
expect(crossAxisPositions.single, 20.0 + 6.0);
mainAxisPositions.clear();
crossAxisPositions.clear();
});
test('addWithAxisOffset with non zero paintOffset', () {
final SliverHitTestResult result = SliverHitTestResult();
late double recordedMainAxisPosition;
late double recordedCrossAxisPosition;
final HitTestEntry entry = HitTestEntry(_DummyHitTestTarget());
const Offset paintOffset = Offset(7, 11);
final bool isHit = result.addWithAxisOffset(
paintOffset: paintOffset,
mainAxisOffset: 5.0,
crossAxisOffset: 6.0,
mainAxisPosition: 10.0,
crossAxisPosition: 20.0,
hitTest: (SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
recordedMainAxisPosition = mainAxisPosition;
recordedCrossAxisPosition = crossAxisPosition;
result.add(entry);
return true;
},
);
expect(isHit, isTrue);
expect(recordedMainAxisPosition, 10.0 - 5.0);
expect(recordedCrossAxisPosition, 20.0 - 6.0);
expect(
entry.transform!..translate(paintOffset.dx, paintOffset.dy),
Matrix4.identity(),
);
});
});
test('SliverConstraints check for NaN on all double properties', () {
const SliverConstraints constraints = SliverConstraints(
axisDirection: AxisDirection.down,
cacheOrigin: double.nan,
crossAxisDirection: AxisDirection.left,
crossAxisExtent: double.nan,
growthDirection: GrowthDirection.forward,
overlap: double.nan,
precedingScrollExtent: double.nan,
remainingCacheExtent: double.nan,
remainingPaintExtent: double.nan,
scrollOffset: double.nan,
userScrollDirection: ScrollDirection.idle,
viewportMainAxisExtent: double.nan,
);
bool threw = false;
try {
constraints.debugAssertIsValid();
} on FlutterError catch (error) {
expect(
error.message,
'SliverConstraints is not valid:\n'
' The "scrollOffset" is NaN.\n'
' The "overlap" is NaN.\n'
' The "crossAxisExtent" is NaN.\n'
' The "scrollOffset" is NaN, expected greater than or equal to zero.\n'
' The "viewportMainAxisExtent" is NaN, expected greater than or equal to zero.\n'
' The "remainingPaintExtent" is NaN, expected greater than or equal to zero.\n'
' The "remainingCacheExtent" is NaN, expected greater than or equal to zero.\n'
' The "cacheOrigin" is NaN, expected less than or equal to zero.\n'
' The "precedingScrollExtent" is NaN, expected greater than or equal to zero.\n'
' The constraints are not normalized.\n'
'The offending constraints were:\n'
' SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle, scrollOffset: NaN, precedingScrollExtent: NaN, remainingPaintExtent: NaN, overlap: NaN, crossAxisExtent: NaN, crossAxisDirection: AxisDirection.left, viewportMainAxisExtent: NaN, remainingCacheExtent: NaN, cacheOrigin: NaN)',
);
threw = true;
}
expect(threw, true);
});
test('SliverConstraints check for sign on relevant double properties', () {
const SliverConstraints constraints = SliverConstraints(
axisDirection: AxisDirection.down,
cacheOrigin: 1.0,
crossAxisDirection: AxisDirection.left,
crossAxisExtent: 0.0,
growthDirection: GrowthDirection.forward,
overlap: 0.0,
precedingScrollExtent: -1.0,
remainingCacheExtent: -1.0,
remainingPaintExtent: -1.0,
scrollOffset: -1.0,
userScrollDirection: ScrollDirection.idle,
viewportMainAxisExtent: 0.0,
);
bool threw = false;
try {
constraints.debugAssertIsValid();
} on FlutterError catch (error) {
expect(
error.message,
'SliverConstraints is not valid:\n'
' The "scrollOffset" is negative.\n'
' The "remainingPaintExtent" is negative.\n'
' The "remainingCacheExtent" is negative.\n'
' The "cacheOrigin" is positive.\n'
' The "precedingScrollExtent" is negative.\n'
' The constraints are not normalized.\n'
'The offending constraints were:\n'
' SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle, scrollOffset: -1.0, precedingScrollExtent: -1.0, remainingPaintExtent: -1.0, crossAxisExtent: 0.0, crossAxisDirection: AxisDirection.left, viewportMainAxisExtent: 0.0, remainingCacheExtent: -1.0, cacheOrigin: 1.0)',
);
threw = true;
}
expect(threw, true);
});
}
class _DummyHitTestTarget implements HitTestTarget {
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
// Nothing to do.
}
}
class MyHitTestResult extends HitTestResult {
void publicPushTransform(Matrix4 transform) => pushTransform(transform);
}
| flutter/packages/flutter/test/rendering/slivers_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/slivers_test.dart",
"repo_id": "flutter",
"token_count": 18897
} | 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 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Priority operators control test', () async {
Priority priority = Priority.idle + (Priority.kMaxOffset + 100);
expect(priority.value, equals(Priority.idle.value + Priority.kMaxOffset));
priority = Priority.animation - (Priority.kMaxOffset + 100);
expect(priority.value, equals(Priority.animation.value - Priority.kMaxOffset));
});
}
| flutter/packages/flutter/test/scheduler/priority_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/scheduler/priority_test.dart",
"repo_id": "flutter",
"token_count": 194
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class _TestBinding extends BindingBase with SchedulerBinding, ServicesBinding {
@override
Future<void> initializationComplete() async {
return super.initializationComplete();
}
@override
TestDefaultBinaryMessenger get defaultBinaryMessenger => super.defaultBinaryMessenger as TestDefaultBinaryMessenger;
@override
TestDefaultBinaryMessenger createBinaryMessenger() {
Future<ByteData?> keyboardHandler(ByteData? message) async {
return const StandardMethodCodec().encodeSuccessEnvelope(<int, int>{1:1});
}
return TestDefaultBinaryMessenger(
super.createBinaryMessenger(),
outboundHandlers: <String, MessageHandler>{'flutter/keyboard': keyboardHandler},
);
}
}
void main() {
final _TestBinding binding = _TestBinding();
test('can send message on completion of binding initialization', () async {
bool called = false;
binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall method) async {
if (method.method == 'System.initializationComplete') {
called = true;
}
return null;
});
await binding.initializationComplete();
expect(called, isTrue);
});
}
| flutter/packages/flutter/test/services/binding_lifecycle_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/binding_lifecycle_test.dart",
"repo_id": "flutter",
"token_count": 482
} | 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:typed_data';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void checkEncoding<T>(MessageCodec<T> codec, T message, List<int> expectedBytes) {
final ByteData encoded = codec.encodeMessage(message)!;
expect(
encoded.buffer.asUint8List(0, encoded.lengthInBytes),
orderedEquals(expectedBytes),
);
}
void checkEncodeDecode<T>(MessageCodec<T> codec, T message) {
final ByteData? encoded = codec.encodeMessage(message);
final T? decoded = codec.decodeMessage(encoded);
if (message == null) {
expect(encoded, isNull);
expect(decoded, isNull);
} else {
expect(deepEquals(message, decoded), isTrue);
final ByteData? encodedAgain = codec.encodeMessage(decoded as T);
expect(
encodedAgain!.buffer.asUint8List(),
orderedEquals(encoded!.buffer.asUint8List()),
);
}
}
bool deepEquals(dynamic valueA, dynamic valueB) {
if (valueA is TypedData) {
return valueB is TypedData && deepEqualsTypedData(valueA, valueB);
}
if (valueA is List) {
return valueB is List && deepEqualsList(valueA, valueB);
}
if (valueA is Map) {
return valueB is Map && deepEqualsMap(valueA, valueB);
}
if (valueA is double && valueA.isNaN) {
return valueB is double && valueB.isNaN;
}
return valueA == valueB;
}
bool deepEqualsTypedData(TypedData valueA, TypedData valueB) {
if (valueA is ByteData) {
return valueB is ByteData
&& deepEqualsList(valueA.buffer.asUint8List(), valueB.buffer.asUint8List());
}
if (valueA is Uint8List) {
return valueB is Uint8List && deepEqualsList(valueA, valueB);
}
if (valueA is Int32List) {
return valueB is Int32List && deepEqualsList(valueA, valueB);
}
if (valueA is Int64List) {
return valueB is Int64List && deepEqualsList(valueA, valueB);
}
if (valueA is Float32List) {
return valueB is Float32List && deepEqualsList(valueA, valueB);
}
if (valueA is Float64List) {
return valueB is Float64List && deepEqualsList(valueA, valueB);
}
throw 'Unexpected typed data: $valueA';
}
bool deepEqualsList(List<dynamic> valueA, List<dynamic> valueB) {
if (valueA.length != valueB.length) {
return false;
}
for (int i = 0; i < valueA.length; i++) {
if (!deepEquals(valueA[i], valueB[i])) {
return false;
}
}
return true;
}
bool deepEqualsMap(Map<dynamic, dynamic> valueA, Map<dynamic, dynamic> valueB) {
if (valueA.length != valueB.length) {
return false;
}
for (final dynamic key in valueA.keys) {
if (!valueB.containsKey(key) || !deepEquals(valueA[key], valueB[key])) {
return false;
}
}
return true;
}
| flutter/packages/flutter/test/services/message_codecs_testing.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/message_codecs_testing.dart",
"repo_id": "flutter",
"token_count": 1063
} | 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 'dart:convert' show jsonDecode;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('TextEditingDeltaInsertion', () {
test('Verify creation of insertion delta when inserting at a collapsed selection.', () {
const String jsonInsertionDelta = '{'
'"oldText": "",'
' "deltaText": "let there be text",'
' "deltaStart": 0,'
' "deltaEnd": 0,'
' "selectionBase": 17,'
' "selectionExtent": 17,'
' "selectionAffinity" : "TextAffinity.downstream" ,'
' "selectionIsDirectional": false,'
' "composingBase": -1,'
' "composingExtent": -1}';
final TextEditingDeltaInsertion delta = TextEditingDelta.fromJSON(jsonDecode(jsonInsertionDelta) as Map<String, dynamic>) as TextEditingDeltaInsertion;
const TextRange expectedComposing = TextRange.empty;
const int expectedInsertionOffset = 0;
const TextSelection expectedSelection = TextSelection.collapsed(offset: 17);
expect(delta.oldText, '');
expect(delta.textInserted, 'let there be text');
expect(delta.insertionOffset, expectedInsertionOffset);
expect(delta.selection, expectedSelection);
expect(delta.composing, expectedComposing);
});
test('Verify creation of insertion delta when inserting at end of composing region.', () {
const String jsonInsertionDelta = '{'
'"oldText": "hello worl",'
' "deltaText": "world",'
' "deltaStart": 6,'
' "deltaEnd": 10,'
' "selectionBase": 11,'
' "selectionExtent": 11,'
' "selectionAffinity" : "TextAffinity.downstream",'
' "selectionIsDirectional": false,'
' "composingBase": 6,'
' "composingExtent": 11}';
final TextEditingDeltaInsertion delta = TextEditingDelta.fromJSON(jsonDecode(jsonInsertionDelta) as Map<String, dynamic>) as TextEditingDeltaInsertion;
const TextRange expectedComposing = TextRange(start: 6, end: 11);
const int expectedInsertionOffset = 10;
const TextSelection expectedSelection = TextSelection.collapsed(offset: 11);
expect(delta.oldText, 'hello worl');
expect(delta.textInserted, 'd');
expect(delta.insertionOffset, expectedInsertionOffset);
expect(delta.selection, expectedSelection);
expect(delta.composing, expectedComposing);
});
test('Verify invalid TextEditingDeltaInsertion fails to apply', () {
const TextEditingDeltaInsertion delta =
TextEditingDeltaInsertion(
oldText: 'hello worl',
textInserted: 'd',
insertionOffset: 11,
selection: TextSelection.collapsed(offset: 11),
composing: TextRange.empty,
);
expect(() { delta.apply(TextEditingValue.empty); }, throwsAssertionError);
});
test('Verify TextEditingDeltaInsertion debugFillProperties', () {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const TextEditingDeltaInsertion insertionDelta = TextEditingDeltaInsertion(
oldText: 'hello worl',
textInserted: 'd',
insertionOffset: 10,
selection: TextSelection.collapsed(offset: 11),
composing: TextRange.empty,
);
insertionDelta.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
expect(
description,
<String>[
'oldText: hello worl',
'textInserted: d',
'insertionOffset: 10',
'selection: TextSelection.collapsed(offset: 11, affinity: TextAffinity.downstream, isDirectional: false)',
'composing: TextRange(start: -1, end: -1)',
],
);
});
});
group('TextEditingDeltaDeletion', () {
test('Verify creation of deletion delta when deleting.', () {
const String jsonDeletionDelta = '{'
'"oldText": "let there be text.",'
' "deltaText": "",'
' "deltaStart": 1,'
' "deltaEnd": 2,'
' "selectionBase": 1,'
' "selectionExtent": 1,'
' "selectionAffinity" : "TextAffinity.downstream" ,'
' "selectionIsDirectional": false,'
' "composingBase": -1,'
' "composingExtent": -1}';
final TextEditingDeltaDeletion delta = TextEditingDelta.fromJSON(jsonDecode(jsonDeletionDelta) as Map<String, dynamic>) as TextEditingDeltaDeletion;
const TextRange expectedComposing = TextRange.empty;
const TextRange expectedDeletedRange = TextRange(start: 1, end: 2);
const TextSelection expectedSelection = TextSelection.collapsed(offset: 1);
expect(delta.oldText, 'let there be text.');
expect(delta.textDeleted, 'e');
expect(delta.deletedRange, expectedDeletedRange);
expect(delta.selection, expectedSelection);
expect(delta.composing, expectedComposing);
});
test('Verify creation of deletion delta when deleting at end of composing region.', () {
const String jsonDeletionDelta = '{'
'"oldText": "hello world",'
' "deltaText": "worl",'
' "deltaStart": 6,'
' "deltaEnd": 11,'
' "selectionBase": 10,'
' "selectionExtent": 10,'
' "selectionAffinity" : "TextAffinity.downstream",'
' "selectionIsDirectional": false,'
' "composingBase": 6,'
' "composingExtent": 10}';
final TextEditingDeltaDeletion delta = TextEditingDelta.fromJSON(jsonDecode(jsonDeletionDelta) as Map<String, dynamic>) as TextEditingDeltaDeletion;
const TextRange expectedComposing = TextRange(start: 6, end: 10);
const TextRange expectedDeletedRange = TextRange(start: 10, end: 11);
const TextSelection expectedSelection = TextSelection.collapsed(offset: 10);
expect(delta.oldText, 'hello world');
expect(delta.textDeleted, 'd');
expect(delta.deletedRange, expectedDeletedRange);
expect(delta.selection, expectedSelection);
expect(delta.composing, expectedComposing);
});
test('Verify invalid TextEditingDeltaDeletion fails to apply', () {
const TextEditingDeltaDeletion delta =
TextEditingDeltaDeletion(
oldText: 'hello world',
deletedRange: TextRange(start: 5, end: 12),
selection: TextSelection.collapsed(offset: 5),
composing: TextRange.empty,
);
expect(() { delta.apply(TextEditingValue.empty); }, throwsAssertionError);
});
test('Verify TextEditingDeltaDeletion debugFillProperties', () {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const TextEditingDeltaDeletion deletionDelta = TextEditingDeltaDeletion(
oldText: 'hello world',
deletedRange: TextRange(start: 6, end: 10),
selection: TextSelection.collapsed(offset: 6),
composing: TextRange.empty,
);
deletionDelta.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
expect(
description,
<String>[
'oldText: hello world',
'textDeleted: worl',
'deletedRange: TextRange(start: 6, end: 10)',
'selection: TextSelection.collapsed(offset: 6, affinity: TextAffinity.downstream, isDirectional: false)',
'composing: TextRange(start: -1, end: -1)',
],
);
});
});
group('TextEditingDeltaReplacement', () {
test('Verify creation of replacement delta when replacing with longer.', () {
const String jsonReplacementDelta = '{'
'"oldText": "hello worfi",'
' "deltaText": "working",'
' "deltaStart": 6,'
' "deltaEnd": 11,'
' "selectionBase": 13,'
' "selectionExtent": 13,'
' "selectionAffinity" : "TextAffinity.downstream",'
' "selectionIsDirectional": false,'
' "composingBase": 6,'
' "composingExtent": 13}';
final TextEditingDeltaReplacement delta = TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) as TextEditingDeltaReplacement;
const TextRange expectedComposing = TextRange(start: 6, end: 13);
const TextRange expectedReplacedRange = TextRange(start: 6, end: 11);
const TextSelection expectedSelection = TextSelection.collapsed(offset: 13);
expect(delta.oldText, 'hello worfi');
expect(delta.textReplaced, 'worfi');
expect(delta.replacementText, 'working');
expect(delta.replacedRange, expectedReplacedRange);
expect(delta.selection, expectedSelection);
expect(delta.composing, expectedComposing);
});
test('Verify creation of replacement delta when replacing with shorter.', () {
const String jsonReplacementDelta = '{'
'"oldText": "hello world",'
' "deltaText": "h",'
' "deltaStart": 6,'
' "deltaEnd": 11,'
' "selectionBase": 7,'
' "selectionExtent": 7,'
' "selectionAffinity" : "TextAffinity.downstream",'
' "selectionIsDirectional": false,'
' "composingBase": 6,'
' "composingExtent": 7}';
final TextEditingDeltaReplacement delta = TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) as TextEditingDeltaReplacement;
const TextRange expectedComposing = TextRange(start: 6, end: 7);
const TextRange expectedReplacedRange = TextRange(start: 6, end: 11);
const TextSelection expectedSelection = TextSelection.collapsed(offset: 7);
expect(delta.oldText, 'hello world');
expect(delta.textReplaced, 'world');
expect(delta.replacementText, 'h');
expect(delta.replacedRange, expectedReplacedRange);
expect(delta.selection, expectedSelection);
expect(delta.composing, expectedComposing);
});
test('Verify creation of replacement delta when replacing with same.', () {
const String jsonReplacementDelta = '{'
'"oldText": "hello world",'
' "deltaText": "words",'
' "deltaStart": 6,'
' "deltaEnd": 11,'
' "selectionBase": 11,'
' "selectionExtent": 11,'
' "selectionAffinity" : "TextAffinity.downstream",'
' "selectionIsDirectional": false,'
' "composingBase": 6,'
' "composingExtent": 11}';
final TextEditingDeltaReplacement delta = TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) as TextEditingDeltaReplacement;
const TextRange expectedComposing = TextRange(start: 6, end: 11);
const TextRange expectedReplacedRange = TextRange(start: 6, end: 11);
const TextSelection expectedSelection = TextSelection.collapsed(offset: 11);
expect(delta.oldText, 'hello world');
expect(delta.textReplaced, 'world');
expect(delta.replacementText, 'words');
expect(delta.replacedRange, expectedReplacedRange);
expect(delta.selection, expectedSelection);
expect(delta.composing, expectedComposing);
});
test('Verify invalid TextEditingDeltaReplacement fails to apply', () {
const TextEditingDeltaReplacement delta =
TextEditingDeltaReplacement(
oldText: 'hello worl',
replacementText: 'world',
replacedRange: TextRange(start: 5, end: 11),
selection: TextSelection.collapsed(offset: 11),
composing: TextRange.empty,
);
expect(() { delta.apply(TextEditingValue.empty); }, throwsAssertionError);
});
test('Verify TextEditingDeltaReplacement debugFillProperties', () {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const TextEditingDeltaReplacement replacementDelta = TextEditingDeltaReplacement(
oldText: 'hello world',
replacementText: 'h',
replacedRange: TextRange(start: 6, end: 11),
selection: TextSelection.collapsed(offset: 7),
composing: TextRange(start: 6, end: 7),
);
replacementDelta.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
expect(
description,
<String>[
'oldText: hello world',
'textReplaced: world',
'replacementText: h',
'replacedRange: TextRange(start: 6, end: 11)',
'selection: TextSelection.collapsed(offset: 7, affinity: TextAffinity.downstream, isDirectional: false)',
'composing: TextRange(start: 6, end: 7)',
],
);
});
});
group('TextEditingDeltaNonTextUpdate', () {
test('Verify non text update delta created.', () {
const String jsonNonTextUpdateDelta = '{'
'"oldText": "hello world",'
' "deltaText": "",'
' "deltaStart": -1,'
' "deltaEnd": -1,'
' "selectionBase": 10,'
' "selectionExtent": 10,'
' "selectionAffinity" : "TextAffinity.downstream",'
' "selectionIsDirectional": false,'
' "composingBase": 6,'
' "composingExtent": 11}';
final TextEditingDeltaNonTextUpdate delta = TextEditingDelta.fromJSON(jsonDecode(jsonNonTextUpdateDelta) as Map<String, dynamic>) as TextEditingDeltaNonTextUpdate;
const TextRange expectedComposing = TextRange(start: 6, end: 11);
const TextSelection expectedSelection = TextSelection.collapsed(offset: 10);
expect(delta.oldText, 'hello world');
expect(delta.selection, expectedSelection);
expect(delta.composing, expectedComposing);
});
test('Verify invalid TextEditingDeltaNonTextUpdate fails to apply', () {
const TextEditingDeltaNonTextUpdate delta =
TextEditingDeltaNonTextUpdate(
oldText: 'hello world',
selection: TextSelection.collapsed(offset: 12),
composing: TextRange.empty,
);
expect(() { delta.apply(TextEditingValue.empty); }, throwsAssertionError);
});
test('Verify TextEditingDeltaNonTextUpdate debugFillProperties', () {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const TextEditingDeltaNonTextUpdate nonTextUpdateDelta = TextEditingDeltaNonTextUpdate(
oldText: 'hello world',
selection: TextSelection.collapsed(offset: 7),
composing: TextRange(start: 6, end: 7),
);
nonTextUpdateDelta.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
expect(
description,
<String>[
'oldText: hello world',
'selection: TextSelection.collapsed(offset: 7, affinity: TextAffinity.downstream, isDirectional: false)',
'composing: TextRange(start: 6, end: 7)',
],
);
});
});
}
| flutter/packages/flutter/test/services/text_editing_delta_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/text_editing_delta_test.dart",
"repo_id": "flutter",
"token_count": 6260
} | 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.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('AnimatedPadding.debugFillProperties', (WidgetTester tester) async {
final AnimatedPadding padding = AnimatedPadding(
padding: const EdgeInsets.all(7.0),
curve: Curves.ease,
duration: const Duration(milliseconds: 200),
);
expect(padding, hasOneLineDescription);
});
testWidgets('AnimatedPadding padding visual-to-directional animation', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedPadding(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.only(right: 50.0),
child: SizedBox.expand(key: target),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(750.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(750.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedPadding(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsetsDirectional.only(start: 100.0),
child: SizedBox.expand(key: target),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(750.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(750.0, 0.0));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byKey(target)), const Size(725.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(725.0, 0.0));
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getSize(find.byKey(target)), const Size(700.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(700.0, 0.0));
});
testWidgets('AnimatedPadding animated padding clamped to positive values', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedPadding(
curve: Curves.easeInOutBack, // will cause negative padding during overshoot
duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.only(right: 50.0),
child: SizedBox.expand(key: target),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(750.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(750.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedPadding(
curve: Curves.easeInOutBack,
duration: const Duration(milliseconds: 200),
padding: EdgeInsets.zero,
child: SizedBox.expand(key: target),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(750.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(750.0, 0.0));
await tester.pump(const Duration(milliseconds: 128));
// Curve would have made the padding negative a this point if it is not clamped.
expect(tester.getSize(find.byKey(target)), const Size(800.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 0.0));
});
}
| flutter/packages/flutter/test/widgets/animated_padding_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/animated_padding_test.dart",
"repo_id": "flutter",
"token_count": 1417
} | 712 |
// 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:ui';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets("Material2 - BackdropFilter's cull rect does not shrink", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Text('0 0 ' * 10000),
Center(
// ClipRect needed for filtering the 200x200 area instead of the
// whole screen.
child: ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
),
child: Container(
alignment: Alignment.center,
width: 200.0,
height: 200.0,
child: const Text('Hello World'),
),
),
),
),
],
),
),
),
);
await expectLater(
find.byType(RepaintBoundary).first,
matchesGoldenFile('m2_backdrop_filter_test.cull_rect.png'),
);
});
testWidgets("Material3 - BackdropFilter's cull rect does not shrink", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Text('0 0 ' * 10000),
Center(
// ClipRect needed for filtering the 200x200 area instead of the
// whole screen.
child: ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
),
child: Container(
alignment: Alignment.center,
width: 200.0,
height: 200.0,
child: const Text('Hello World'),
),
),
),
),
],
),
),
),
);
await expectLater(
find.byType(RepaintBoundary).first,
matchesGoldenFile('m3_backdrop_filter_test.cull_rect.png'),
);
});
testWidgets('Material2 - BackdropFilter blendMode on saveLayer', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Opacity(
opacity: 0.9,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Text('0 0 ' * 10000),
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// ClipRect needed for filtering the 200x200 area instead of the
// whole screen.
children: <Widget>[
ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
),
child: Container(
alignment: Alignment.center,
width: 200.0,
height: 200.0,
color: Colors.yellow.withAlpha(0x7),
),
),
),
ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
),
blendMode: BlendMode.src,
child: Container(
alignment: Alignment.center,
width: 200.0,
height: 200.0,
color: Colors.yellow.withAlpha(0x7),
),
),
),
],
),
],
),
),
),
),
);
await expectLater(
find.byType(RepaintBoundary).first,
matchesGoldenFile('m2_backdrop_filter_test.saveLayer.blendMode.png'),
);
});
testWidgets('Material3 - BackdropFilter blendMode on saveLayer', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: Opacity(
opacity: 0.9,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Text('0 0 ' * 10000),
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// ClipRect needed for filtering the 200x200 area instead of the
// whole screen.
children: <Widget>[
ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
),
child: Container(
alignment: Alignment.center,
width: 200.0,
height: 200.0,
color: Colors.yellow.withAlpha(0x7),
),
),
),
ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
),
blendMode: BlendMode.src,
child: Container(
alignment: Alignment.center,
width: 200.0,
height: 200.0,
color: Colors.yellow.withAlpha(0x7),
),
),
),
],
),
],
),
),
),
),
);
await expectLater(
find.byType(RepaintBoundary).first,
matchesGoldenFile('m3_backdrop_filter_test.saveLayer.blendMode.png'),
);
});
}
| flutter/packages/flutter/test/widgets/backdrop_filter_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/backdrop_filter_test.dart",
"repo_id": "flutter",
"token_count": 4187
} | 713 |
// 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';
import 'test_widgets.dart';
class ProbeWidget extends StatefulWidget {
const ProbeWidget({ super.key });
@override
ProbeWidgetState createState() => ProbeWidgetState();
}
class ProbeWidgetState extends State<ProbeWidget> {
static int buildCount = 0;
@override
void initState() {
super.initState();
setState(() { });
}
@override
void didUpdateWidget(ProbeWidget oldWidget) {
super.didUpdateWidget(oldWidget);
setState(() { });
}
@override
Widget build(BuildContext context) {
setState(() { });
buildCount++;
return Container();
}
}
class BadWidget extends StatelessWidget {
const BadWidget(this.parentState, { super.key });
final BadWidgetParentState parentState;
@override
Widget build(BuildContext context) {
parentState._markNeedsBuild();
return Container();
}
}
class BadWidgetParent extends StatefulWidget {
const BadWidgetParent({ super.key });
@override
BadWidgetParentState createState() => BadWidgetParentState();
}
class BadWidgetParentState extends State<BadWidgetParent> {
void _markNeedsBuild() {
setState(() {
// Our state didn't really change, but we're doing something pathological
// here to trigger an interesting scenario to test.
});
}
@override
Widget build(BuildContext context) {
return BadWidget(this);
}
}
class BadDisposeWidget extends StatefulWidget {
const BadDisposeWidget({ super.key });
@override
BadDisposeWidgetState createState() => BadDisposeWidgetState();
}
class BadDisposeWidgetState extends State<BadDisposeWidget> {
@override
Widget build(BuildContext context) {
return Container();
}
@override
void dispose() {
setState(() { /* This is invalid behavior. */ });
super.dispose();
}
}
class StatefulWrapper extends StatefulWidget {
const StatefulWrapper({
super.key,
required this.child,
});
final Widget child;
@override
StatefulWrapperState createState() => StatefulWrapperState();
}
class StatefulWrapperState extends State<StatefulWrapper> {
void trigger() {
setState(() { built = null; });
}
int? built;
late int oldBuilt;
static int buildId = 0;
@override
Widget build(BuildContext context) {
buildId += 1;
built = buildId;
return widget.child;
}
}
class Wrapper extends StatelessWidget {
const Wrapper({
super.key,
required this.child,
});
final Widget child;
@override
Widget build(BuildContext context) {
return child;
}
}
void main() {
testWidgets('Legal times for setState', (WidgetTester tester) async {
final GlobalKey flipKey = GlobalKey();
expect(ProbeWidgetState.buildCount, equals(0));
await tester.pumpWidget(const ProbeWidget(key: Key('a')));
expect(ProbeWidgetState.buildCount, equals(1));
await tester.pumpWidget(const ProbeWidget(key: Key('b')));
expect(ProbeWidgetState.buildCount, equals(2));
await tester.pumpWidget(FlipWidget(
key: flipKey,
left: Container(),
right: const ProbeWidget(key: Key('c')),
));
expect(ProbeWidgetState.buildCount, equals(2));
final FlipWidgetState flipState1 = flipKey.currentState! as FlipWidgetState;
flipState1.flip();
await tester.pump();
expect(ProbeWidgetState.buildCount, equals(3));
final FlipWidgetState flipState2 = flipKey.currentState! as FlipWidgetState;
flipState2.flip();
await tester.pump();
expect(ProbeWidgetState.buildCount, equals(3));
await tester.pumpWidget(Container());
expect(ProbeWidgetState.buildCount, equals(3));
});
testWidgets('Setting parent state during build is forbidden', (WidgetTester tester) async {
await tester.pumpWidget(const BadWidgetParent());
expect(tester.takeException(), isFlutterError);
await tester.pumpWidget(Container());
});
testWidgets('Setting state during dispose is forbidden', (WidgetTester tester) async {
await tester.pumpWidget(const BadDisposeWidget());
expect(tester.takeException(), isNull);
await tester.pumpWidget(Container());
expect(tester.takeException(), isNotNull);
});
testWidgets('Dirty element list sort order', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: 'key1');
final GlobalKey key2 = GlobalKey(debugLabel: 'key2');
bool didMiddle = false;
late Widget middle;
final List<StateSetter> setStates = <StateSetter>[];
Widget builder(BuildContext context, StateSetter setState) {
setStates.add(setState);
final bool returnMiddle = !didMiddle;
didMiddle = true;
return Wrapper(
child: Wrapper(
child: StatefulWrapper(
child: returnMiddle ? middle : Container(),
),
),
);
}
final Widget part1 = Wrapper(
child: KeyedSubtree(
key: key1,
child: StatefulBuilder(
builder: builder,
),
),
);
final Widget part2 = Wrapper(
child: KeyedSubtree(
key: key2,
child: StatefulBuilder(
builder: builder,
),
),
);
middle = part2;
await tester.pumpWidget(part1);
for (final StatefulWrapperState state in tester.stateList<StatefulWrapperState>(find.byType(StatefulWrapper))) {
expect(state.built, isNotNull);
state.oldBuilt = state.built!;
state.trigger();
}
for (final StateSetter setState in setStates) {
setState(() { });
}
StatefulWrapperState.buildId = 0;
middle = part1;
didMiddle = false;
await tester.pumpWidget(part2);
for (final StatefulWrapperState state in tester.stateList<StatefulWrapperState>(find.byType(StatefulWrapper))) {
expect(state.built, isNotNull);
expect(state.built, isNot(equals(state.oldBuilt)));
}
});
}
| flutter/packages/flutter/test/widgets/build_scope_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/build_scope_test.dart",
"repo_id": "flutter",
"token_count": 2141
} | 714 |
// 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 TestSingleChildLayoutDelegate extends SingleChildLayoutDelegate {
late BoxConstraints constraintsFromGetSize;
BoxConstraints? constraintsFromGetConstraintsForChild;
late Size sizeFromGetPositionForChild;
late Size childSizeFromGetPositionForChild;
@override
Size getSize(BoxConstraints constraints) {
if (!RenderObject.debugCheckingIntrinsics) {
constraintsFromGetSize = constraints;
}
return const Size(200.0, 300.0);
}
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
assert(!RenderObject.debugCheckingIntrinsics);
constraintsFromGetConstraintsForChild = constraints;
return const BoxConstraints(minWidth: 100.0, maxWidth: 150.0, minHeight: 200.0, maxHeight: 400.0);
}
@override
Offset getPositionForChild(Size size, Size childSize) {
assert(!RenderObject.debugCheckingIntrinsics);
sizeFromGetPositionForChild = size;
childSizeFromGetPositionForChild = childSize;
return Offset.zero;
}
bool shouldRelayoutCalled = false;
bool shouldRelayoutValue = false;
@override
bool shouldRelayout(_) {
assert(!RenderObject.debugCheckingIntrinsics);
shouldRelayoutCalled = true;
return shouldRelayoutValue;
}
}
class FixedSizeLayoutDelegate extends SingleChildLayoutDelegate {
FixedSizeLayoutDelegate(this.size);
final Size size;
@override
Size getSize(BoxConstraints constraints) => size;
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
return BoxConstraints.tight(size);
}
@override
bool shouldRelayout(FixedSizeLayoutDelegate oldDelegate) {
return size != oldDelegate.size;
}
}
class NotifierLayoutDelegate extends SingleChildLayoutDelegate {
NotifierLayoutDelegate(this.size) : super(relayout: size);
final ValueNotifier<Size> size;
@override
Size getSize(BoxConstraints constraints) => size.value;
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
return BoxConstraints.tight(size.value);
}
@override
bool shouldRelayout(NotifierLayoutDelegate oldDelegate) {
return size != oldDelegate.size;
}
}
Widget buildFrame(SingleChildLayoutDelegate delegate) {
return Center(
child: CustomSingleChildLayout(
delegate: delegate,
child: Container(),
),
);
}
void main() {
testWidgets('Control test for CustomSingleChildLayout', (WidgetTester tester) async {
final TestSingleChildLayoutDelegate delegate = TestSingleChildLayoutDelegate();
await tester.pumpWidget(buildFrame(delegate));
expect(delegate.constraintsFromGetSize.minWidth, 0.0);
expect(delegate.constraintsFromGetSize.maxWidth, 800.0);
expect(delegate.constraintsFromGetSize.minHeight, 0.0);
expect(delegate.constraintsFromGetSize.maxHeight, 600.0);
expect(delegate.constraintsFromGetConstraintsForChild!.minWidth, 0.0);
expect(delegate.constraintsFromGetConstraintsForChild!.maxWidth, 800.0);
expect(delegate.constraintsFromGetConstraintsForChild!.minHeight, 0.0);
expect(delegate.constraintsFromGetConstraintsForChild!.maxHeight, 600.0);
expect(delegate.sizeFromGetPositionForChild.width, 200.0);
expect(delegate.sizeFromGetPositionForChild.height, 300.0);
expect(delegate.childSizeFromGetPositionForChild.width, 150.0);
expect(delegate.childSizeFromGetPositionForChild.height, 400.0);
});
testWidgets('Test SingleChildDelegate shouldRelayout method', (WidgetTester tester) async {
TestSingleChildLayoutDelegate delegate =
TestSingleChildLayoutDelegate();
await tester.pumpWidget(buildFrame(delegate));
// Layout happened because the delegate was set.
expect(delegate.constraintsFromGetConstraintsForChild, isNotNull); // i.e. layout happened
expect(delegate.shouldRelayoutCalled, isFalse);
// Layout did not happen because shouldRelayout() returned false.
delegate = TestSingleChildLayoutDelegate();
delegate.shouldRelayoutValue = false;
await tester.pumpWidget(buildFrame(delegate));
expect(delegate.shouldRelayoutCalled, isTrue);
expect(delegate.constraintsFromGetConstraintsForChild, isNull);
// Layout happened because shouldRelayout() returned true.
delegate = TestSingleChildLayoutDelegate();
delegate.shouldRelayoutValue = true;
await tester.pumpWidget(buildFrame(delegate));
expect(delegate.shouldRelayoutCalled, isTrue);
expect(delegate.constraintsFromGetConstraintsForChild, isNotNull);
});
testWidgets('Delegate can change size', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(FixedSizeLayoutDelegate(const Size(100.0, 200.0))));
RenderBox box = tester.renderObject(find.byType(CustomSingleChildLayout));
expect(box.size, equals(const Size(100.0, 200.0)));
await tester.pumpWidget(buildFrame(FixedSizeLayoutDelegate(const Size(150.0, 240.0))));
box = tester.renderObject(find.byType(CustomSingleChildLayout));
expect(box.size, equals(const Size(150.0, 240.0)));
});
testWidgets('Can use listener for relayout', (WidgetTester tester) async {
final ValueNotifier<Size> size = ValueNotifier<Size>(const Size(100.0, 200.0));
addTearDown(size.dispose);
await tester.pumpWidget(buildFrame(NotifierLayoutDelegate(size)));
RenderBox box = tester.renderObject(find.byType(CustomSingleChildLayout));
expect(box.size, equals(const Size(100.0, 200.0)));
size.value = const Size(150.0, 240.0);
await tester.pump();
box = tester.renderObject(find.byType(CustomSingleChildLayout));
expect(box.size, equals(const Size(150.0, 240.0)));
});
}
| flutter/packages/flutter/test/widgets/custom_single_child_layout_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/custom_single_child_layout_test.dart",
"repo_id": "flutter",
"token_count": 1943
} | 715 |
// 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';
void main() {
testWidgets('runs animations', (WidgetTester tester) async {
final AnimationController controller = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
addTearDown(controller.dispose);
await tester.pumpWidget(Center(
child: DualTransitionBuilder(
animation: controller,
forwardBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return ScaleTransition(
scale: animation,
child: child,
);
},
reverseBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return FadeTransition(
opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
child: child,
);
},
child: Container(
color: Colors.green,
height: 100,
width: 100,
),
),
));
expect(_getScale(tester), 0.0);
expect(_getOpacity(tester), 1.0);
controller.forward();
await tester.pump();
await tester.pump(const Duration(milliseconds: 150));
expect(_getScale(tester), 0.5);
expect(_getOpacity(tester), 1.0);
await tester.pump(const Duration(milliseconds: 150));
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 1.0);
await tester.pumpAndSettle();
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 1.0);
controller.reverse();
await tester.pump();
await tester.pump(const Duration(milliseconds: 150));
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 0.5);
await tester.pump(const Duration(milliseconds: 150));
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 0.0);
await tester.pumpAndSettle();
expect(_getScale(tester), 0.0);
expect(_getOpacity(tester), 1.0);
});
testWidgets('keeps state', (WidgetTester tester) async {
final AnimationController controller = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: DualTransitionBuilder(
animation: controller,
forwardBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return ScaleTransition(
scale: animation,
child: child,
);
},
reverseBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return FadeTransition(
opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
child: child,
);
},
child: const _StatefulTestWidget(name: 'Foo'),
),
),
));
final State<StatefulWidget> state =
tester.state(find.byType(_StatefulTestWidget));
expect(state, isNotNull);
controller.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
controller.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
});
testWidgets('does not jump when interrupted - forward', (WidgetTester tester) async {
final AnimationController controller = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
addTearDown(controller.dispose);
await tester.pumpWidget(Center(
child: DualTransitionBuilder(
animation: controller,
forwardBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return ScaleTransition(
scale: animation,
child: child,
);
},
reverseBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return FadeTransition(
opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
child: child,
);
},
child: Container(
color: Colors.green,
height: 100,
width: 100,
),
),
));
expect(_getScale(tester), 0.0);
expect(_getOpacity(tester), 1.0);
controller.forward();
await tester.pump();
await tester.pump(const Duration(milliseconds: 150));
expect(_getScale(tester), 0.5);
expect(_getOpacity(tester), 1.0);
controller.reverse();
expect(_getScale(tester), 0.5);
expect(_getOpacity(tester), 1.0);
await tester.pump();
expect(_getScale(tester), 0.5);
expect(_getOpacity(tester), 1.0);
await tester.pump(const Duration(milliseconds: 75));
expect(_getScale(tester), 0.25);
expect(_getOpacity(tester), 1.0);
await tester.pump(const Duration(milliseconds: 75));
expect(_getScale(tester), 0.0);
expect(_getOpacity(tester), 1.0);
await tester.pumpAndSettle();
expect(_getScale(tester), 0.0);
expect(_getOpacity(tester), 1.0);
});
testWidgets('does not jump when interrupted - reverse', (WidgetTester tester) async {
final AnimationController controller = AnimationController(
value: 1.0,
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
addTearDown(controller.dispose);
await tester.pumpWidget(Center(
child: DualTransitionBuilder(
animation: controller,
forwardBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return ScaleTransition(
scale: animation,
child: child,
);
},
reverseBuilder: (
BuildContext context,
Animation<double> animation,
Widget? child,
) {
return FadeTransition(
opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
child: child,
);
},
child: Container(
color: Colors.green,
height: 100,
width: 100,
),
),
));
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 1.0);
controller.reverse();
await tester.pump();
await tester.pump(const Duration(milliseconds: 150));
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 0.5);
controller.forward();
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 0.5);
await tester.pump();
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 0.5);
await tester.pump(const Duration(milliseconds: 75));
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 0.75);
await tester.pump(const Duration(milliseconds: 75));
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 1.0);
await tester.pumpAndSettle();
expect(_getScale(tester), 1.0);
expect(_getOpacity(tester), 1.0);
});
}
double _getScale(WidgetTester tester) {
final ScaleTransition scale = tester.widget(find.byType(ScaleTransition));
return scale.scale.value;
}
double _getOpacity(WidgetTester tester) {
final FadeTransition scale = tester.widget(find.byType(FadeTransition));
return scale.opacity.value;
}
class _StatefulTestWidget extends StatefulWidget {
const _StatefulTestWidget({required this.name});
final String name;
@override
State<_StatefulTestWidget> createState() => _StatefulTestWidgetState();
}
class _StatefulTestWidgetState extends State<_StatefulTestWidget> {
@override
Widget build(BuildContext context) {
return Text(widget.name);
}
}
| flutter/packages/flutter/test/widgets/dual_transition_builder_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/dual_transition_builder_test.dart",
"repo_id": "flutter",
"token_count": 3777
} | 716 |
// 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/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
group(WidgetOrderTraversalPolicy, () {
testWidgets('Find the initial focus if there is none yet.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final GlobalKey key3 = GlobalKey(debugLabel: '3');
final GlobalKey key4 = GlobalKey(debugLabel: '4');
final GlobalKey key5 = GlobalKey(debugLabel: '5');
await tester.pumpWidget(FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
key: key1,
child: Column(
children: <Widget>[
Focus(
key: key2,
child: SizedBox(key: key3, width: 100, height: 100),
),
Focus(
key: key4,
child: SizedBox(key: key5, width: 100, height: 100),
),
],
),
),
));
final Element firstChild = tester.element(find.byKey(key3));
final Element secondChild = tester.element(find.byKey(key5));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode secondFocusNode = Focus.of(secondChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
secondFocusNode.nextFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
});
testWidgets('Find the initial focus if there is none yet and traversing backwards.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final GlobalKey key3 = GlobalKey(debugLabel: '3');
final GlobalKey key4 = GlobalKey(debugLabel: '4');
final GlobalKey key5 = GlobalKey(debugLabel: '5');
await tester.pumpWidget(FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
key: key1,
child: Column(
children: <Widget>[
Focus(
key: key2,
child: SizedBox(key: key3, width: 100, height: 100),
),
Focus(
key: key4,
child: SizedBox(key: key5, width: 100, height: 100),
),
],
),
),
));
final Element firstChild = tester.element(find.byKey(key3));
final Element secondChild = tester.element(find.byKey(key5));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode secondFocusNode = Focus.of(secondChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isFalse);
secondFocusNode.previousFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
});
testWidgets('focus traversal should work case 1', (WidgetTester tester) async {
final FocusNode outer1 = FocusNode(debugLabel: 'outer1', skipTraversal: true);
final FocusNode outer2 = FocusNode(debugLabel: 'outer2', skipTraversal: true);
final FocusNode inner1 = FocusNode(debugLabel: 'inner1', );
final FocusNode inner2 = FocusNode(debugLabel: 'inner2', );
addTearDown(() {
outer1.dispose();
outer2.dispose();
inner1.dispose();
inner2.dispose();
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
child: Row(
children: <Widget>[
FocusScope(
child: Focus(
focusNode: outer1,
child: Focus(
focusNode: inner1,
child: const SizedBox(width: 10, height: 10),
),
),
),
FocusScope(
child: Focus(
focusNode: outer2,
// Add a padding to ensure both Focus widgets have different
// sizes.
child: Padding(
padding: const EdgeInsets.all(5),
child: Focus(
focusNode: inner2,
child: const SizedBox(width: 10, height: 10),
),
),
),
),
],
),
),
),
);
expect(FocusManager.instance.primaryFocus, isNull);
inner1.requestFocus();
await tester.pump();
expect(FocusManager.instance.primaryFocus, inner1);
outer2.nextFocus();
await tester.pump();
expect(FocusManager.instance.primaryFocus, inner2);
});
testWidgets('focus traversal should work case 2', (WidgetTester tester) async {
final FocusNode outer1 = FocusNode(debugLabel: 'outer1', skipTraversal: true);
final FocusNode outer2 = FocusNode(debugLabel: 'outer2', skipTraversal: true);
final FocusNode inner1 = FocusNode(debugLabel: 'inner1', );
final FocusNode inner2 = FocusNode(debugLabel: 'inner2', );
addTearDown(() {
outer1.dispose();
outer2.dispose();
inner1.dispose();
inner2.dispose();
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
child: Row(
children: <Widget>[
FocusScope(
child: Focus(
focusNode: outer1,
child: Focus(
focusNode: inner1,
child: const SizedBox(width: 10, height: 10),
),
),
),
FocusScope(
child: Focus(
focusNode: outer2,
child: Focus(
focusNode: inner2,
child: const SizedBox(width: 10, height: 10),
),
),
),
],
),
),
),
);
expect(FocusManager.instance.primaryFocus, isNull);
inner1.requestFocus();
await tester.pump();
expect(FocusManager.instance.primaryFocus, inner1);
outer2.nextFocus();
await tester.pump();
expect(FocusManager.instance.primaryFocus, inner2);
});
testWidgets('Move focus to next node.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final GlobalKey key3 = GlobalKey(debugLabel: '3');
final GlobalKey key4 = GlobalKey(debugLabel: '4');
final GlobalKey key5 = GlobalKey(debugLabel: '5');
final GlobalKey key6 = GlobalKey(debugLabel: '6');
bool? focus1;
bool? focus2;
bool? focus3;
bool? focus5;
await tester.pumpWidget(
FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'key1',
key: key1,
onFocusChange: (bool focus) => focus1 = focus,
child: Column(
children: <Widget>[
FocusScope(
debugLabel: 'key2',
key: key2,
onFocusChange: (bool focus) => focus2 = focus,
child: Column(
children: <Widget>[
Focus(
debugLabel: 'key3',
key: key3,
onFocusChange: (bool focus) => focus3 = focus,
child: Container(key: key4),
),
Focus(
debugLabel: 'key5',
key: key5,
onFocusChange: (bool focus) => focus5 = focus,
child: Container(key: key6),
),
],
),
),
],
),
),
),
);
final Element firstChild = tester.element(find.byKey(key4));
final Element secondChild = tester.element(find.byKey(key6));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode secondFocusNode = Focus.of(secondChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
firstFocusNode.requestFocus();
await tester.pump();
expect(focus1, isTrue);
expect(focus2, isTrue);
expect(focus3, isTrue);
expect(focus5, isNull);
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
focus1 = null;
focus2 = null;
focus3 = null;
focus5 = null;
Focus.of(firstChild).nextFocus();
await tester.pump();
expect(focus1, isNull);
expect(focus2, isNull);
expect(focus3, isFalse);
expect(focus5, isTrue);
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
focus1 = null;
focus2 = null;
focus3 = null;
focus5 = null;
Focus.of(firstChild).nextFocus();
await tester.pump();
expect(focus1, isNull);
expect(focus2, isNull);
expect(focus3, isTrue);
expect(focus5, isFalse);
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
focus1 = null;
focus2 = null;
focus3 = null;
focus5 = null;
// Tests that can still move back to original node.
Focus.of(firstChild).previousFocus();
await tester.pump();
expect(focus1, isNull);
expect(focus2, isNull);
expect(focus3, isFalse);
expect(focus5, isTrue);
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
});
testWidgets('Move focus to previous node.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final GlobalKey key3 = GlobalKey(debugLabel: '3');
final GlobalKey key4 = GlobalKey(debugLabel: '4');
final GlobalKey key5 = GlobalKey(debugLabel: '5');
final GlobalKey key6 = GlobalKey(debugLabel: '6');
await tester.pumpWidget(
FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
key: key1,
child: Column(
children: <Widget>[
FocusScope(
key: key2,
child: Column(
children: <Widget>[
Focus(
key: key3,
child: Container(key: key4),
),
Focus(
key: key5,
child: Container(key: key6),
),
],
),
),
],
),
),
),
);
final Element firstChild = tester.element(find.byKey(key4));
final Element secondChild = tester.element(find.byKey(key6));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode secondFocusNode = Focus.of(secondChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
secondFocusNode.requestFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
Focus.of(firstChild).previousFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
Focus.of(firstChild).previousFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
// Tests that can still move back to original node.
Focus.of(firstChild).nextFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
});
testWidgets('Move focus to next/previous node while skipping nodes in policy', (WidgetTester tester) async {
final List<FocusNode> nodes =
List<FocusNode>.generate(7, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
await tester.pumpWidget(
FocusTraversalGroup(
policy: SkipAllButFirstAndLastPolicy(),
child: Column(
children: List<Widget>.generate(
nodes.length,
(int index) => Focus(
focusNode: nodes[index],
child: const SizedBox(),
),
),
),
),
);
nodes[2].requestFocus();
await tester.pump();
expect(nodes[2].hasPrimaryFocus, isTrue);
primaryFocus!.nextFocus();
await tester.pump();
expect(nodes[6].hasPrimaryFocus, isTrue);
primaryFocus!.previousFocus();
await tester.pump();
expect(nodes[0].hasPrimaryFocus, isTrue);
});
testWidgets('Find the initial focus when a route is pushed or popped.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final FocusNode testNode1 = FocusNode(debugLabel: 'First Focus Node');
addTearDown(testNode1.dispose);
final FocusNode testNode2 = FocusNode(debugLabel: 'Second Focus Node');
addTearDown(testNode2.dispose);
await tester.pumpWidget(
MaterialApp(
home: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: Center(
child: Builder(builder: (BuildContext context) {
return ElevatedButton(
key: key1,
focusNode: testNode1,
autofocus: true,
onPressed: () {
Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return Center(
child: ElevatedButton(
key: key2,
focusNode: testNode2,
autofocus: true,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Go Back'),
),
);
},
),
);
},
child: const Text('Go Forward'),
);
}),
),
),
),
);
final Element firstChild = tester.element(find.text('Go Forward'));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
await tester.pump();
expect(firstFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
await tester.tap(find.text('Go Forward'));
await tester.pumpAndSettle();
final Element secondChild = tester.element(find.text('Go Back'));
final FocusNode secondFocusNode = Focus.of(secondChild);
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
await tester.tap(find.text('Go Back'));
await tester.pumpAndSettle();
expect(firstFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
});
testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final FocusNode testNode1 = FocusNode(debugLabel: 'Focus Node');
addTearDown(testNode1.dispose);
bool calledCallback = false;
await tester.pumpWidget(
FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(
requestFocusCallback: (FocusNode node, {double? alignment,
ScrollPositionAlignmentPolicy? alignmentPolicy,
Curve? curve,
Duration? duration}) {
calledCallback = true;
},
),
child: FocusScope(
debugLabel: 'key1',
child: Focus(
key: key1,
focusNode: testNode1,
child: Container(),
),
),
),
);
final Element element = tester.element(find.byKey(key1));
final FocusNode scope = FocusScope.of(element);
scope.nextFocus();
await tester.pump();
expect(calledCallback, isTrue);
calledCallback = false;
scope.previousFocus();
await tester.pump();
expect(calledCallback, isTrue);
});
});
testWidgets('Nested navigator does not trap focus', (WidgetTester tester) async {
final FocusNode node1 = FocusNode();
addTearDown(node1.dispose);
final FocusNode node2 = FocusNode();
addTearDown(node2.dispose);
final FocusNode node3 = FocusNode();
addTearDown(node3.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: FocusScope(
child: Column(
children: <Widget>[
Focus(
focusNode: node1,
child: const SizedBox(width: 100, height: 100),
),
SizedBox(
width: 100,
height: 100,
child: Navigator(
pages: <Page<void>>[
MaterialPage<void>(
child: Focus(
focusNode: node2,
child: const SizedBox(width: 100, height: 100),
),
),
],
onPopPage: (_, __) => false,
),
),
Focus(
focusNode: node3,
child: const SizedBox(width: 100, height: 100),
),
],
),
),
),
),
);
node1.requestFocus();
await tester.pump();
expect(node1.hasFocus, isTrue);
expect(node2.hasFocus, isFalse);
expect(node3.hasFocus, isFalse);
node1.nextFocus();
await tester.pump();
expect(node1.hasFocus, isFalse);
expect(node2.hasFocus, isTrue);
expect(node3.hasFocus, isFalse);
node2.nextFocus();
await tester.pump();
expect(node1.hasFocus, isFalse);
expect(node2.hasFocus, isFalse);
expect(node3.hasFocus, isTrue);
node3.nextFocus();
await tester.pump();
expect(node1.hasFocus, isTrue);
expect(node2.hasFocus, isFalse);
expect(node3.hasFocus, isFalse);
node1.previousFocus();
await tester.pump();
expect(node1.hasFocus, isFalse);
expect(node2.hasFocus, isFalse);
expect(node3.hasFocus, isTrue);
node3.previousFocus();
await tester.pump();
expect(node1.hasFocus, isFalse);
expect(node2.hasFocus, isTrue);
expect(node3.hasFocus, isFalse);
node2.previousFocus();
await tester.pump();
expect(node1.hasFocus, isTrue);
expect(node2.hasFocus, isFalse);
expect(node3.hasFocus, isFalse);
});
group(ReadingOrderTraversalPolicy, () {
testWidgets('Find the initial focus if there is none yet.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final GlobalKey key3 = GlobalKey(debugLabel: '3');
final GlobalKey key4 = GlobalKey(debugLabel: '4');
final GlobalKey key5 = GlobalKey(debugLabel: '5');
await tester.pumpWidget(FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: FocusScope(
key: key1,
child: Column(
children: <Widget>[
Focus(
key: key2,
child: SizedBox(key: key3, width: 100, height: 100),
),
Focus(
key: key4,
child: SizedBox(key: key5, width: 100, height: 100),
),
],
),
),
));
final Element firstChild = tester.element(find.byKey(key3));
final Element secondChild = tester.element(find.byKey(key5));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode secondFocusNode = Focus.of(secondChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
secondFocusNode.nextFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
});
testWidgets('Move reading focus to next node.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final GlobalKey key3 = GlobalKey(debugLabel: '3');
final GlobalKey key4 = GlobalKey(debugLabel: '4');
final GlobalKey key5 = GlobalKey(debugLabel: '5');
final GlobalKey key6 = GlobalKey(debugLabel: '6');
bool? focus1;
bool? focus2;
bool? focus3;
bool? focus5;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'key1',
key: key1,
onFocusChange: (bool focus) => focus1 = focus,
child: Column(
children: <Widget>[
FocusScope(
debugLabel: 'key2',
key: key2,
onFocusChange: (bool focus) => focus2 = focus,
child: Row(
children: <Widget>[
Focus(
debugLabel: 'key3',
key: key3,
onFocusChange: (bool focus) => focus3 = focus,
child: Container(key: key4),
),
Focus(
debugLabel: 'key5',
key: key5,
onFocusChange: (bool focus) => focus5 = focus,
child: Container(key: key6),
),
],
),
),
],
),
),
),
),
);
void clear() {
focus1 = null;
focus2 = null;
focus3 = null;
focus5 = null;
}
final Element firstChild = tester.element(find.byKey(key4));
final Element secondChild = tester.element(find.byKey(key6));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode secondFocusNode = Focus.of(secondChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
firstFocusNode.requestFocus();
await tester.pump();
expect(focus1, isTrue);
expect(focus2, isTrue);
expect(focus3, isTrue);
expect(focus5, isNull);
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
clear();
Focus.of(firstChild).nextFocus();
await tester.pump();
expect(focus1, isNull);
expect(focus2, isNull);
expect(focus3, isFalse);
expect(focus5, isTrue);
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
clear();
Focus.of(firstChild).nextFocus();
await tester.pump();
expect(focus1, isNull);
expect(focus2, isNull);
expect(focus3, isTrue);
expect(focus5, isFalse);
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
clear();
// Tests that can still move back to original node.
Focus.of(firstChild).previousFocus();
await tester.pump();
expect(focus1, isNull);
expect(focus2, isNull);
expect(focus3, isFalse);
expect(focus5, isTrue);
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
});
testWidgets('Requesting nextFocus on node focuses its descendant', (WidgetTester tester) async {
for (final bool canRequestFocus in <bool>{true, false}) {
final FocusNode node1 = FocusNode();
final FocusNode node2 = FocusNode();
addTearDown(() {
node1.dispose();
node2.dispose();
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: FocusScope(
child: Focus(
focusNode: node1,
canRequestFocus: canRequestFocus,
child: Focus(
focusNode: node2,
child: Container(),
),
),
),
),
),
);
final bool didFindNode = node1.nextFocus();
await tester.pump();
expect(didFindNode, isTrue);
if (canRequestFocus) {
expect(node1.hasPrimaryFocus, isTrue);
expect(node2.hasPrimaryFocus, isFalse);
} else {
expect(node1.hasPrimaryFocus, isFalse);
expect(node2.hasPrimaryFocus, isTrue);
}
}
});
testWidgets('Move reading focus to previous node.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final GlobalKey key3 = GlobalKey(debugLabel: '3');
final GlobalKey key4 = GlobalKey(debugLabel: '4');
final GlobalKey key5 = GlobalKey(debugLabel: '5');
final GlobalKey key6 = GlobalKey(debugLabel: '6');
await tester.pumpWidget(
FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: FocusScope(
key: key1,
child: Column(
children: <Widget>[
FocusScope(
key: key2,
child: Column(
children: <Widget>[
Focus(
key: key3,
child: Container(key: key4),
),
Focus(
key: key5,
child: Container(key: key6),
),
],
),
),
],
),
),
),
);
final Element firstChild = tester.element(find.byKey(key4));
final Element secondChild = tester.element(find.byKey(key6));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode secondFocusNode = Focus.of(secondChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
secondFocusNode.requestFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
Focus.of(firstChild).previousFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
Focus.of(firstChild).previousFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
// Tests that can still move back to original node.
Focus.of(firstChild).nextFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isTrue);
expect(secondFocusNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
});
testWidgets('Focus order is correct in the presence of different directionalities.', (WidgetTester tester) async {
const int nodeCount = 10;
final FocusScopeNode scopeNode = FocusScopeNode();
addTearDown(scopeNode.dispose);
final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
Widget buildTest(TextDirection topDirection) {
return Directionality(
textDirection: topDirection,
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: FocusScope(
node: scopeNode,
child: Column(
children: <Widget>[
Directionality(
textDirection: TextDirection.ltr,
child: Row(children: <Widget>[
Focus(
focusNode: nodes[0],
child: const SizedBox(width: 10, height: 10),
),
Focus(
focusNode: nodes[1],
child: const SizedBox(width: 10, height: 10),
),
Focus(
focusNode: nodes[2],
child: const SizedBox(width: 10, height: 10),
),
]),
),
Directionality(
textDirection: TextDirection.ltr,
child: Row(children: <Widget>[
Directionality(
textDirection: TextDirection.rtl,
child: Focus(
focusNode: nodes[3],
child: const SizedBox(width: 10, height: 10),
),
),
Directionality(
textDirection: TextDirection.rtl,
child: Focus(
focusNode: nodes[4],
child: const SizedBox(width: 10, height: 10),
),
),
Directionality(
textDirection: TextDirection.ltr,
child: Focus(
focusNode: nodes[5],
child: const SizedBox(width: 10, height: 10),
),
),
]),
),
Row(children: <Widget>[
Directionality(
textDirection: TextDirection.ltr,
child: Focus(
focusNode: nodes[6],
child: const SizedBox(width: 10, height: 10),
),
),
Directionality(
textDirection: TextDirection.rtl,
child: Focus(
focusNode: nodes[7],
child: const SizedBox(width: 10, height: 10),
),
),
Directionality(
textDirection: TextDirection.rtl,
child: Focus(
focusNode: nodes[8],
child: const SizedBox(width: 10, height: 10),
),
),
Directionality(
textDirection: TextDirection.ltr,
child: Focus(
focusNode: nodes[9],
child: const SizedBox(width: 10, height: 10),
),
),
]),
],
),
),
),
);
}
await tester.pumpWidget(buildTest(TextDirection.rtl));
// The last four *are* correct: the Row is sensitive to the directionality
// too, so it swaps the positions of 7 and 8.
final List<int> order = <int>[];
for (int i = 0; i < nodeCount; ++i) {
nodes.first.nextFocus();
await tester.pump();
order.add(nodes.indexOf(primaryFocus!));
}
expect(order, orderedEquals(<int>[0, 1, 2, 4, 3, 5, 6, 7, 8, 9]));
await tester.pumpWidget(buildTest(TextDirection.ltr));
order.clear();
for (int i = 0; i < nodeCount; ++i) {
nodes.first.nextFocus();
await tester.pump();
order.add(nodes.indexOf(primaryFocus!));
}
expect(order, orderedEquals(<int>[0, 1, 2, 4, 3, 5, 6, 8, 7, 9]));
});
testWidgets('Focus order is reading order regardless of widget order, even when overlapping.', (WidgetTester tester) async {
const int nodeCount = 10;
final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: Stack(
alignment: Alignment.topLeft,
children: List<Widget>.generate(nodeCount, (int index) {
// Boxes that all have the same upper left origin corner.
return Focus(
focusNode: nodes[index],
child: SizedBox(width: 10.0 * (index + 1), height: 10.0 * (index + 1)),
);
}),
),
),
),
);
final List<int> order = <int>[];
for (int i = 0; i < nodeCount; ++i) {
nodes.first.nextFocus();
await tester.pump();
order.add(nodes.indexOf(primaryFocus!));
}
expect(order, orderedEquals(<int>[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]));
// Concentric boxes.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: Stack(
alignment: Alignment.center,
children: List<Widget>.generate(nodeCount, (int index) {
return Focus(
focusNode: nodes[index],
child: SizedBox(width: 10.0 * (index + 1), height: 10.0 * (index + 1)),
);
}),
),
),
),
);
order.clear();
for (int i = 0; i < nodeCount; ++i) {
nodes.first.nextFocus();
await tester.pump();
order.add(nodes.indexOf(primaryFocus!));
}
expect(order, orderedEquals(<int>[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]));
// Stacked (vertically) and centered (horizontally, on each other)
// widgets, not overlapping.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: Stack(
alignment: Alignment.center,
children: List<Widget>.generate(nodeCount, (int index) {
return Positioned(
top: 5.0 * index * (index + 1),
left: 5.0 * (9 - index),
child: Focus(
focusNode: nodes[index],
child: Container(
decoration: BoxDecoration(border: Border.all()),
width: 10.0 * (index + 1),
height: 10.0 * (index + 1),
),
),
);
}),
),
),
),
);
order.clear();
for (int i = 0; i < nodeCount; ++i) {
nodes.first.nextFocus();
await tester.pump();
order.add(nodes.indexOf(primaryFocus!));
}
expect(order, orderedEquals(<int>[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]));
});
testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final FocusNode testNode1 = FocusNode(debugLabel: 'Focus Node');
addTearDown(testNode1.dispose);
bool calledCallback = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(
requestFocusCallback: (FocusNode node, {double? alignment,
ScrollPositionAlignmentPolicy? alignmentPolicy,
Curve? curve,
Duration? duration}) {
calledCallback = true;
},
),
child: FocusScope(
debugLabel: 'key1',
child: Focus(
key: key1,
focusNode: testNode1,
child: Container(),
),
),
),
),
);
final Element element = tester.element(find.byKey(key1));
final FocusNode scope = FocusScope.of(element);
scope.nextFocus();
await tester.pump();
expect(calledCallback, isTrue);
calledCallback = false;
scope.previousFocus();
await tester.pump();
expect(calledCallback, isTrue);
});
});
group(OrderedTraversalPolicy, () {
testWidgets('Find the initial focus if there is none yet.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
await tester.pumpWidget(FocusTraversalGroup(
policy: OrderedTraversalPolicy(secondary: ReadingOrderTraversalPolicy()),
child: FocusScope(
child: Column(
children: <Widget>[
FocusTraversalOrder(
order: const NumericFocusOrder(2),
child: Focus(
child: SizedBox(key: key1, width: 100, height: 100),
),
),
FocusTraversalOrder(
order: const NumericFocusOrder(1),
child: Focus(
child: SizedBox(key: key2, width: 100, height: 100),
),
),
],
),
),
));
final Element firstChild = tester.element(find.byKey(key1));
final Element secondChild = tester.element(find.byKey(key2));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode secondFocusNode = Focus.of(secondChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
secondFocusNode.nextFocus();
await tester.pump();
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
});
testWidgets('Fall back to the secondary sort if no FocusTraversalOrder exists.', (WidgetTester tester) async {
const int nodeCount = 10;
final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()),
child: FocusScope(
child: Row(
children: List<Widget>.generate(
nodeCount,
(int index) => Focus(
focusNode: nodes[index],
child: const SizedBox(width: 10, height: 10),
),
),
),
),
),
),
);
// Because it should be using widget order, this shouldn't be affected by
// the directionality.
for (int i = 0; i < nodeCount; ++i) {
nodes.first.nextFocus();
await tester.pump();
expect(nodes[i].hasPrimaryFocus, isTrue, reason: "node $i doesn't have focus, but should");
}
// Now check backwards.
for (int i = nodeCount - 1; i > 0; --i) {
nodes.first.previousFocus();
await tester.pump();
expect(nodes[i - 1].hasPrimaryFocus, isTrue, reason: "node ${i - 1} doesn't have focus, but should");
}
});
testWidgets('Move focus to next/previous node using numerical order.', (WidgetTester tester) async {
const int nodeCount = 10;
final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()),
child: FocusScope(
child: Row(
children: List<Widget>.generate(
nodeCount,
(int index) => FocusTraversalOrder(
order: NumericFocusOrder(nodeCount - index.toDouble()),
child: Focus(
focusNode: nodes[index],
child: const SizedBox(width: 10, height: 10),
),
),
),
),
),
),
),
);
// The orders are assigned to be backwards from normal, so should go backwards.
for (int i = nodeCount - 1; i >= 0; --i) {
nodes.first.nextFocus();
await tester.pump();
expect(nodes[i].hasPrimaryFocus, isTrue, reason: "node $i doesn't have focus, but should");
}
// Now check backwards.
for (int i = 1; i < nodeCount; ++i) {
nodes.first.previousFocus();
await tester.pump();
expect(nodes[i].hasPrimaryFocus, isTrue, reason: "node $i doesn't have focus, but should");
}
});
testWidgets('Move focus to next/previous node using lexical order.', (WidgetTester tester) async {
const int nodeCount = 10;
/// Generate ['J' ... 'A'];
final List<String> keys = List<String>.generate(nodeCount, (int index) => String.fromCharCode('A'.codeUnits[0] + nodeCount - index - 1));
final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node ${keys[index]}'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()),
child: FocusScope(
child: Row(
children: List<Widget>.generate(
nodeCount,
(int index) => FocusTraversalOrder(
order: LexicalFocusOrder(keys[index]),
child: Focus(
focusNode: nodes[index],
child: const SizedBox(width: 10, height: 10),
),
),
),
),
),
),
),
);
// The orders are assigned to be backwards from normal, so should go backwards.
for (int i = nodeCount - 1; i >= 0; --i) {
nodes.first.nextFocus();
await tester.pump();
expect(nodes[i].hasPrimaryFocus, isTrue, reason: "node $i doesn't have focus, but should");
}
// Now check backwards.
for (int i = 1; i < nodeCount; ++i) {
nodes.first.previousFocus();
await tester.pump();
expect(nodes[i].hasPrimaryFocus, isTrue, reason: "node $i doesn't have focus, but should");
}
});
testWidgets('Focus order is correct in the presence of FocusTraversalPolicyGroups.', (WidgetTester tester) async {
const int nodeCount = 10;
final FocusScopeNode scopeNode = FocusScopeNode();
addTearDown(scopeNode.dispose);
final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
node: scopeNode,
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()),
child: Row(
children: <Widget>[
FocusTraversalOrder(
order: const NumericFocusOrder(0),
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: Row(children: <Widget>[
FocusTraversalOrder(
order: const NumericFocusOrder(9),
child: Focus(
focusNode: nodes[9],
child: const SizedBox(width: 10, height: 10),
),
),
FocusTraversalOrder(
order: const NumericFocusOrder(8),
child: Focus(
focusNode: nodes[8],
child: const SizedBox(width: 10, height: 10),
),
),
FocusTraversalOrder(
order: const NumericFocusOrder(7),
child: Focus(
focusNode: nodes[7],
child: const SizedBox(width: 10, height: 10),
),
),
]),
),
),
FocusTraversalOrder(
order: const NumericFocusOrder(1),
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()),
child: Row(children: <Widget>[
FocusTraversalOrder(
order: const NumericFocusOrder(4),
child: Focus(
focusNode: nodes[4],
child: const SizedBox(width: 10, height: 10),
),
),
FocusTraversalOrder(
order: const NumericFocusOrder(5),
child: Focus(
focusNode: nodes[5],
child: const SizedBox(width: 10, height: 10),
),
),
FocusTraversalOrder(
order: const NumericFocusOrder(6),
child: Focus(
focusNode: nodes[6],
child: const SizedBox(width: 10, height: 10),
),
),
]),
),
),
FocusTraversalOrder(
order: const NumericFocusOrder(2),
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()),
child: Row(children: <Widget>[
FocusTraversalOrder(
order: const LexicalFocusOrder('D'),
child: Focus(
focusNode: nodes[3],
child: const SizedBox(width: 10, height: 10),
),
),
FocusTraversalOrder(
order: const LexicalFocusOrder('C'),
child: Focus(
focusNode: nodes[2],
child: const SizedBox(width: 10, height: 10),
),
),
FocusTraversalOrder(
order: const LexicalFocusOrder('B'),
child: Focus(
focusNode: nodes[1],
child: const SizedBox(width: 10, height: 10),
),
),
FocusTraversalOrder(
order: const LexicalFocusOrder('A'),
child: Focus(
focusNode: nodes[0],
child: const SizedBox(width: 10, height: 10),
),
),
]),
),
),
],
),
),
),
),
),
);
final List<int> expectedOrder = <int>[9, 8, 7, 4, 5, 6, 0, 1, 2, 3];
final List<int> order = <int>[];
for (int i = 0; i < nodeCount; ++i) {
nodes.first.nextFocus();
await tester.pump();
order.add(nodes.indexOf(primaryFocus!));
}
expect(order, orderedEquals(expectedOrder));
});
testWidgets('Find the initial focus when a route is pushed or popped.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final FocusNode testNode1 = FocusNode(debugLabel: 'First Focus Node');
addTearDown(testNode1.dispose);
final FocusNode testNode2 = FocusNode(debugLabel: 'Second Focus Node');
addTearDown(testNode2.dispose);
await tester.pumpWidget(
MaterialApp(
home: FocusTraversalGroup(
policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()),
child: Center(
child: Builder(builder: (BuildContext context) {
return FocusTraversalOrder(
order: const NumericFocusOrder(0),
child: ElevatedButton(
key: key1,
focusNode: testNode1,
autofocus: true,
onPressed: () {
Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return Center(
child: FocusTraversalOrder(
order: const NumericFocusOrder(0),
child: ElevatedButton(
key: key2,
focusNode: testNode2,
autofocus: true,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Go Back'),
),
),
);
},
),
);
},
child: const Text('Go Forward'),
),
);
}),
),
),
),
);
final Element firstChild = tester.element(find.text('Go Forward'));
final FocusNode firstFocusNode = Focus.of(firstChild);
final FocusNode scope = Focus.of(firstChild).enclosingScope!;
await tester.pump();
expect(firstFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
await tester.tap(find.text('Go Forward'));
await tester.pumpAndSettle();
final Element secondChild = tester.element(find.text('Go Back'));
final FocusNode secondFocusNode = Focus.of(secondChild);
expect(firstFocusNode.hasFocus, isFalse);
expect(secondFocusNode.hasFocus, isTrue);
await tester.tap(find.text('Go Back'));
await tester.pumpAndSettle();
expect(firstFocusNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
});
testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final FocusNode testNode1 = FocusNode(debugLabel: 'Focus Node');
addTearDown(testNode1.dispose);
bool calledCallback = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(
requestFocusCallback: (FocusNode node, {double? alignment,
ScrollPositionAlignmentPolicy? alignmentPolicy,
Curve? curve,
Duration? duration}) {
calledCallback = true;
},
),
child: FocusScope(
debugLabel: 'key1',
child: Focus(
key: key1,
focusNode: testNode1,
child: Container(),
),
),
),
),
);
final Element element = tester.element(find.byKey(key1));
final FocusNode scope = FocusScope.of(element);
scope.nextFocus();
await tester.pump();
expect(calledCallback, isTrue);
calledCallback = false;
scope.previousFocus();
await tester.pump();
expect(calledCallback, isTrue);
});
});
group(DirectionalFocusTraversalPolicyMixin, () {
testWidgets('Move focus in all directions.', (WidgetTester tester) async {
final GlobalKey upperLeftKey = GlobalKey(debugLabel: 'upperLeftKey');
final GlobalKey upperRightKey = GlobalKey(debugLabel: 'upperRightKey');
final GlobalKey lowerLeftKey = GlobalKey(debugLabel: 'lowerLeftKey');
final GlobalKey lowerRightKey = GlobalKey(debugLabel: 'lowerRightKey');
bool? focusUpperLeft;
bool? focusUpperRight;
bool? focusLowerLeft;
bool? focusLowerRight;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'Scope',
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Focus(
debugLabel: 'upperLeft',
onFocusChange: (bool focus) => focusUpperLeft = focus,
child: SizedBox(width: 100, height: 100, key: upperLeftKey),
),
Focus(
debugLabel: 'upperRight',
onFocusChange: (bool focus) => focusUpperRight = focus,
child: SizedBox(width: 100, height: 100, key: upperRightKey),
),
],
),
Row(
children: <Widget>[
Focus(
debugLabel: 'lowerLeft',
onFocusChange: (bool focus) => focusLowerLeft = focus,
child: SizedBox(width: 100, height: 100, key: lowerLeftKey),
),
Focus(
debugLabel: 'lowerRight',
onFocusChange: (bool focus) => focusLowerRight = focus,
child: SizedBox(width: 100, height: 100, key: lowerRightKey),
),
],
),
],
),
),
),
),
);
void clear() {
focusUpperLeft = null;
focusUpperRight = null;
focusLowerLeft = null;
focusLowerRight = null;
}
final FocusNode upperLeftNode = Focus.of(tester.element(find.byKey(upperLeftKey)));
final FocusNode upperRightNode = Focus.of(tester.element(find.byKey(upperRightKey)));
final FocusNode lowerLeftNode = Focus.of(tester.element(find.byKey(lowerLeftKey)));
final FocusNode lowerRightNode = Focus.of(tester.element(find.byKey(lowerRightKey)));
final FocusNode scope = upperLeftNode.enclosingScope!;
upperLeftNode.requestFocus();
await tester.pump();
expect(focusUpperLeft, isTrue);
expect(focusUpperRight, isNull);
expect(focusLowerLeft, isNull);
expect(focusLowerRight, isNull);
expect(upperLeftNode.hasFocus, isTrue);
expect(upperRightNode.hasFocus, isFalse);
expect(lowerLeftNode.hasFocus, isFalse);
expect(lowerRightNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
clear();
expect(scope.focusInDirection(TraversalDirection.right), isTrue);
await tester.pump();
expect(focusUpperLeft, isFalse);
expect(focusUpperRight, isTrue);
expect(focusLowerLeft, isNull);
expect(focusLowerRight, isNull);
expect(upperLeftNode.hasFocus, isFalse);
expect(upperRightNode.hasFocus, isTrue);
expect(lowerLeftNode.hasFocus, isFalse);
expect(lowerRightNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focusUpperLeft, isNull);
expect(focusUpperRight, isFalse);
expect(focusLowerLeft, isNull);
expect(focusLowerRight, isTrue);
expect(upperLeftNode.hasFocus, isFalse);
expect(upperRightNode.hasFocus, isFalse);
expect(lowerLeftNode.hasFocus, isFalse);
expect(lowerRightNode.hasFocus, isTrue);
expect(scope.hasFocus, isTrue);
clear();
expect(scope.focusInDirection(TraversalDirection.left), isTrue);
await tester.pump();
expect(focusUpperLeft, isNull);
expect(focusUpperRight, isNull);
expect(focusLowerLeft, isTrue);
expect(focusLowerRight, isFalse);
expect(upperLeftNode.hasFocus, isFalse);
expect(upperRightNode.hasFocus, isFalse);
expect(lowerLeftNode.hasFocus, isTrue);
expect(lowerRightNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
clear();
expect(scope.focusInDirection(TraversalDirection.up), isTrue);
await tester.pump();
expect(focusUpperLeft, isTrue);
expect(focusUpperRight, isNull);
expect(focusLowerLeft, isFalse);
expect(focusLowerRight, isNull);
expect(upperLeftNode.hasFocus, isTrue);
expect(upperRightNode.hasFocus, isFalse);
expect(lowerLeftNode.hasFocus, isFalse);
expect(lowerRightNode.hasFocus, isFalse);
expect(scope.hasFocus, isTrue);
});
testWidgets('Directional focus avoids hysteresis.', (WidgetTester tester) async {
List<bool?> focus = List<bool?>.generate(6, (int _) => null);
final List<FocusNode> nodes = List<FocusNode>.generate(6, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
Focus makeFocus(int index) {
return Focus(
debugLabel: '[$index]',
focusNode: nodes[index],
onFocusChange: (bool isFocused) => focus[index] = isFocused,
child: const SizedBox(width: 100, height: 100),
);
}
/// Layout is:
/// [0]
/// [1] [2]
/// [3] [4] [5]
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'Scope',
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
makeFocus(0),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
makeFocus(1),
makeFocus(2),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
makeFocus(3),
makeFocus(4),
makeFocus(5),
],
),
],
),
),
),
),
);
void clear() {
focus = List<bool?>.generate(focus.length, (int _) => null);
}
final FocusNode scope = nodes[0].enclosingScope!;
nodes[4].requestFocus();
// Test to make sure that the same path is followed backwards and forwards.
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null, true, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.up), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, true, null, false, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.up), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[true, null, false, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[false, null, true, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, false, null, true, null]));
clear();
// Make sure that moving in a different axis clears the history.
expect(scope.focusInDirection(TraversalDirection.left), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, true, false, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.up), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, true, null, false, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.up), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[true, false, null, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[false, true, null, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, false, null, true, null, null]));
clear();
});
testWidgets('Directional prefers the closest node even on irregular grids', (WidgetTester tester) async {
const int cols = 3;
const int rows = 3;
List<bool?> focus = List<bool?>.generate(rows * cols, (int _) => null);
final List<FocusNode> nodes = List<FocusNode>.generate(rows * cols, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
Widget makeFocus(int row, int col) {
final int index = row * rows + col;
return Focus(
focusNode: nodes[index],
onFocusChange: (bool isFocused) => focus[index] = isFocused,
child: Container(
// Make some of the items a different size to test the code that
// checks for the closest node.
width: index == 3 ? 150 : 100,
height: index == 1 ? 150 : 100,
color: Colors.primaries[index],
child: Text('[$row, $col]'),
),
);
}
/// Layout is:
/// [0, 1]
/// [0, 0] [ ] [0, 2]
/// [ 1, 0 ] [1, 1] [1, 2]
/// [2, 0] [2, 1] [2, 2]
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'Scope',
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
makeFocus(0, 0),
makeFocus(0, 1),
makeFocus(0, 2),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
makeFocus(1, 0),
makeFocus(1, 1),
makeFocus(1, 2),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
makeFocus(2, 0),
makeFocus(2, 1),
makeFocus(2, 2),
],
),
],
),
),
),
),
);
void clear() {
focus = List<bool?>.generate(focus.length, (int _) => null);
}
final FocusNode scope = nodes[0].enclosingScope!;
// Go down the center column and make sure that the focus stays in that
// column, even though the second row is irregular.
nodes[1].requestFocus();
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, true, null, null, null, null, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, false, null, null, true, null, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null, false, null, null, true, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isFalse);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null, null, null, null, null, null]));
clear();
// Go back up the right column and make sure that the focus stays in that
// column, even though the second row is irregular.
expect(scope.focusInDirection(TraversalDirection.right), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null, null, null, null, false, true]));
clear();
expect(scope.focusInDirection(TraversalDirection.up), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null, null, true, null, null, false]));
clear();
expect(scope.focusInDirection(TraversalDirection.up), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, true, null, null, false, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.up), isFalse);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null, null, null, null, null, null]));
clear();
// Go left on the top row and make sure that the focus stays in that
// row, even though the second column is irregular.
expect(scope.focusInDirection(TraversalDirection.left), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, true, false, null, null, null, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.left), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[true, false, null, null, null, null, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.left), isFalse);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null, null, null, null, null, null]));
clear();
});
testWidgets('Closest vertical is picked when only out of band items are considered', (WidgetTester tester) async {
const int rows = 4;
List<bool?> focus = List<bool?>.generate(rows, (int _) => null);
final List<FocusNode> nodes = List<FocusNode>.generate(rows, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
Widget makeFocus(int row) {
return Padding(
padding: EdgeInsetsDirectional.only(end: row != 0 ? 110.0 : 0),
child: Focus(
focusNode: nodes[row],
onFocusChange: (bool isFocused) => focus[row] = isFocused,
child: Container(
width: row == 1 ? 150 : 100,
height: 100,
color: Colors.primaries[row],
child: Text('[$row]'),
),
),
);
}
/// Layout is:
/// [0]
/// [ 1]
/// [ 2]
/// [ 3]
///
/// The important feature is that nothing is in the vertical band defined
/// by widget [0]. We want it to traverse to 1, 2, 3 in order, even though
/// the center of [2] is horizontally closer to the vertical axis of [0]'s
/// center than [1]'s.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'Scope',
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
makeFocus(0),
makeFocus(1),
makeFocus(2),
makeFocus(3),
],
),
),
),
),
);
void clear() {
focus = List<bool?>.generate(focus.length, (int _) => null);
}
final FocusNode scope = nodes[0].enclosingScope!;
// Go down the column and make sure that the focus goes to the next
// closest one.
nodes[0].requestFocus();
await tester.pump();
expect(focus, orderedEquals(<bool?>[true, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[false, true, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, false, true, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, false, true]));
clear();
expect(scope.focusInDirection(TraversalDirection.down), isFalse);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null]));
clear();
});
testWidgets('Closest horizontal is picked when only out of band items are considered', (WidgetTester tester) async {
const int cols = 4;
List<bool?> focus = List<bool?>.generate(cols, (int _) => null);
final List<FocusNode> nodes = List<FocusNode>.generate(cols, (int index) => FocusNode(debugLabel: 'Node $index'));
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
Widget makeFocus(int col) {
return Padding(
padding: EdgeInsetsDirectional.only(top: col != 0 ? 110.0 : 0),
child: Focus(
focusNode: nodes[col],
onFocusChange: (bool isFocused) => focus[col] = isFocused,
child: Container(
width: 100,
height: col == 1 ? 150 : 100,
color: Colors.primaries[col],
child: Text('[$col]'),
),
),
);
}
/// Layout is:
/// [0]
/// [ ][2][3]
/// [1]
/// ([ ] is part of [1], [1] is just taller than [2] and [3]).
///
/// The important feature is that nothing is in the horizontal band
/// defined by widget [0]. We want it to traverse to 1, 2, 3 in order,
/// even though the center of [2] is vertically closer to the horizontal
/// axis of [0]'s center than [1]'s.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'Scope',
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
makeFocus(0),
makeFocus(1),
makeFocus(2),
makeFocus(3),
],
),
),
),
),
);
void clear() {
focus = List<bool?>.generate(focus.length, (int _) => null);
}
final FocusNode scope = nodes[0].enclosingScope!;
// Go down the row and make sure that the focus goes to the next
// closest one.
nodes[0].requestFocus();
await tester.pump();
expect(focus, orderedEquals(<bool?>[true, null, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.right), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[false, true, null, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.right), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, false, true, null]));
clear();
expect(scope.focusInDirection(TraversalDirection.right), isTrue);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, false, true]));
clear();
expect(scope.focusInDirection(TraversalDirection.right), isFalse);
await tester.pump();
expect(focus, orderedEquals(<bool?>[null, null, null, null]));
clear();
});
testWidgets('Can find first focus in all directions.', (WidgetTester tester) async {
final GlobalKey upperLeftKey = GlobalKey(debugLabel: 'upperLeftKey');
final GlobalKey upperRightKey = GlobalKey(debugLabel: 'upperRightKey');
final GlobalKey lowerLeftKey = GlobalKey(debugLabel: 'lowerLeftKey');
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'scope',
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Focus(
debugLabel: 'upperLeft',
child: SizedBox(width: 100, height: 100, key: upperLeftKey),
),
Focus(
debugLabel: 'upperRight',
child: SizedBox(width: 100, height: 100, key: upperRightKey),
),
],
),
Row(
children: <Widget>[
Focus(
debugLabel: 'lowerLeft',
child: SizedBox(width: 100, height: 100, key: lowerLeftKey),
),
const Focus(
debugLabel: 'lowerRight',
child: SizedBox(width: 100, height: 100),
),
],
),
],
),
),
),
),
);
final FocusNode upperLeftNode = Focus.of(tester.element(find.byKey(upperLeftKey)));
final FocusNode upperRightNode = Focus.of(tester.element(find.byKey(upperRightKey)));
final FocusNode lowerLeftNode = Focus.of(tester.element(find.byKey(lowerLeftKey)));
final FocusNode scope = upperLeftNode.enclosingScope!;
await tester.pump();
final FocusTraversalPolicy policy = FocusTraversalGroup.of(upperLeftKey.currentContext!);
expect(policy.findFirstFocusInDirection(scope, TraversalDirection.up), equals(lowerLeftNode));
expect(policy.findFirstFocusInDirection(scope, TraversalDirection.down), equals(upperLeftNode));
expect(policy.findFirstFocusInDirection(scope, TraversalDirection.left), equals(upperRightNode));
expect(policy.findFirstFocusInDirection(scope, TraversalDirection.right), equals(upperLeftNode));
});
testWidgets('Can find focus when policy data dirty', (WidgetTester tester) async {
final FocusNode focusTop = FocusNode(debugLabel: 'top');
addTearDown(focusTop.dispose);
final FocusNode focusCenter = FocusNode(debugLabel: 'center');
addTearDown(focusCenter.dispose);
final FocusNode focusBottom = FocusNode(debugLabel: 'bottom');
addTearDown(focusBottom.dispose);
final FocusTraversalPolicy policy = ReadingOrderTraversalPolicy();
await tester.pumpWidget(FocusTraversalGroup(
policy: policy,
child: FocusScope(
debugLabel: 'Scope',
child: Column(
children: <Widget>[
Focus(focusNode: focusTop, child: const SizedBox(width: 100, height: 100)),
Focus(focusNode: focusCenter, child: const SizedBox(width: 100, height: 100)),
Focus(focusNode: focusBottom, child: const SizedBox(width: 100, height: 100)),
],
),
),
));
focusTop.requestFocus();
final FocusNode scope = focusTop.enclosingScope!;
scope.focusInDirection(TraversalDirection.down);
scope.focusInDirection(TraversalDirection.down);
await tester.pump();
expect(focusBottom.hasFocus, isTrue);
// Remove center focus node.
await tester.pumpWidget(FocusTraversalGroup(
policy: policy,
child: FocusScope(
debugLabel: 'Scope',
child: Column(
children: <Widget>[
Focus(focusNode: focusTop, child: const SizedBox(width: 100, height: 100)),
Focus(focusNode: focusBottom, child: const SizedBox(width: 100, height: 100)),
],
),
),
));
expect(focusBottom.hasFocus, isTrue);
scope.focusInDirection(TraversalDirection.up);
await tester.pump();
expect(focusCenter.hasFocus, isFalse);
expect(focusTop.hasFocus, isTrue);
});
testWidgets('Focus traversal actions are invoked when shortcuts are used.', (WidgetTester tester) async {
final GlobalKey upperLeftKey = GlobalKey(debugLabel: 'upperLeftKey');
final GlobalKey upperRightKey = GlobalKey(debugLabel: 'upperRightKey');
final GlobalKey lowerLeftKey = GlobalKey(debugLabel: 'lowerLeftKey');
final GlobalKey lowerRightKey = GlobalKey(debugLabel: 'lowerRightKey');
await tester.pumpWidget(
WidgetsApp(
color: const Color(0xFFFFFFFF),
onGenerateRoute: (RouteSettings settings) {
return TestRoute(
child: Directionality(
textDirection: TextDirection.ltr,
child: FocusScope(
debugLabel: 'scope',
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Focus(
autofocus: true,
debugLabel: 'upperLeft',
child: SizedBox(width: 100, height: 100, key: upperLeftKey),
),
Focus(
debugLabel: 'upperRight',
child: SizedBox(width: 100, height: 100, key: upperRightKey),
),
],
),
Row(
children: <Widget>[
Focus(
debugLabel: 'lowerLeft',
child: SizedBox(width: 100, height: 100, key: lowerLeftKey),
),
Focus(
debugLabel: 'lowerRight',
child: SizedBox(width: 100, height: 100, key: lowerRightKey),
),
],
),
],
),
),
),
);
},
),
);
expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue);
// Traverse in a direction
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue);
}, skip: isBrowser, variant: KeySimulatorTransitModeVariant.all()); // https://github.com/flutter/flutter/issues/35347
testWidgets('Focus traversal actions works when current focus skip traversal', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: 'key1');
final GlobalKey key2 = GlobalKey(debugLabel: 'key2');
final GlobalKey key3 = GlobalKey(debugLabel: 'key3');
await tester.pumpWidget(
WidgetsApp(
color: const Color(0xFFFFFFFF),
onGenerateRoute: (RouteSettings settings) {
return TestRoute(
child: Directionality(
textDirection: TextDirection.ltr,
child: FocusScope(
debugLabel: 'scope',
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Focus(
autofocus: true,
skipTraversal: true,
debugLabel: '1',
child: SizedBox(width: 100, height: 100, key: key1),
),
Focus(
debugLabel: '2',
child: SizedBox(width: 100, height: 100, key: key2),
),
Focus(
debugLabel: '3',
child: SizedBox(width: 100, height: 100, key: key3),
),
],
),
],
),
),
),
);
},
),
);
expect(Focus.of(key1.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
expect(Focus.of(key2.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
expect(Focus.of(key3.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
// Skips key 1 because it skips traversal.
expect(Focus.of(key2.currentContext!).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
expect(Focus.of(key3.currentContext!).hasPrimaryFocus, isTrue);
}, skip: isBrowser, variant: KeySimulatorTransitModeVariant.all()); // https://github.com/flutter/flutter/issues/35347
testWidgets('Focus traversal inside a vertical scrollable scrolls to stay visible.', (WidgetTester tester) async {
final List<int> items = List<int>.generate(11, (int index) => index).toList();
final List<FocusNode> nodes = List<FocusNode>.generate(11, (int index) => FocusNode(debugLabel: 'Item ${index + 1}')).toList();
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
final FocusNode topNode = FocusNode(debugLabel: 'Header');
addTearDown(topNode.dispose);
final FocusNode bottomNode = FocusNode(debugLabel: 'Footer');
addTearDown(bottomNode.dispose);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Column(
children: <Widget>[
Focus(focusNode: topNode, child: Container(height: 100)),
Expanded(
child: ListView(
controller: controller,
children: items.map<Widget>((int item) {
return Focus(
focusNode: nodes[item],
child: Container(height: 100),
);
}).toList(),
),
),
Focus(focusNode: bottomNode, child: Container(height: 100)),
],
),
),
);
// Start at the top
expect(controller.offset, equals(0.0));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(topNode.hasPrimaryFocus, isTrue);
expect(controller.offset, equals(0.0));
// Enter the list.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(nodes[0].hasPrimaryFocus, isTrue);
expect(controller.offset, equals(0.0));
// Go down until we hit the bottom of the visible area.
for (int i = 1; i <= 4; ++i) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(controller.offset, equals(0.0), reason: 'Focusing item $i caused a scroll');
}
// Now keep going down, and the scrollable should scroll automatically.
for (int i = 5; i <= 10; ++i) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
final double expectedOffset = 100.0 * (i - 5) + 200.0;
expect(controller.offset, equals(expectedOffset), reason: "Focusing item $i didn't cause a scroll to $expectedOffset");
}
// Now go one more, and see that the footer gets focused.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(bottomNode.hasPrimaryFocus, isTrue);
expect(controller.offset, equals(100.0 * (10 - 5) + 200.0));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(nodes[10].hasPrimaryFocus, isTrue);
expect(controller.offset, equals(100.0 * (10 - 5) + 200.0));
// Now reverse directions and go back to the top.
// These should not cause a scroll.
final double lowestOffset = controller.offset;
for (int i = 10; i >= 8; --i) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(controller.offset, equals(lowestOffset), reason: 'Focusing item $i caused a scroll');
}
// These should all cause a scroll.
for (int i = 7; i >= 1; --i) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
final double expectedOffset = 100.0 * (i - 1);
expect(controller.offset, equals(expectedOffset), reason: "Focusing item $i didn't cause a scroll");
}
// Back at the top.
expect(nodes[0].hasPrimaryFocus, isTrue);
expect(controller.offset, equals(0.0));
// Now we jump to the header.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(topNode.hasPrimaryFocus, isTrue);
expect(controller.offset, equals(0.0));
}, skip: isBrowser, variant: KeySimulatorTransitModeVariant.all()); // https://github.com/flutter/flutter/issues/35347
testWidgets('Focus traversal inside a horizontal scrollable scrolls to stay visible.', (WidgetTester tester) async {
final List<int> items = List<int>.generate(11, (int index) => index).toList();
final List<FocusNode> nodes = List<FocusNode>.generate(11, (int index) => FocusNode(debugLabel: 'Item ${index + 1}')).toList();
addTearDown(() {
for (final FocusNode node in nodes) {
node.dispose();
}
});
final FocusNode leftNode = FocusNode(debugLabel: 'Left Side');
addTearDown(leftNode.dispose);
final FocusNode rightNode = FocusNode(debugLabel: 'Right Side');
addTearDown(rightNode.dispose);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Row(
children: <Widget>[
Focus(focusNode: leftNode, child: Container(width: 100)),
Expanded(
child: ListView(
scrollDirection: Axis.horizontal,
controller: controller,
children: items.map<Widget>((int item) {
return Focus(
focusNode: nodes[item],
child: Container(width: 100),
);
}).toList(),
),
),
Focus(focusNode: rightNode, child: Container(width: 100)),
],
),
),
);
// Start at the right
expect(controller.offset, equals(0.0));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
expect(leftNode.hasPrimaryFocus, isTrue);
expect(controller.offset, equals(0.0));
// Enter the list.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
expect(nodes[0].hasPrimaryFocus, isTrue);
expect(controller.offset, equals(0.0));
// Go right until we hit the right of the visible area.
for (int i = 1; i <= 6; ++i) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
expect(controller.offset, equals(0.0), reason: 'Focusing item $i caused a scroll');
}
// Now keep going right, and the scrollable should scroll automatically.
for (int i = 7; i <= 10; ++i) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
final double expectedOffset = 100.0 * (i - 5);
expect(controller.offset, equals(expectedOffset), reason: "Focusing item $i didn't cause a scroll to $expectedOffset");
}
// Now go one more, and see that the right edge gets focused.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
expect(rightNode.hasPrimaryFocus, isTrue);
expect(controller.offset, equals(100.0 * 5));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pump();
expect(nodes[10].hasPrimaryFocus, isTrue);
expect(controller.offset, equals(100.0 * 5));
// Now reverse directions and go back to the left.
// These should not cause a scroll.
final double lowestOffset = controller.offset;
for (int i = 10; i >= 7; --i) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pump();
expect(controller.offset, equals(lowestOffset), reason: 'Focusing item $i caused a scroll');
}
// These should all cause a scroll.
for (int i = 6; i >= 1; --i) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pump();
final double expectedOffset = 100.0 * (i - 1);
expect(controller.offset, equals(expectedOffset), reason: "Focusing item $i didn't cause a scroll");
}
// Back at the left side of the scrollable.
expect(nodes[0].hasPrimaryFocus, isTrue);
expect(controller.offset, equals(0.0));
// Now we jump to the left edge of the app.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pump();
expect(leftNode.hasPrimaryFocus, isTrue);
expect(controller.offset, equals(0.0));
}, skip: isBrowser, variant: KeySimulatorTransitModeVariant.all()); // https://github.com/flutter/flutter/issues/35347
testWidgets('Arrow focus traversal actions can be re-enabled for text fields.', (WidgetTester tester) async {
final GlobalKey upperLeftKey = GlobalKey(debugLabel: 'upperLeftKey');
final GlobalKey upperRightKey = GlobalKey(debugLabel: 'upperRightKey');
final GlobalKey lowerLeftKey = GlobalKey(debugLabel: 'lowerLeftKey');
final GlobalKey lowerRightKey = GlobalKey(debugLabel: 'lowerRightKey');
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 FocusNode focusNodeUpperLeft = FocusNode(debugLabel: 'upperLeft');
addTearDown(focusNodeUpperLeft.dispose);
final FocusNode focusNodeUpperRight = FocusNode(debugLabel: 'upperRight');
addTearDown(focusNodeUpperRight.dispose);
final FocusNode focusNodeLowerLeft = FocusNode(debugLabel: 'lowerLeft');
addTearDown(focusNodeLowerLeft.dispose);
final FocusNode focusNodeLowerRight = FocusNode(debugLabel: 'lowerRight');
addTearDown(focusNodeLowerRight.dispose);
Widget generatetestWidgets(bool ignoreTextFields) {
final Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{
const SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left, ignoreTextFields: ignoreTextFields),
const SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right, ignoreTextFields: ignoreTextFields),
const SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down, ignoreTextFields: ignoreTextFields),
const SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up, ignoreTextFields: ignoreTextFields),
};
return MaterialApp(
home: Shortcuts(
shortcuts: shortcuts,
child: FocusScope(
debugLabel: 'scope',
child: Column(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(
width: 100,
height: 100,
child: EditableText(
autofocus: true,
key: upperLeftKey,
controller: controller1,
focusNode: focusNodeUpperLeft,
cursorColor: const Color(0xffffffff),
backgroundCursorColor: const Color(0xff808080),
style: const TextStyle(),
),
),
SizedBox(
width: 100,
height: 100,
child: EditableText(
key: upperRightKey,
controller: controller2,
focusNode: focusNodeUpperRight,
cursorColor: const Color(0xffffffff),
backgroundCursorColor: const Color(0xff808080),
style: const TextStyle(),
),
),
],
),
Row(
children: <Widget>[
SizedBox(
width: 100,
height: 100,
child: EditableText(
key: lowerLeftKey,
controller: controller3,
focusNode: focusNodeLowerLeft,
cursorColor: const Color(0xffffffff),
backgroundCursorColor: const Color(0xff808080),
style: const TextStyle(),
),
),
SizedBox(
width: 100,
height: 100,
child: EditableText(
key: lowerRightKey,
controller: controller4,
focusNode: focusNodeLowerRight,
cursorColor: const Color(0xffffffff),
backgroundCursorColor: const Color(0xff808080),
style: const TextStyle(),
),
),
],
),
],
),
),
),
);
}
await tester.pumpWidget(generatetestWidgets(false));
expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
expect(focusNodeUpperRight.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusNodeLowerRight.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
expect(focusNodeLowerLeft.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue);
await tester.pumpWidget(generatetestWidgets(true));
expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
expect(focusNodeUpperRight.hasPrimaryFocus, isFalse);
expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusNodeLowerRight.hasPrimaryFocus, isFalse);
expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
expect(focusNodeLowerLeft.hasPrimaryFocus, isFalse);
expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Focus traversal does not break when no focusable is available on a MaterialApp', (WidgetTester tester) async {
final List<Object> events = <Object>[];
await tester.pumpWidget(MaterialApp(home: Container()));
HardwareKeyboard.instance.addHandler((KeyEvent event) {
events.add(event);
return true;
});
await tester.idle();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.idle();
expect(events.length, 2);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Focus traversal does not throw when no focusable is available in a group', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Scaffold(body: ListTile(title: Text('title')))));
final FocusNode? initialFocus = primaryFocus;
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(primaryFocus, equals(initialFocus));
});
testWidgets('Focus traversal does not break when no focusable is available on a WidgetsApp', (WidgetTester tester) async {
final List<KeyEvent> events = <KeyEvent>[];
await tester.pumpWidget(
WidgetsApp(
color: Colors.white,
onGenerateRoute: (RouteSettings settings) => PageRouteBuilder<void>(
settings: settings,
pageBuilder: (BuildContext context, Animation<double> animation1, Animation<double> animation2) {
return const Placeholder();
},
),
),
);
HardwareKeyboard.instance.addHandler((KeyEvent event) {
events.add(event);
return true;
});
await tester.idle();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.idle();
expect(events.length, 2);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Custom requestFocusCallback gets called on focusInDirection up/down/left/right.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final FocusNode testNode1 = FocusNode(debugLabel: 'Focus Node');
addTearDown(testNode1.dispose);
bool calledCallback = false;
await tester.pumpWidget(
FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(
requestFocusCallback: (FocusNode node, {double? alignment,
ScrollPositionAlignmentPolicy? alignmentPolicy,
Curve? curve,
Duration? duration}) {
calledCallback = true;
},
),
child: FocusScope(
debugLabel: 'key1',
child: Focus(
key: key1,
focusNode: testNode1,
child: Container(),
),
),
),
);
final Element element = tester.element(find.byKey(key1));
final FocusNode scope = FocusScope.of(element);
scope.focusInDirection(TraversalDirection.up);
await tester.pump();
expect(calledCallback, isTrue);
calledCallback = false;
scope.focusInDirection(TraversalDirection.down);
await tester.pump();
expect(calledCallback, isTrue);
calledCallback = false;
scope.focusInDirection(TraversalDirection.left);
await tester.pump();
expect(calledCallback, isTrue);
scope.focusInDirection(TraversalDirection.right);
await tester.pump();
expect(calledCallback, isTrue);
});
});
group(FocusTraversalGroup, () {
testWidgets("Focus traversal group doesn't introduce a Semantics node", (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(FocusTraversalGroup(child: Container()));
final TestSemantics expectedSemantics = TestSemantics.root();
expect(semantics, hasSemantics(expectedSemantics));
semantics.dispose();
});
testWidgets("Descendants of FocusTraversalGroup aren't focusable if descendantsAreFocusable is false.", (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
bool? gotFocus;
await tester.pumpWidget(
FocusTraversalGroup(
descendantsAreFocusable: false,
child: Focus(
onFocusChange: (bool focused) => gotFocus = focused,
child: Focus(
key: key1,
focusNode: focusNode,
child: Container(key: key2),
),
),
),
);
final Element childWidget = tester.element(find.byKey(key1));
final FocusNode unfocusableNode = Focus.of(childWidget);
final Element containerWidget = tester.element(find.byKey(key2));
final FocusNode containerNode = Focus.of(containerWidget);
unfocusableNode.requestFocus();
await tester.pump();
expect(gotFocus, isNull);
expect(containerNode.hasFocus, isFalse);
expect(unfocusableNode.hasFocus, isFalse);
containerNode.requestFocus();
await tester.pump();
expect(gotFocus, isNull);
expect(containerNode.hasFocus, isFalse);
expect(unfocusableNode.hasFocus, isFalse);
});
testWidgets('Group applies correct policy if focus tree is different from widget tree.', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final GlobalKey key3 = GlobalKey(debugLabel: '3');
final GlobalKey key4 = GlobalKey(debugLabel: '4');
final FocusNode focusNode = FocusNode(debugLabel: 'child');
addTearDown(focusNode.dispose);
final FocusNode parentFocusNode = FocusNode(debugLabel: 'parent');
addTearDown(parentFocusNode.dispose);
await tester.pumpWidget(
Column(
children: <Widget>[
FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: Focus(
child: Focus.withExternalFocusNode(
key: key1,
// This makes focusNode be a child of parentFocusNode instead
// of the surrounding Focus.
parentNode: parentFocusNode,
focusNode: focusNode,
child: Container(key: key2),
),
),
),
FocusTraversalGroup(
policy: SkipAllButFirstAndLastPolicy(),
child: FocusScope(
child: Focus.withExternalFocusNode(
key: key3,
focusNode: parentFocusNode,
child: Container(key: key4),
),
),
),
],
),
);
expect(focusNode.parent, equals(parentFocusNode));
expect(FocusTraversalGroup.maybeOf(key2.currentContext!), const TypeMatcher<SkipAllButFirstAndLastPolicy>());
expect(FocusTraversalGroup.of(key2.currentContext!), const TypeMatcher<SkipAllButFirstAndLastPolicy>());
});
testWidgets("Descendants of FocusTraversalGroup aren't traversable if descendantsAreTraversable is false.", (WidgetTester tester) async {
final FocusNode node1 = FocusNode();
addTearDown(node1.dispose);
final FocusNode node2 = FocusNode();
addTearDown(node2.dispose);
await tester.pumpWidget(
FocusTraversalGroup(
descendantsAreTraversable: false,
child: Column(
children: <Widget>[
Focus(
focusNode: node1,
child: Container(),
),
Focus(
focusNode: node2,
child: Container(),
),
],
),
),
);
node1.requestFocus();
await tester.pump();
expect(node1.hasPrimaryFocus, isTrue);
expect(node2.hasPrimaryFocus, isFalse);
expect(primaryFocus!.nextFocus(), isFalse);
await tester.pump();
expect(node1.hasPrimaryFocus, isTrue);
expect(node2.hasPrimaryFocus, isFalse);
});
testWidgets("FocusTraversalGroup with skipTraversal for all descendants set to true doesn't cause an exception.", (WidgetTester tester) async {
final FocusNode node1 = FocusNode();
addTearDown(node1.dispose);
final FocusNode node2 = FocusNode();
addTearDown(node2.dispose);
await tester.pumpWidget(
FocusTraversalGroup(
child: Column(
children: <Widget>[
Focus(
skipTraversal: true,
focusNode: node1,
child: Container(),
),
Focus(
skipTraversal: true,
focusNode: node2,
child: Container(),
),
],
),
),
);
node1.requestFocus();
await tester.pump();
expect(node1.hasPrimaryFocus, isTrue);
expect(node2.hasPrimaryFocus, isFalse);
expect(primaryFocus!.nextFocus(), isFalse);
await tester.pump();
expect(node1.hasPrimaryFocus, isTrue);
expect(node2.hasPrimaryFocus, isFalse);
});
testWidgets("Nested FocusTraversalGroup with unfocusable children doesn't assert.", (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey(debugLabel: '1');
final GlobalKey key2 = GlobalKey(debugLabel: '2');
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
bool? gotFocus;
await tester.pumpWidget(
FocusTraversalGroup(
child: Column(
children: <Widget>[
Focus(
autofocus: true,
child: Container(),
),
FocusTraversalGroup(
descendantsAreFocusable: false,
child: Focus(
onFocusChange: (bool focused) => gotFocus = focused,
child: Focus(
key: key1,
focusNode: focusNode,
child: Container(key: key2),
),
),
),
],
),
),
);
final Element childWidget = tester.element(find.byKey(key1));
final FocusNode unfocusableNode = Focus.of(childWidget);
final Element containerWidget = tester.element(find.byKey(key2));
final FocusNode containerNode = Focus.of(containerWidget);
await tester.pump();
primaryFocus!.nextFocus();
expect(gotFocus, isNull);
expect(containerNode.hasFocus, isFalse);
expect(unfocusableNode.hasFocus, isFalse);
containerNode.requestFocus();
await tester.pump();
expect(gotFocus, isNull);
expect(containerNode.hasFocus, isFalse);
expect(unfocusableNode.hasFocus, isFalse);
});
testWidgets("Empty FocusTraversalGroup doesn't cause an exception.", (WidgetTester tester) async {
final GlobalKey key = GlobalKey(debugLabel: 'Test Key');
final FocusNode focusNode = FocusNode(debugLabel: 'Test Node');
addTearDown(focusNode.dispose);
await tester.pumpWidget(
FocusTraversalGroup(
child: Directionality(
textDirection: TextDirection.rtl,
child: Column(
children: <Widget>[
FocusTraversalGroup(
child: Container(key: key),
),
Focus(
focusNode: focusNode,
autofocus: true,
child: Container(),
),
],
),
),
),
);
await tester.pump();
primaryFocus!.nextFocus();
await tester.pump();
expect(primaryFocus, equals(focusNode));
});
});
group(RawKeyboardListener, () {
testWidgets('Raw keyboard listener introduces a Semantics node by default', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
RawKeyboardListener(
focusNode: focusNode,
child: Container(),
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
flags: <SemanticsFlag>[
SemanticsFlag.isFocusable,
],
),
],
);
expect(semantics, hasSemantics(
expectedSemantics,
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
));
semantics.dispose();
});
testWidgets("Raw keyboard listener doesn't introduce a Semantics node when specified", (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
RawKeyboardListener(
focusNode: focusNode,
includeSemantics: false,
child: Container(),
),
);
final TestSemantics expectedSemantics = TestSemantics.root();
expect(semantics, hasSemantics(expectedSemantics));
semantics.dispose();
});
});
group(ExcludeFocusTraversal, () {
testWidgets("Descendants aren't traversable", (WidgetTester tester) async {
final FocusNode node1 = FocusNode(debugLabel: 'node 1');
addTearDown(node1.dispose);
final FocusNode node2 = FocusNode(debugLabel: 'node 2');
addTearDown(node2.dispose);
final FocusNode node3 = FocusNode(debugLabel: 'node 3');
addTearDown(node3.dispose);
final FocusNode node4 = FocusNode(debugLabel: 'node 4');
addTearDown(node4.dispose);
await tester.pumpWidget(
FocusTraversalGroup(
child: Column(
children: <Widget>[
Focus(
autofocus: true,
focusNode: node1,
child: Container(),
),
ExcludeFocusTraversal(
child: Focus(
focusNode: node2,
child: Focus(
focusNode: node3,
child: Container(),
),
),
),
Focus(
focusNode: node4,
child: Container(),
),
],
),
),
);
await tester.pump();
expect(node1.hasPrimaryFocus, isTrue);
expect(node2.hasPrimaryFocus, isFalse);
expect(node3.hasPrimaryFocus, isFalse);
expect(node4.hasPrimaryFocus, isFalse);
node1.nextFocus();
await tester.pump();
expect(node1.hasPrimaryFocus, isFalse);
expect(node2.hasPrimaryFocus, isFalse);
expect(node3.hasPrimaryFocus, isFalse);
expect(node4.hasPrimaryFocus, isTrue);
});
testWidgets("Doesn't introduce a Semantics node", (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(ExcludeFocusTraversal(child: Container()));
final TestSemantics expectedSemantics = TestSemantics.root();
expect(semantics, hasSemantics(expectedSemantics));
semantics.dispose();
});
});
// Tests that Flutter allows the focus to escape the app. This is the default
// behavior on the web, since on the web the app is always embedded into some
// surrounding UI. There's at least the browser UI for the address bar and
// tabs. If Flutter Web is embedded into a custom element, there could be
// other focusable HTML elements surrounding Flutter.
//
// See also: https://github.com/flutter/flutter/issues/114463
testWidgets('Default route edge traversal behavior', (WidgetTester tester) async {
final FocusNode nodeA = FocusNode();
addTearDown(nodeA.dispose);
final FocusNode nodeB = FocusNode();
addTearDown(nodeB.dispose);
Future<bool> nextFocus() async {
final bool result = Actions.invoke(
primaryFocus!.context!,
const NextFocusIntent(),
)! as bool;
await tester.pump();
return result;
}
Future<bool> previousFocus() async {
final bool result = Actions.invoke(
primaryFocus!.context!,
const PreviousFocusIntent(),
)! as bool;
await tester.pump();
return result;
}
await tester.pumpWidget(
MaterialApp(
home: Column(
children: <Widget>[
TextButton(
focusNode: nodeA,
child: const Text('A'),
onPressed: () {},
),
TextButton(
focusNode: nodeB,
child: const Text('B'),
onPressed: () {},
),
],
),
),
);
nodeA.requestFocus();
await tester.pump();
expect(nodeA.hasFocus, true);
expect(nodeB.hasFocus, false);
// A -> B
expect(await nextFocus(), isTrue);
expect(nodeA.hasFocus, false);
expect(nodeB.hasFocus, true);
// A <- B
expect(await previousFocus(), isTrue);
expect(nodeA.hasFocus, true);
expect(nodeB.hasFocus, false);
// A -> B
expect(await nextFocus(), isTrue);
expect(nodeA.hasFocus, false);
expect(nodeB.hasFocus, true);
// B ->
// * on mobile: cycle back to A
// * on web: let the focus escape the app
expect(await nextFocus(), !kIsWeb);
expect(nodeA.hasFocus, !kIsWeb);
expect(nodeB.hasFocus, false);
// Start with A again, but wrap around in the opposite direction
nodeA.requestFocus();
await tester.pump();
expect(await previousFocus(), !kIsWeb);
expect(nodeA.hasFocus, false);
expect(nodeB.hasFocus, !kIsWeb);
});
// This test creates a FocusScopeNode configured to traverse focus in a closed
// loop. After traversing one loop, it changes the behavior to leave the
// FlutterView, then verifies that the new behavior did indeed take effect.
testWidgets('FocusScopeNode.traversalEdgeBehavior takes effect after update', (WidgetTester tester) async {
final FocusScopeNode scope = FocusScopeNode();
addTearDown(scope.dispose);
expect(scope.traversalEdgeBehavior, TraversalEdgeBehavior.closedLoop);
final FocusNode nodeA = FocusNode();
addTearDown(nodeA.dispose);
final FocusNode nodeB = FocusNode();
addTearDown(nodeB.dispose);
Future<bool> nextFocus() async {
final bool result = Actions.invoke(
primaryFocus!.context!,
const NextFocusIntent(),
)! as bool;
await tester.pump();
return result;
}
Future<bool> previousFocus() async {
final bool result = Actions.invoke(
primaryFocus!.context!,
const PreviousFocusIntent(),
)! as bool;
await tester.pump();
return result;
}
await tester.pumpWidget(
MaterialApp(
home: Focus(
focusNode: scope,
child: Column(
children: <Widget>[
TextButton(
focusNode: nodeA,
child: const Text('A'),
onPressed: () {},
),
TextButton(
focusNode: nodeB,
child: const Text('B'),
onPressed: () {},
),
],
),
),
),
);
nodeA.requestFocus();
await tester.pump();
expect(nodeA.hasFocus, true);
expect(nodeB.hasFocus, false);
// A -> B
expect(await nextFocus(), isTrue);
expect(nodeA.hasFocus, false);
expect(nodeB.hasFocus, true);
// A <- B (wrap around)
expect(await nextFocus(), isTrue);
expect(nodeA.hasFocus, true);
expect(nodeB.hasFocus, false);
// Change the behavior and verify that the new behavior is in effect.
scope.traversalEdgeBehavior = TraversalEdgeBehavior.leaveFlutterView;
expect(scope.traversalEdgeBehavior, TraversalEdgeBehavior.leaveFlutterView);
// A -> B
expect(await nextFocus(), isTrue);
expect(nodeA.hasFocus, false);
expect(nodeB.hasFocus, true);
// B -> escape the view
expect(await nextFocus(), false);
expect(nodeA.hasFocus, false);
expect(nodeB.hasFocus, false);
// Change the behavior back to closedLoop and verify it's in effect. Also,
// this time traverse in the opposite direction.
nodeA.requestFocus();
await tester.pump();
expect(nodeA.hasFocus, true);
scope.traversalEdgeBehavior = TraversalEdgeBehavior.closedLoop;
expect(scope.traversalEdgeBehavior, TraversalEdgeBehavior.closedLoop);
expect(await previousFocus(), true);
expect(nodeA.hasFocus, false);
expect(nodeB.hasFocus, true);
});
testWidgets('NextFocusAction converts invoke result to KeyEventResult', (WidgetTester tester) async {
expect(
NextFocusAction().toKeyEventResult(const NextFocusIntent(), true),
KeyEventResult.handled,
);
expect(
NextFocusAction().toKeyEventResult(const NextFocusIntent(), false),
KeyEventResult.skipRemainingHandlers,
);
});
testWidgets('PreviousFocusAction converts invoke result to KeyEventResult', (WidgetTester tester) async {
expect(
PreviousFocusAction().toKeyEventResult(const PreviousFocusIntent(), true),
KeyEventResult.handled,
);
expect(
PreviousFocusAction().toKeyEventResult(const PreviousFocusIntent(), false),
KeyEventResult.skipRemainingHandlers,
);
});
testWidgets('RequestFocusAction calls the RequestFocusIntent.requestFocusCallback', (WidgetTester tester) async {
bool calledCallback = false;
final FocusNode nodeA = FocusNode();
addTearDown(nodeA.dispose);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: TextButton(
focusNode: nodeA,
child: const Text('A'),
onPressed: () {},
),
)
)
);
RequestFocusAction().invoke(RequestFocusIntent(nodeA));
await tester.pump();
expect(nodeA.hasFocus, isTrue);
nodeA.unfocus();
await tester.pump();
expect(nodeA.hasFocus, isFalse);
final RequestFocusIntent focusIntentWithCallback = RequestFocusIntent(nodeA, requestFocusCallback: (FocusNode node, {
double? alignment,
ScrollPositionAlignmentPolicy? alignmentPolicy,
Curve? curve,
Duration? duration
}) => calledCallback = true);
RequestFocusAction().invoke(focusIntentWithCallback);
await tester.pump();
expect(calledCallback, isTrue);
});
}
class TestRoute extends PageRouteBuilder<void> {
TestRoute({required Widget child})
: super(
pageBuilder: (BuildContext _, Animation<double> __, Animation<double> ___) {
return child;
},
);
}
/// Used to test removal of nodes while sorting.
class SkipAllButFirstAndLastPolicy extends FocusTraversalPolicy with DirectionalFocusTraversalPolicyMixin {
@override
Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) {
return <FocusNode>[
descendants.first,
if (currentNode != descendants.first && currentNode != descendants.last) currentNode,
descendants.last,
];
}
}
| flutter/packages/flutter/test/widgets/focus_traversal_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/focus_traversal_test.dart",
"repo_id": "flutter",
"token_count": 60717
} | 717 |
// 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can tap a hyperlink', (WidgetTester tester) async {
bool didTapLeft = false;
final TapGestureRecognizer tapLeft = TapGestureRecognizer()
..onTap = () {
didTapLeft = true;
};
addTearDown(tapLeft.dispose);
bool didTapRight = false;
final TapGestureRecognizer tapRight = TapGestureRecognizer()
..onTap = () {
didTapRight = true;
};
addTearDown(tapRight.dispose);
const Key textKey = Key('text');
await tester.pumpWidget(
Center(
child: RichText(
key: textKey,
textDirection: TextDirection.ltr,
text: TextSpan(
children: <TextSpan>[
TextSpan(
text: 'xxxxxxxx',
recognizer: tapLeft,
),
const TextSpan(text: 'yyyyyyyy'),
TextSpan(
text: 'zzzzzzzzz',
recognizer: tapRight,
),
],
),
),
),
);
final RenderBox box = tester.renderObject(find.byKey(textKey));
expect(didTapLeft, isFalse);
expect(didTapRight, isFalse);
await tester.tapAt(box.localToGlobal(Offset.zero) + const Offset(2.0, 2.0));
expect(didTapLeft, isTrue);
expect(didTapRight, isFalse);
didTapLeft = false;
await tester.tapAt(box.localToGlobal(Offset.zero) + const Offset(30.0, 2.0));
expect(didTapLeft, isTrue);
expect(didTapRight, isFalse);
didTapLeft = false;
await tester.tapAt(box.localToGlobal(Offset(box.size.width, 0.0)) + const Offset(-2.0, 2.0));
expect(didTapLeft, isFalse);
expect(didTapRight, isTrue);
});
}
| flutter/packages/flutter/test/widgets/hyperlink_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/hyperlink_test.dart",
"repo_id": "flutter",
"token_count": 887
} | 718 |
// 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_test/flutter_test.dart';
// A simple "flat" InheritedModel: the data model is just 3 integer
// valued fields: a, b, c.
class ABCModel extends InheritedModel<String> {
const ABCModel({
super.key,
this.a,
this.b,
this.c,
this.aspects,
required super.child,
});
final int? a;
final int? b;
final int? c;
// The aspects (fields) of this model that widgets can depend on with
// inheritFrom.
//
// This property is null by default, which means that the model supports
// all 3 fields.
final Set<String>? aspects;
@override
bool isSupportedAspect(Object aspect) {
return aspects == null || aspects!.contains(aspect);
}
@override
bool updateShouldNotify(ABCModel old) {
return !setEquals<String>(aspects, old.aspects) || a != old.a || b != old.b || c != old.c;
}
@override
bool updateShouldNotifyDependent(ABCModel old, Set<String> dependencies) {
return !setEquals<String>(aspects, old.aspects)
|| (a != old.a && dependencies.contains('a'))
|| (b != old.b && dependencies.contains('b'))
|| (c != old.c && dependencies.contains('c'));
}
static ABCModel? of(BuildContext context, { String? fieldName }) {
return InheritedModel.inheritFrom<ABCModel>(context, aspect: fieldName);
}
}
class ShowABCField extends StatefulWidget {
const ShowABCField({ super.key, required this.fieldName });
final String fieldName;
@override
State<ShowABCField> createState() => _ShowABCFieldState();
}
class _ShowABCFieldState extends State<ShowABCField> {
int _buildCount = 0;
@override
Widget build(BuildContext context) {
final ABCModel abc = ABCModel.of(context, fieldName: widget.fieldName)!;
final int? value = widget.fieldName == 'a' ? abc.a : (widget.fieldName == 'b' ? abc.b : abc.c);
return Text('${widget.fieldName}: $value [${_buildCount++}]');
}
}
void main() {
testWidgets('InheritedModel basics', (WidgetTester tester) async {
int a = 0;
int b = 1;
int c = 2;
final Widget abcPage = StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
const Widget showA = ShowABCField(fieldName: 'a');
const Widget showB = ShowABCField(fieldName: 'b');
const Widget showC = ShowABCField(fieldName: 'c');
// Unconditionally depends on the ABCModel: rebuilt when any
// aspect of the model changes.
final Widget showABC = Builder(
builder: (BuildContext context) {
final ABCModel abc = ABCModel.of(context)!;
return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}');
},
);
return Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return ABCModel(
a: a,
b: b,
c: c,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
showA,
showB,
showC,
showABC,
ElevatedButton(
child: const Text('Increment a'),
onPressed: () {
// Rebuilds the ABCModel which triggers a rebuild
// of showA because showA depends on the 'a' aspect
// of the ABCModel.
setState(() { a += 1; });
},
),
ElevatedButton(
child: const Text('Increment b'),
onPressed: () {
// Rebuilds the ABCModel which triggers a rebuild
// of showB because showB depends on the 'b' aspect
// of the ABCModel.
setState(() { b += 1; });
},
),
ElevatedButton(
child: const Text('Increment c'),
onPressed: () {
// Rebuilds the ABCModel which triggers a rebuild
// of showC because showC depends on the 'c' aspect
// of the ABCModel.
setState(() { c += 1; });
},
),
],
),
),
);
},
),
);
},
);
await tester.pumpWidget(MaterialApp(home: abcPage));
expect(find.text('a: 0 [0]'), findsOneWidget);
expect(find.text('b: 1 [0]'), findsOneWidget);
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 0 b: 1 c: 2'), findsOneWidget);
await tester.tap(find.text('Increment a'));
await tester.pumpAndSettle();
// Verify that field 'a' was incremented, but only the showA
// and showABC widgets were rebuilt.
expect(find.text('a: 1 [1]'), findsOneWidget);
expect(find.text('b: 1 [0]'), findsOneWidget);
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 1 b: 1 c: 2'), findsOneWidget);
// Verify that field 'a' was incremented, but only the showA
// and showABC widgets were rebuilt.
await tester.tap(find.text('Increment a'));
await tester.pumpAndSettle();
expect(find.text('a: 2 [2]'), findsOneWidget);
expect(find.text('b: 1 [0]'), findsOneWidget);
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 2 b: 1 c: 2'), findsOneWidget);
// Verify that field 'b' was incremented, but only the showB
// and showABC widgets were rebuilt.
await tester.tap(find.text('Increment b'));
await tester.pumpAndSettle();
expect(find.text('a: 2 [2]'), findsOneWidget);
expect(find.text('b: 2 [1]'), findsOneWidget);
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 2 b: 2 c: 2'), findsOneWidget);
// Verify that field 'c' was incremented, but only the showC
// and showABC widgets were rebuilt.
await tester.tap(find.text('Increment c'));
await tester.pumpAndSettle();
expect(find.text('a: 2 [2]'), findsOneWidget);
expect(find.text('b: 2 [1]'), findsOneWidget);
expect(find.text('c: 3 [1]'), findsOneWidget);
expect(find.text('a: 2 b: 2 c: 3'), findsOneWidget);
});
testWidgets('Looking up an non existent InheritedModel ancestor returns null', (WidgetTester tester) async {
ABCModel? inheritedModel;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
inheritedModel = InheritedModel.inheritFrom(context);
return Container();
},
),
);
// Shouldn't crash first of all.
expect(inheritedModel, null);
});
testWidgets('Inner InheritedModel shadows the outer one', (WidgetTester tester) async {
int a = 0;
int b = 1;
int c = 2;
// Same as in abcPage in the "InheritedModel basics" test except:
// there are two ABCModels and the inner model's "a" and "b"
// properties shadow (override) the outer model. Further complicating
// matters: the inner model only supports the model's "a" aspect,
// so showB and showC will depend on the outer model.
final Widget abcPage = StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
const Widget showA = ShowABCField(fieldName: 'a');
const Widget showB = ShowABCField(fieldName: 'b');
const Widget showC = ShowABCField(fieldName: 'c');
// Unconditionally depends on the closest ABCModel ancestor.
// Which is the inner model, for which b,c are null.
final Widget showABC = Builder(
builder: (BuildContext context) {
final ABCModel abc = ABCModel.of(context)!;
return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}', style: Theme.of(context).textTheme.titleLarge);
},
);
return Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return ABCModel( // The "outer" model
a: a,
b: b,
c: c,
child: ABCModel( // The "inner" model
a: 100 + a,
b: 100 + b,
aspects: const <String>{'a'},
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
showA,
showB,
showC,
const SizedBox(height: 24.0),
showABC,
const SizedBox(height: 24.0),
ElevatedButton(
child: const Text('Increment a'),
onPressed: () {
setState(() { a += 1; });
},
),
ElevatedButton(
child: const Text('Increment b'),
onPressed: () {
setState(() { b += 1; });
},
),
ElevatedButton(
child: const Text('Increment c'),
onPressed: () {
setState(() { c += 1; });
},
),
],
),
),
),
);
},
),
);
},
);
await tester.pumpWidget(MaterialApp(home: abcPage));
expect(find.text('a: 100 [0]'), findsOneWidget);
expect(find.text('b: 1 [0]'), findsOneWidget);
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 100 b: 101 c: null'), findsOneWidget);
await tester.tap(find.text('Increment a'));
await tester.pumpAndSettle();
// Verify that field 'a' was incremented, but only the showA
// and showABC widgets were rebuilt.
expect(find.text('a: 101 [1]'), findsOneWidget);
expect(find.text('b: 1 [0]'), findsOneWidget);
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 101 b: 101 c: null'), findsOneWidget);
await tester.tap(find.text('Increment a'));
await tester.pumpAndSettle();
// Verify that field 'a' was incremented, but only the showA
// and showABC widgets were rebuilt.
expect(find.text('a: 102 [2]'), findsOneWidget);
expect(find.text('b: 1 [0]'), findsOneWidget);
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 102 b: 101 c: null'), findsOneWidget);
// Verify that field 'b' was incremented, but only the showB
// and showABC widgets were rebuilt.
await tester.tap(find.text('Increment b'));
await tester.pumpAndSettle();
expect(find.text('a: 102 [2]'), findsOneWidget);
expect(find.text('b: 2 [1]'), findsOneWidget);
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 102 b: 102 c: null'), findsOneWidget);
// Verify that field 'c' was incremented, but only the showC
// and showABC widgets were rebuilt.
await tester.tap(find.text('Increment c'));
await tester.pumpAndSettle();
expect(find.text('a: 102 [2]'), findsOneWidget);
expect(find.text('b: 2 [1]'), findsOneWidget);
expect(find.text('c: 3 [1]'), findsOneWidget);
expect(find.text('a: 102 b: 102 c: null'), findsOneWidget);
});
testWidgets('InheritedModel inner models supported aspect change', (WidgetTester tester) async {
int a = 0;
int b = 1;
int c = 2;
Set<String>? innerModelAspects = <String>{'a'};
// Same as in abcPage in the "Inner InheritedModel shadows the outer one"
// test except: the "Add b aspect" changes adds 'b' to the set of
// aspects supported by the inner model.
final Widget abcPage = StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
const Widget showA = ShowABCField(fieldName: 'a');
const Widget showB = ShowABCField(fieldName: 'b');
const Widget showC = ShowABCField(fieldName: 'c');
// Unconditionally depends on the closest ABCModel ancestor.
// Which is the inner model, for which b,c are null.
final Widget showABC = Builder(
builder: (BuildContext context) {
final ABCModel abc = ABCModel.of(context)!;
return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}', style: Theme.of(context).textTheme.titleLarge);
},
);
return Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return ABCModel( // The "outer" model
a: a,
b: b,
c: c,
child: ABCModel( // The "inner" model
a: 100 + a,
b: 100 + b,
aspects: innerModelAspects,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
showA,
showB,
showC,
const SizedBox(height: 24.0),
showABC,
const SizedBox(height: 24.0),
ElevatedButton(
child: const Text('Increment a'),
onPressed: () {
setState(() { a += 1; });
},
),
ElevatedButton(
child: const Text('Increment b'),
onPressed: () {
setState(() { b += 1; });
},
),
ElevatedButton(
child: const Text('Increment c'),
onPressed: () {
setState(() { c += 1; });
},
),
ElevatedButton(
child: const Text('rebuild'),
onPressed: () {
setState(() {
// Rebuild both models
});
},
),
],
),
),
),
);
},
),
);
},
);
innerModelAspects = <String>{'a'};
await tester.pumpWidget(MaterialApp(home: abcPage));
expect(find.text('a: 100 [0]'), findsOneWidget); // showA depends on the inner model
expect(find.text('b: 1 [0]'), findsOneWidget); // showB depends on the outer model
expect(find.text('c: 2 [0]'), findsOneWidget);
expect(find.text('a: 100 b: 101 c: null'), findsOneWidget); // inner model's a, b, c
innerModelAspects = <String>{'a', 'b'};
await tester.tap(find.text('rebuild'));
await tester.pumpAndSettle();
expect(find.text('a: 100 [1]'), findsOneWidget); // rebuilt showA still depend on the inner model
expect(find.text('b: 101 [1]'), findsOneWidget); // rebuilt showB now depends on the inner model
expect(find.text('c: 2 [1]'), findsOneWidget); // rebuilt showC still depends on the outer model
expect(find.text('a: 100 b: 101 c: null'), findsOneWidget); // inner model's a, b, c
// Verify that field 'a' was incremented, but only the showA
// and showABC widgets were rebuilt.
await tester.tap(find.text('Increment a'));
await tester.pumpAndSettle();
expect(find.text('a: 101 [2]'), findsOneWidget); // rebuilt showA still depends on the inner model
expect(find.text('b: 101 [1]'), findsOneWidget);
expect(find.text('c: 2 [1]'), findsOneWidget);
expect(find.text('a: 101 b: 101 c: null'), findsOneWidget);
// Verify that field 'b' was incremented, but only the showB
// and showABC widgets were rebuilt.
await tester.tap(find.text('Increment b'));
await tester.pumpAndSettle();
expect(find.text('a: 101 [2]'), findsOneWidget); // rebuilt showB still depends on the inner model
expect(find.text('b: 102 [2]'), findsOneWidget);
expect(find.text('c: 2 [1]'), findsOneWidget);
expect(find.text('a: 101 b: 102 c: null'), findsOneWidget);
// Verify that field 'c' was incremented, but only the showC
// and showABC widgets were rebuilt.
await tester.tap(find.text('Increment c'));
await tester.pumpAndSettle();
expect(find.text('a: 101 [2]'), findsOneWidget);
expect(find.text('b: 102 [2]'), findsOneWidget);
expect(find.text('c: 3 [2]'), findsOneWidget); // rebuilt showC still depends on the outer model
expect(find.text('a: 101 b: 102 c: null'), findsOneWidget);
innerModelAspects = <String>{'a', 'b', 'c'};
await tester.tap(find.text('rebuild'));
await tester.pumpAndSettle();
expect(find.text('a: 101 [3]'), findsOneWidget); // rebuilt showA still depend on the inner model
expect(find.text('b: 102 [3]'), findsOneWidget); // rebuilt showB still depends on the inner model
expect(find.text('c: null [3]'), findsOneWidget); // rebuilt showC now depends on the inner model
expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); // inner model's a, b, c
// Now the inner model supports no aspects
innerModelAspects = <String>{};
await tester.tap(find.text('rebuild'));
await tester.pumpAndSettle();
expect(find.text('a: 1 [4]'), findsOneWidget); // rebuilt showA now depends on the outer model
expect(find.text('b: 2 [4]'), findsOneWidget); // rebuilt showB now depends on the outer model
expect(find.text('c: 3 [4]'), findsOneWidget); // rebuilt showC now depends on the outer model
expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); // inner model's a, b, c
// Now the inner model supports all aspects
innerModelAspects = null;
await tester.tap(find.text('rebuild'));
await tester.pumpAndSettle();
expect(find.text('a: 101 [5]'), findsOneWidget); // rebuilt showA now depends on the inner model
expect(find.text('b: 102 [5]'), findsOneWidget); // rebuilt showB now depends on the inner model
expect(find.text('c: null [5]'), findsOneWidget); // rebuilt showC now depends on the inner model
expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); // inner model's a, b, c
});
}
| flutter/packages/flutter/test/widgets/inherited_model_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/inherited_model_test.dart",
"repo_id": "flutter",
"token_count": 8843
} | 719 |
// 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 contains a wacky demonstration of creating a custom ScrollPosition
// setup. It's testing that we don't regress the factoring of the
// ScrollPosition/ScrollActivity logic into a state where you can no longer
// implement this, e.g. by oversimplifying it or overfitting it to the features
// built into the framework itself.
import 'dart:collection';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
class LinkedScrollController extends ScrollController {
LinkedScrollController({ this.before, this.after });
LinkedScrollController? before;
LinkedScrollController? after;
ScrollController? _parent;
void setParent(ScrollController? newParent) {
if (_parent != null) {
positions.forEach(_parent!.detach);
}
_parent = newParent;
if (_parent != null) {
positions.forEach(_parent!.attach);
}
}
@override
void attach(ScrollPosition position) {
assert(position is LinkedScrollPosition, 'A LinkedScrollController must only be used with LinkedScrollPositions.');
final LinkedScrollPosition linkedPosition = position as LinkedScrollPosition;
assert(linkedPosition.owner == this, 'A LinkedScrollPosition cannot change controllers once created.');
super.attach(position);
_parent?.attach(position);
}
@override
void detach(ScrollPosition position) {
super.detach(position);
_parent?.detach(position);
}
@override
void dispose() {
if (_parent != null) {
positions.forEach(_parent!.detach);
}
super.dispose();
}
@override
LinkedScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) {
return LinkedScrollPosition(
this,
physics: physics,
context: context,
initialPixels: initialScrollOffset,
oldPosition: oldPosition,
);
}
bool get canLinkWithBefore => before != null && before!.hasClients;
bool get canLinkWithAfter => after != null && after!.hasClients;
Iterable<LinkedScrollActivity> linkWithBefore(LinkedScrollPosition driver) {
assert(canLinkWithBefore);
return before!.link(driver);
}
Iterable<LinkedScrollActivity> linkWithAfter(LinkedScrollPosition driver) {
assert(canLinkWithAfter);
return after!.link(driver);
}
Iterable<LinkedScrollActivity> link(LinkedScrollPosition driver) sync* {
assert(hasClients);
for (final LinkedScrollPosition position in positions.cast<LinkedScrollPosition>()) {
yield position.link(driver);
}
}
@override
void debugFillDescription(List<String> description) {
super.debugFillDescription(description);
if (before != null && after != null) {
description.add('links: ⬌');
} else if (before != null) {
description.add('links: ⬅');
} else if (after != null) {
description.add('links: ➡');
} else {
description.add('links: none');
}
}
}
class LinkedScrollPosition extends ScrollPositionWithSingleContext {
LinkedScrollPosition(
this.owner, {
required super.physics,
required super.context,
required double super.initialPixels,
super.oldPosition,
});
final LinkedScrollController owner;
Set<LinkedScrollActivity>? _beforeActivities;
Set<LinkedScrollActivity>? _afterActivities;
@override
void beginActivity(ScrollActivity? newActivity) {
if (newActivity == null) {
return;
}
if (_beforeActivities != null) {
for (final LinkedScrollActivity activity in _beforeActivities!) {
activity.unlink(this);
}
_beforeActivities!.clear();
}
if (_afterActivities != null) {
for (final LinkedScrollActivity activity in _afterActivities!) {
activity.unlink(this);
}
_afterActivities!.clear();
}
super.beginActivity(newActivity);
}
@override
void applyUserOffset(double delta) {
updateUserScrollDirection(delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse);
final double value = pixels - physics.applyPhysicsToUserOffset(this, delta);
if (value == pixels) {
return;
}
double beforeOverscroll = 0.0;
if (owner.canLinkWithBefore && (value < minScrollExtent)) {
final double delta = value - minScrollExtent;
_beforeActivities ??= HashSet<LinkedScrollActivity>();
_beforeActivities!.addAll(owner.linkWithBefore(this));
for (final LinkedScrollActivity activity in _beforeActivities!) {
beforeOverscroll = math.min(activity.moveBy(delta), beforeOverscroll);
}
assert(beforeOverscroll <= 0.0);
}
double afterOverscroll = 0.0;
if (owner.canLinkWithAfter && (value > maxScrollExtent)) {
final double delta = value - maxScrollExtent;
_afterActivities ??= HashSet<LinkedScrollActivity>();
_afterActivities!.addAll(owner.linkWithAfter(this));
for (final LinkedScrollActivity activity in _afterActivities!) {
afterOverscroll = math.max(activity.moveBy(delta), afterOverscroll);
}
assert(afterOverscroll >= 0.0);
}
assert(beforeOverscroll == 0.0 || afterOverscroll == 0.0);
final double localOverscroll = setPixels(value.clamp(
owner.canLinkWithBefore ? minScrollExtent : -double.infinity,
owner.canLinkWithAfter ? maxScrollExtent : double.infinity,
));
assert(localOverscroll == 0.0 || (beforeOverscroll == 0.0 && afterOverscroll == 0.0));
}
void _userMoved(ScrollDirection direction) {
updateUserScrollDirection(direction);
}
LinkedScrollActivity link(LinkedScrollPosition driver) {
if (this.activity is! LinkedScrollActivity) {
beginActivity(LinkedScrollActivity(this));
}
final LinkedScrollActivity? activity = this.activity as LinkedScrollActivity?;
activity!.link(driver);
return activity;
}
void unlink(LinkedScrollActivity activity) {
if (_beforeActivities != null) {
_beforeActivities!.remove(activity);
}
if (_afterActivities != null) {
_afterActivities!.remove(activity);
}
}
@override
void debugFillDescription(List<String> description) {
super.debugFillDescription(description);
description.add('owner: $owner');
}
}
class LinkedScrollActivity extends ScrollActivity {
LinkedScrollActivity(
LinkedScrollPosition super.delegate,
);
@override
LinkedScrollPosition get delegate => super.delegate as LinkedScrollPosition;
final Set<LinkedScrollPosition> drivers = HashSet<LinkedScrollPosition>();
void link(LinkedScrollPosition driver) {
drivers.add(driver);
}
void unlink(LinkedScrollPosition driver) {
drivers.remove(driver);
if (drivers.isEmpty) {
delegate.goIdle();
}
}
@override
bool get shouldIgnorePointer => true;
@override
bool get isScrolling => true;
// LinkedScrollActivity is not self-driven but moved by calls to the [moveBy]
// method.
@override
double get velocity => 0.0;
double moveBy(double delta) {
assert(drivers.isNotEmpty);
ScrollDirection? commonDirection;
for (final LinkedScrollPosition driver in drivers) {
commonDirection ??= driver.userScrollDirection;
if (driver.userScrollDirection != commonDirection) {
commonDirection = ScrollDirection.idle;
}
}
if (commonDirection != null) {
delegate._userMoved(commonDirection);
}
return delegate.setPixels(delegate.pixels + delta);
}
@override
void dispose() {
for (final LinkedScrollPosition driver in drivers) {
driver.unlink(this);
}
super.dispose();
}
}
class Test extends StatefulWidget {
const Test({ super.key });
@override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
late LinkedScrollController _beforeController;
late LinkedScrollController _afterController;
@override
void initState() {
super.initState();
_beforeController = LinkedScrollController();
_afterController = LinkedScrollController(before: _beforeController);
_beforeController.after = _afterController;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_beforeController.setParent(PrimaryScrollController.maybeOf(context));
_afterController.setParent(PrimaryScrollController.maybeOf(context));
}
@override
void dispose() {
_beforeController.dispose();
_afterController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
Expanded(
child: ListView(
controller: _beforeController,
children: <Widget>[
Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
height: 250.0,
color: const Color(0xFF90F090),
child: const Center(child: Text('Hello A')),
),
Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
height: 250.0,
color: const Color(0xFF90F090),
child: const Center(child: Text('Hello B')),
),
Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
height: 250.0,
color: const Color(0xFF90F090),
child: const Center(child: Text('Hello C')),
),
Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
height: 250.0,
color: const Color(0xFF90F090),
child: const Center(child: Text('Hello D')),
),
],
),
),
const Divider(),
Expanded(
child: ListView(
controller: _afterController,
children: <Widget>[
Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
height: 250.0,
color: const Color(0xFF9090F0),
child: const Center(child: Text('Hello 1')),
),
Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
height: 250.0,
color: const Color(0xFF9090F0),
child: const Center(child: Text('Hello 2')),
),
Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
height: 250.0,
color: const Color(0xFF9090F0),
child: const Center(child: Text('Hello 3')),
),
Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
height: 250.0,
color: const Color(0xFF9090F0),
child: const Center(child: Text('Hello 4')),
),
],
),
),
],
),
);
}
}
void main() {
testWidgets('LinkedScrollController - 1', (WidgetTester tester) async {
await tester.pumpWidget(const Test());
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await tester.pump(const Duration(seconds: 2));
await tester.fling(find.text('Hello A'), const Offset(0.0, -50.0), 10000.0);
await tester.pumpAndSettle();
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello D'), findsOneWidget);
expect(find.text('Hello 4'), findsNothing);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello D'), const Offset(0.0, -10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello D'), findsOneWidget);
expect(find.text('Hello 4'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello D'), const Offset(0.0, -10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello D'), findsOneWidget);
expect(find.text('Hello 4'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello 4'), const Offset(0.0, -10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello D'), findsOneWidget);
expect(find.text('Hello 4'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello D'), const Offset(0.0, 10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 4'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello A'), const Offset(0.0, 10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 4'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello A'), const Offset(0.0, -10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello D'), findsOneWidget);
expect(find.text('Hello 4'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello 4'), const Offset(0.0, 10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello 1'), const Offset(0.0, 10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await tester.pump(const Duration(seconds: 2));
await tester.drag(find.text('Hello 1'), const Offset(0.0, -10000.0));
await tester.pump(const Duration(seconds: 2));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 4'), findsOneWidget);
});
testWidgets('LinkedScrollController - 2', (WidgetTester tester) async {
await tester.pumpWidget(const Test());
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsNothing);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
final TestGesture gestureTop = await tester.startGesture(const Offset(200.0, 150.0));
final TestGesture gestureBottom = await tester.startGesture(const Offset(600.0, 450.0));
await tester.pump(const Duration(seconds: 1));
await gestureTop.moveBy(const Offset(0.0, -270.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsOneWidget);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await gestureBottom.moveBy(const Offset(0.0, -270.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsOneWidget);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsOneWidget);
expect(find.text('Hello 4'), findsNothing);
await gestureTop.moveBy(const Offset(0.0, -270.0));
await gestureBottom.moveBy(const Offset(0.0, -270.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello B'), findsNothing);
expect(find.text('Hello C'), findsOneWidget);
expect(find.text('Hello D'), findsOneWidget);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello 2'), findsNothing);
expect(find.text('Hello 3'), findsOneWidget);
expect(find.text('Hello 4'), findsOneWidget);
await gestureTop.moveBy(const Offset(0.0, 270.0));
await gestureBottom.moveBy(const Offset(0.0, 270.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsOneWidget);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsNothing);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsOneWidget);
expect(find.text('Hello 4'), findsNothing);
await gestureBottom.moveBy(const Offset(0.0, 270.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello A'), findsNothing);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsOneWidget);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await gestureBottom.moveBy(const Offset(0.0, 50.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsNothing);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await gestureBottom.moveBy(const Offset(0.0, 50.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsNothing);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await gestureBottom.moveBy(const Offset(0.0, 50.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsNothing);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await gestureTop.moveBy(const Offset(0.0, -270.0));
expect(find.text('Hello A'), findsOneWidget);
expect(find.text('Hello B'), findsOneWidget);
expect(find.text('Hello C'), findsNothing);
expect(find.text('Hello D'), findsNothing);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello 2'), findsOneWidget);
expect(find.text('Hello 3'), findsNothing);
expect(find.text('Hello 4'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 60));
});
}
| flutter/packages/flutter/test/widgets/linked_scroll_view_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/linked_scroll_view_test.dart",
"repo_id": "flutter",
"token_count": 8011
} | 720 |
// 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/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
/// A mock class to control the return result of Live Text input functions.
class LiveTextInputTester {
LiveTextInputTester() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, _handler);
}
bool mockLiveTextInputEnabled = false;
Future<Object?> _handler(MethodCall methodCall) async {
// Need to set Clipboard.hasStrings method handler because when showing the tool bar,
// the Clipboard.hasStrings will also be invoked. If this isn't handled,
// an exception will be thrown.
if (methodCall.method == 'Clipboard.hasStrings') {
return <String, bool>{'value': true};
}
if (methodCall.method == 'LiveText.isLiveTextInputAvailable') {
return mockLiveTextInputEnabled;
}
return false;
}
void dispose() {
assert(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(SystemChannels.platform.name, _handler));
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
}
}
/// A function to find the live text button.
///
/// LiveText button is displayed either using a custom painter,
/// a Text with an empty label, or a Text with the 'Scan text' label.
Finder findLiveTextButton() {
final bool isMobile = defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.fuchsia ||
defaultTargetPlatform == TargetPlatform.iOS;
if (isMobile) {
return find.byWidgetPredicate((Widget widget) {
return (widget is CustomPaint && '${widget.painter?.runtimeType}' == '_LiveTextIconPainter')
|| (widget is Text && widget.data == 'Scan text'); // Android and Fuchsia when inside a MaterialApp.
});
}
if (defaultTargetPlatform == TargetPlatform.macOS) {
return find.ancestor(of: find.text(''), matching: find.byType(CupertinoDesktopTextSelectionToolbarButton));
}
return find.byWidgetPredicate((Widget widget) {
return widget is Text && (widget.data == '' || widget.data == 'Scan text');
});
}
| flutter/packages/flutter/test/widgets/live_text_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/live_text_utils.dart",
"repo_id": "flutter",
"token_count": 785
} | 721 |
// 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 'observer_tester.dart';
void main() {
testWidgets('Back during pushReplacement', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: const Material(child: Text('home')),
routes: <String, WidgetBuilder>{
'/a': (BuildContext context) => const Material(child: Text('a')),
'/b': (BuildContext context) => const Material(child: Text('b')),
},
));
final NavigatorState navigator = tester.state(find.byType(Navigator));
navigator.pushNamed('/a');
await tester.pumpAndSettle();
expect(find.text('a'), findsOneWidget);
expect(find.text('home'), findsNothing);
navigator.pushReplacementNamed('/b');
await tester.pump();
await tester.pump(const Duration(milliseconds: 10));
expect(find.text('a'), findsOneWidget);
expect(find.text('b'), findsOneWidget);
expect(find.text('home'), findsNothing);
navigator.pop();
await tester.pumpAndSettle();
expect(find.text('a'), findsNothing);
expect(find.text('b'), findsNothing);
expect(find.text('home'), findsOneWidget);
});
group('pushAndRemoveUntil', () {
testWidgets('notifies appropriately', (WidgetTester tester) async {
final TestObserver observer = TestObserver();
final Widget myApp = MaterialApp(
home: const Material(child: Text('home')),
routes: <String, WidgetBuilder>{
'/a': (BuildContext context) => const Material(child: Text('a')),
'/b': (BuildContext context) => const Material(child: Text('b')),
},
navigatorObservers: <NavigatorObserver>[observer],
);
await tester.pumpWidget(myApp);
final NavigatorState navigator = tester.state(find.byType(Navigator));
final List<String> log = <String>[];
observer
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
log.add('${route!.settings.name} pushed, previous route: ${previousRoute!.settings.name}');
}
..onRemoved = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
log.add('${route!.settings.name} removed, previous route: ${previousRoute?.settings.name}');
};
navigator.pushNamed('/a');
await tester.pumpAndSettle();
expect(find.text('home', skipOffstage: false), findsOneWidget);
expect(find.text('a', skipOffstage: false), findsOneWidget);
expect(find.text('b', skipOffstage: false), findsNothing);
// Remove all routes below
navigator.pushNamedAndRemoveUntil('/b', (Route<dynamic> route) => false);
await tester.pumpAndSettle();
expect(find.text('home', skipOffstage: false), findsNothing);
expect(find.text('a', skipOffstage: false), findsNothing);
expect(find.text('b', skipOffstage: false), findsOneWidget);
expect(log, equals(<String>[
'/a pushed, previous route: /',
'/b pushed, previous route: /a',
'/a removed, previous route: null',
'/ removed, previous route: null',
]));
log.clear();
navigator.pushNamed('/');
await tester.pumpAndSettle();
expect(find.text('home', skipOffstage: false), findsOneWidget);
expect(find.text('a', skipOffstage: false), findsNothing);
expect(find.text('b', skipOffstage: false), findsOneWidget);
// Remove only some routes below
navigator.pushNamedAndRemoveUntil('/a', ModalRoute.withName('/b'));
await tester.pumpAndSettle();
expect(find.text('home', skipOffstage: false), findsNothing);
expect(find.text('a', skipOffstage: false), findsOneWidget);
expect(find.text('b', skipOffstage: false), findsOneWidget);
expect(log, equals(<String>[
'/ pushed, previous route: /b',
'/a pushed, previous route: /',
'/ removed, previous route: /b',
]));
});
testWidgets('triggers page transition animation for pushed route', (WidgetTester tester) async {
final Widget myApp = MaterialApp(
home: const Material(child: Text('home')),
routes: <String, WidgetBuilder>{
'/a': (BuildContext context) => const Material(child: Text('a')),
'/b': (BuildContext context) => const Material(child: Text('b')),
},
);
await tester.pumpWidget(myApp);
final NavigatorState navigator = tester.state(find.byType(Navigator));
navigator.pushNamed('/a');
await tester.pumpAndSettle();
navigator.pushNamedAndRemoveUntil('/b', (Route<dynamic> route) => false);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
// We are mid-transition, both pages are onstage
expect(find.text('a'), findsOneWidget);
expect(find.text('b'), findsOneWidget);
// Complete transition
await tester.pumpAndSettle();
expect(find.text('a'), findsNothing);
expect(find.text('b'), findsOneWidget);
});
testWidgets('Hero transition triggers when preceding route contains hero, and predicate route does not', (WidgetTester tester) async {
const String kHeroTag = 'hero';
final Widget myApp = MaterialApp(
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => const Material(child: Text('home')),
'/a': (BuildContext context) => const Material(child: Hero(
tag: kHeroTag,
child: Text('a'),
)),
'/b': (BuildContext context) => const Material(child: Padding(
padding: EdgeInsets.all(100.0),
child: Hero(
tag: kHeroTag,
child: Text('b'),
),
)),
},
);
await tester.pumpWidget(myApp);
final NavigatorState navigator = tester.state(find.byType(Navigator));
navigator.pushNamed('/a');
await tester.pumpAndSettle();
navigator.pushNamedAndRemoveUntil('/b', ModalRoute.withName('/'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
expect(find.text('b'), isOnstage);
// 'b' text is heroing to its new location
final Offset bOffset = tester.getTopLeft(find.text('b'));
expect(bOffset.dx, greaterThan(0.0));
expect(bOffset.dx, lessThan(100.0));
expect(bOffset.dy, greaterThan(0.0));
expect(bOffset.dy, lessThan(100.0));
await tester.pump(const Duration(seconds: 1));
expect(find.text('a'), findsNothing);
expect(find.text('b'), isOnstage);
});
testWidgets('Hero transition does not trigger when preceding route does not contain hero, but predicate route does', (WidgetTester tester) async {
const String kHeroTag = 'hero';
final Widget myApp = MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
},
),
),
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => const Material(child: Hero(
tag:kHeroTag,
child: Text('home'),
)),
'/a': (BuildContext context) => const Material(child: Text('a')),
'/b': (BuildContext context) => const Material(child: Padding(
padding: EdgeInsets.all(100.0),
child: Hero(
tag: kHeroTag,
child: Text('b'),
),
)),
},
);
await tester.pumpWidget(myApp);
final NavigatorState navigator = tester.state(find.byType(Navigator));
navigator.pushNamed('/a');
await tester.pumpAndSettle();
navigator.pushNamedAndRemoveUntil('/b', ModalRoute.withName('/'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
expect(find.text('b'), isOnstage);
// 'b' text is sliding in from the right, no hero transition
final Offset bOffset = tester.getTopLeft(find.text('b'));
expect(bOffset.dx, 100.0);
expect(bOffset.dy, greaterThan(100.0));
});
});
}
| flutter/packages/flutter/test/widgets/navigator_replacement_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/navigator_replacement_test.dart",
"repo_id": "flutter",
"token_count": 3361
} | 722 |
// 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';
class TestTransition extends AnimatedWidget {
const TestTransition({
super.key,
required this.childFirstHalf,
required this.childSecondHalf,
required Animation<double> animation,
}) : super(listenable: animation);
final Widget childFirstHalf;
final Widget childSecondHalf;
@override
Widget build(BuildContext context) {
final Animation<double> animation = listenable as Animation<double>;
if (animation.value >= 0.5) {
return childSecondHalf;
}
return childFirstHalf;
}
}
class TestRoute<T> extends PageRoute<T> {
TestRoute({
required this.child,
required RouteSettings settings,
this.barrierColor,
}) : super(settings: settings);
final Widget child;
@override
Duration get transitionDuration => const Duration(milliseconds: 150);
@override
final Color? barrierColor;
@override
String? get barrierLabel => null;
@override
bool get maintainState => false;
@override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return child;
}
}
void main() {
const Duration kTwoTenthsOfTheTransitionDuration = Duration(milliseconds: 30);
const Duration kFourTenthsOfTheTransitionDuration = Duration(milliseconds: 60);
testWidgets('Check onstage/offstage handling around transitions', (WidgetTester tester) async {
final GlobalKey insideKey = GlobalKey();
String state({ bool skipOffstage = true }) {
String result = '';
if (tester.any(find.text('A', skipOffstage: skipOffstage))) {
result += 'A';
}
if (tester.any(find.text('B', skipOffstage: skipOffstage))) {
result += 'B';
}
if (tester.any(find.text('C', skipOffstage: skipOffstage))) {
result += 'C';
}
if (tester.any(find.text('D', skipOffstage: skipOffstage))) {
result += 'D';
}
if (tester.any(find.text('E', skipOffstage: skipOffstage))) {
result += 'E';
}
if (tester.any(find.text('F', skipOffstage: skipOffstage))) {
result += 'F';
}
if (tester.any(find.text('G', skipOffstage: skipOffstage))) {
result += 'G';
}
return result;
}
await tester.pumpWidget(
MaterialApp(
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case '/':
return TestRoute<void>(
settings: settings,
child: Builder(
key: insideKey,
builder: (BuildContext context) {
final PageRoute<void> route = ModalRoute.of(context)! as PageRoute<void>;
return Column(
children: <Widget>[
TestTransition(
childFirstHalf: const Text('A'),
childSecondHalf: const Text('B'),
animation: route.animation!,
),
TestTransition(
childFirstHalf: const Text('C'),
childSecondHalf: const Text('D'),
animation: route.secondaryAnimation!,
),
],
);
},
),
);
case '/2': return TestRoute<void>(settings: settings, child: const Text('E'));
case '/3': return TestRoute<void>(settings: settings, child: const Text('F'));
case '/4': return TestRoute<void>(settings: settings, child: const Text('G'));
}
return null;
},
),
);
final NavigatorState navigator = insideKey.currentContext!.findAncestorStateOfType<NavigatorState>()!;
expect(state(), equals('BC')); // transition ->1 is at 1.0
navigator.pushNamed('/2');
expect(state(), equals('BC')); // transition 1->2 is not yet built
await tester.pump();
expect(state(), equals('BC')); // transition 1->2 is at 0.0
expect(state(skipOffstage: false), equals('BCE')); // E is offstage
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('BCE')); // transition 1->2 is at 0.4
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('BDE')); // transition 1->2 is at 0.8
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('E')); // transition 1->2 is at 1.0
expect(state(skipOffstage: false), equals('E')); // B and C are gone, the route is inactive with maintainState=false
navigator.pop();
expect(state(), equals('E')); // transition 1<-2 is at 1.0, just reversed
await tester.pump();
await tester.pump();
expect(state(), equals('BDE')); // transition 1<-2 is at 1.0
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('BDE')); // transition 1<-2 is at 0.6
navigator.pushNamed('/3');
expect(state(), equals('BDE')); // transition 1<-2 is at 0.6
await tester.pump();
expect(state(), equals('BDE')); // transition 1<-2 is at 0.6, 1->3 is at 0.0
expect(state(skipOffstage: false), equals('BDEF')); // F is offstage since we're at 0.0
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('BCEF')); // transition 1<-2 is at 0.2, 1->3 is at 0.4
expect(state(skipOffstage: false), equals('BCEF')); // nothing secret going on here
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('BDF')); // transition 1<-2 is done, 1->3 is at 0.8
navigator.pop();
expect(state(), equals('BDF')); // transition 1<-3 is at 0.8, just reversed
await tester.pump();
expect(state(), equals('BDF')); // transition 1<-3 is at 0.8
await tester.pump(kTwoTenthsOfTheTransitionDuration); // notice that dT=0.2 here, not 0.4
expect(state(), equals('BDF')); // transition 1<-3 is at 0.6
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('BCF')); // transition 1<-3 is at 0.2
navigator.pushNamed('/4');
expect(state(), equals('BCF')); // transition 1<-3 is at 0.2, 1->4 is not yet built
await tester.pump();
expect(state(), equals('BCF')); // transition 1<-3 is at 0.2, 1->4 is at 0.0
expect(state(skipOffstage: false), equals('BCFG')); // G is offstage
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('BCG')); // transition 1<-3 is done, 1->4 is at 0.4
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('BDG')); // transition 1->4 is at 0.8
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(state(), equals('G')); // transition 1->4 is done
expect(state(skipOffstage: false), equals('G')); // route 1 is not around any more
});
testWidgets('Check onstage/offstage handling of barriers around transitions', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
onGenerateRoute: (RouteSettings settings) => switch (settings.name) {
'/' => TestRoute<void>(settings: settings, child: const Text('A')),
'/1' => TestRoute<void>(settings: settings, barrierColor: const Color(0xFFFFFF00), child: const Text('B')),
_ => null,
},
),
);
expect(find.byType(ModalBarrier), findsOneWidget);
tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/1');
expect(find.byType(ModalBarrier), findsOneWidget);
await tester.pump();
expect(find.byType(ModalBarrier), findsNWidgets(2));
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).first).color, isNull);
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, isNull);
await tester.pump(const Duration(seconds: 1));
expect(find.byType(ModalBarrier), findsOneWidget);
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier)).color, const Color(0xFFFFFF00));
});
}
| flutter/packages/flutter/test/widgets/page_forward_transitions_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/page_forward_transitions_test.dart",
"repo_id": "flutter",
"token_count": 3308
} | 723 |
// 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can dispose without keyboard', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(RawKeyboardListener(focusNode: focusNode, child: Container()));
await tester.pumpWidget(RawKeyboardListener(focusNode: focusNode, child: Container()));
await tester.pumpWidget(Container());
});
testWidgets('Fuchsia key event', (WidgetTester tester) async {
final List<RawKeyEvent> events = <RawKeyEvent>[];
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
RawKeyboardListener(
focusNode: focusNode,
onKey: events.add,
child: Container(),
),
);
focusNode.requestFocus();
await tester.idle();
await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia');
await tester.idle();
expect(events.length, 2);
expect(events[0].runtimeType, equals(RawKeyDownEvent));
expect(events[0].data.runtimeType, equals(RawKeyEventDataFuchsia));
final RawKeyEventDataFuchsia typedData = events[0].data as RawKeyEventDataFuchsia;
expect(typedData.hidUsage, 0x700e3);
expect(typedData.codePoint, 0x0);
expect(typedData.modifiers, RawKeyEventDataFuchsia.modifierLeftMeta);
expect(typedData.isModifierPressed(ModifierKey.metaModifier, side: KeyboardSide.left), isTrue);
await tester.pumpWidget(Container());
}, skip: isBrowser); // [intended] This is a Fuchsia-specific test.
testWidgets('Web key event', (WidgetTester tester) async {
final List<RawKeyEvent> events = <RawKeyEvent>[];
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
RawKeyboardListener(
focusNode: focusNode,
onKey: events.add,
child: Container(),
),
);
focusNode.requestFocus();
await tester.idle();
await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'web');
await tester.idle();
expect(events.length, 2);
expect(events[0].runtimeType, equals(RawKeyDownEvent));
expect(events[0].data, isA<RawKeyEventDataWeb>());
final RawKeyEventDataWeb typedData = events[0].data as RawKeyEventDataWeb;
expect(typedData.code, 'MetaLeft');
expect(typedData.metaState, RawKeyEventDataWeb.modifierMeta);
expect(typedData.isModifierPressed(ModifierKey.metaModifier, side: KeyboardSide.left), isTrue);
await tester.pumpWidget(Container());
});
testWidgets('Defunct listeners do not receive events', (WidgetTester tester) async {
final List<RawKeyEvent> events = <RawKeyEvent>[];
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
RawKeyboardListener(
focusNode: focusNode,
onKey: events.add,
child: Container(),
),
);
focusNode.requestFocus();
await tester.idle();
await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia');
await tester.idle();
expect(events.length, 2);
events.clear();
await tester.pumpWidget(Container());
await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia');
await tester.idle();
expect(events.length, 0);
await tester.pumpWidget(Container());
});
}
| flutter/packages/flutter/test/widgets/raw_keyboard_listener_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/raw_keyboard_listener_test.dart",
"repo_id": "flutter",
"token_count": 1320
} | 724 |
// 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class OnTapPage extends StatelessWidget {
const OnTapPage({super.key, required this.id, required this.onTap});
final String id;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Page $id')),
body: GestureDetector(
onTap: onTap,
behavior: HitTestBehavior.opaque,
child: Center(
child: Text(id, style: Theme.of(context).textTheme.displaySmall),
),
),
);
}
}
void main() {
testWidgets('Push and Pop should send platform messages', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => OnTapPage(
id: '/',
onTap: () {
Navigator.pushNamed(context, '/A');
},
),
'/A': (BuildContext context) => OnTapPage(
id: 'A',
onTap: () {
Navigator.pop(context);
},
),
};
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await tester.pumpWidget(MaterialApp(
routes: routes,
));
expect(log, <Object>[
isMethodCall('selectSingleEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated',
arguments: <String, dynamic>{
'uri': '/',
'state': null,
'replace': false,
},
),
]);
log.clear();
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(log, hasLength(1));
expect(
log.last,
isMethodCall(
'routeInformationUpdated',
arguments: <String, dynamic>{
'uri': '/A',
'state': null,
'replace': false,
},
),
);
log.clear();
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(log, hasLength(1));
expect(
log.last,
isMethodCall(
'routeInformationUpdated',
arguments: <String, dynamic>{
'uri': '/',
'state': null,
'replace': false,
},
),
);
});
testWidgets('Navigator does not report route name by default', (WidgetTester tester) async {
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Navigator(
pages: const <Page<void>>[
TestPage(name: '/'),
],
onPopPage: (Route<void> route, void result) => false,
),
));
expect(log, hasLength(0));
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Navigator(
pages: const <Page<void>>[
TestPage(name: '/'),
TestPage(name: '/abc'),
],
onPopPage: (Route<void> route, void result) => false,
),
));
await tester.pumpAndSettle();
expect(log, hasLength(0));
});
testWidgets('Replace should send platform messages', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => OnTapPage(
id: '/',
onTap: () {
Navigator.pushNamed(context, '/A');
},
),
'/A': (BuildContext context) => OnTapPage(
id: 'A',
onTap: () {
Navigator.pushReplacementNamed(context, '/B');
},
),
'/B': (BuildContext context) => OnTapPage(id: 'B', onTap: () {}),
};
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await tester.pumpWidget(MaterialApp(
routes: routes,
));
expect(log, <Object>[
isMethodCall('selectSingleEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated',
arguments: <String, dynamic>{
'uri': '/',
'state': null,
'replace': false,
},
),
]);
log.clear();
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(log, hasLength(1));
expect(
log.last,
isMethodCall(
'routeInformationUpdated',
arguments: <String, dynamic>{
'uri': '/A',
'state': null,
'replace': false,
},
),
);
log.clear();
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(log, hasLength(1));
expect(
log.last,
isMethodCall(
'routeInformationUpdated',
arguments: <String, dynamic>{
'uri': '/B',
'state': null,
'replace': false,
},
),
);
});
testWidgets('Nameless routes should send platform messages', (WidgetTester tester) async {
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await tester.pumpWidget(MaterialApp(
initialRoute: '/home',
routes: <String, WidgetBuilder>{
'/home': (BuildContext context) {
return OnTapPage(
id: 'Home',
onTap: () {
// Create a route with no name.
final Route<void> route = MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('Nameless Route'),
);
Navigator.push<void>(context, route);
},
);
},
},
));
expect(log, <Object>[
isMethodCall('selectSingleEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated',
arguments: <String, dynamic>{
'uri': '/home',
'state': null,
'replace': false,
},
),
]);
log.clear();
await tester.tap(find.text('Home'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(log, isEmpty);
});
testWidgets('PlatformRouteInformationProvider reports URL', (WidgetTester tester) async {
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse('initial'),
),
);
addTearDown(provider.dispose);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
reportConfiguration: true,
builder: (BuildContext context, RouteInformation information) {
return Text(information.uri.toString());
},
);
addTearDown(delegate.dispose);
await tester.pumpWidget(MaterialApp.router(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
));
expect(find.text('initial'), findsOneWidget);
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{
'uri': 'initial',
'state': null,
'replace': false,
}),
]);
log.clear();
// Triggers a router rebuild and verify the route information is reported
// to the web engine.
delegate.routeInformation = RouteInformation(
uri: Uri.parse('update'),
state: 'state',
);
await tester.pump();
expect(find.text('update'), findsOneWidget);
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{
'uri': 'update',
'state': 'state',
'replace': false,
}),
]);
});
}
typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext context, RouteInformation information);
typedef SimpleRouterDelegatePopRoute = Future<bool> Function();
class SimpleRouteInformationParser extends RouteInformationParser<RouteInformation> {
SimpleRouteInformationParser();
@override
Future<RouteInformation> parseRouteInformation(RouteInformation information) {
return SynchronousFuture<RouteInformation>(information);
}
@override
RouteInformation restoreRouteInformation(RouteInformation configuration) {
return configuration;
}
}
class SimpleRouterDelegate extends RouterDelegate<RouteInformation> with ChangeNotifier {
SimpleRouterDelegate({
required this.builder,
this.onPopRoute,
this.reportConfiguration = false,
}) {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
RouteInformation get routeInformation => _routeInformation;
late RouteInformation _routeInformation;
set routeInformation(RouteInformation newValue) {
_routeInformation = newValue;
notifyListeners();
}
SimpleRouterDelegateBuilder builder;
SimpleRouterDelegatePopRoute? onPopRoute;
final bool reportConfiguration;
@override
RouteInformation? get currentConfiguration {
if (reportConfiguration) {
return routeInformation;
}
return null;
}
@override
Future<void> setNewRoutePath(RouteInformation configuration) {
_routeInformation = configuration;
return SynchronousFuture<void>(null);
}
@override
Future<bool> popRoute() {
if (onPopRoute != null) {
return onPopRoute!();
}
return SynchronousFuture<bool>(true);
}
@override
Widget build(BuildContext context) => builder(context, routeInformation);
}
class TestPage extends Page<void> {
const TestPage({super.key, super.name});
@override
Route<void> createRoute(BuildContext context) {
return PageRouteBuilder<void>(
settings: this,
pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) => const Placeholder(),
);
}
}
| flutter/packages/flutter/test/widgets/route_notification_messages_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/route_notification_messages_test.dart",
"repo_id": "flutter",
"token_count": 4335
} | 725 |
// 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_test/flutter_test.dart';
class TestScrollPhysics extends ScrollPhysics {
const TestScrollPhysics({
required this.name,
super.parent,
});
final String name;
@override
TestScrollPhysics applyTo(ScrollPhysics? ancestor) {
return TestScrollPhysics(
name: name,
parent: parent?.applyTo(ancestor) ?? ancestor!,
);
}
TestScrollPhysics get namedParent => parent! as TestScrollPhysics;
String get names => parent == null ? name : '$name ${namedParent.names}';
@override
String toString() {
if (parent == null) {
return '${objectRuntimeType(this, 'TestScrollPhysics')}($name)';
}
return '${objectRuntimeType(this, 'TestScrollPhysics')}($name) -> $parent';
}
}
void main() {
test('ScrollPhysics applyTo()', () {
const TestScrollPhysics a = TestScrollPhysics(name: 'a');
const TestScrollPhysics b = TestScrollPhysics(name: 'b');
const TestScrollPhysics c = TestScrollPhysics(name: 'c');
const TestScrollPhysics d = TestScrollPhysics(name: 'd');
const TestScrollPhysics e = TestScrollPhysics(name: 'e');
expect(a.parent, null);
expect(b.parent, null);
expect(c.parent, null);
final TestScrollPhysics ab = a.applyTo(b);
expect(ab.names, 'a b');
final TestScrollPhysics abc = ab.applyTo(c);
expect(abc.names, 'a b c');
final TestScrollPhysics de = d.applyTo(e);
expect(de.names, 'd e');
final TestScrollPhysics abcde = abc.applyTo(de);
expect(abcde.names, 'a b c d e');
});
test('ScrollPhysics subclasses applyTo()', () {
const ScrollPhysics bounce = BouncingScrollPhysics();
const ScrollPhysics clamp = ClampingScrollPhysics();
const ScrollPhysics never = NeverScrollableScrollPhysics();
const ScrollPhysics always = AlwaysScrollableScrollPhysics();
const ScrollPhysics page = PageScrollPhysics();
const ScrollPhysics bounceDesktop = BouncingScrollPhysics(decelerationRate: ScrollDecelerationRate.fast);
String types(ScrollPhysics? value) => value!.parent == null ? '${value.runtimeType}' : '${value.runtimeType} ${types(value.parent)}';
expect(
types(bounce.applyTo(clamp.applyTo(never.applyTo(always.applyTo(page))))),
'BouncingScrollPhysics ClampingScrollPhysics NeverScrollableScrollPhysics AlwaysScrollableScrollPhysics PageScrollPhysics',
);
expect(
types(clamp.applyTo(never.applyTo(always.applyTo(page.applyTo(bounce))))),
'ClampingScrollPhysics NeverScrollableScrollPhysics AlwaysScrollableScrollPhysics PageScrollPhysics BouncingScrollPhysics',
);
expect(
types(never.applyTo(always.applyTo(page.applyTo(bounce.applyTo(clamp))))),
'NeverScrollableScrollPhysics AlwaysScrollableScrollPhysics PageScrollPhysics BouncingScrollPhysics ClampingScrollPhysics',
);
expect(
types(always.applyTo(page.applyTo(bounce.applyTo(clamp.applyTo(never))))),
'AlwaysScrollableScrollPhysics PageScrollPhysics BouncingScrollPhysics ClampingScrollPhysics NeverScrollableScrollPhysics',
);
expect(
types(page.applyTo(bounce.applyTo(clamp.applyTo(never.applyTo(always))))),
'PageScrollPhysics BouncingScrollPhysics ClampingScrollPhysics NeverScrollableScrollPhysics AlwaysScrollableScrollPhysics',
);
expect(
bounceDesktop.applyTo(always),
(BouncingScrollPhysics x) => x.decelerationRate == ScrollDecelerationRate.fast
);
});
test("ScrollPhysics scrolling subclasses - Creating the simulation doesn't alter the velocity for time 0", () {
final ScrollMetrics position = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 100.0,
pixels: 20.0,
viewportDimension: 500.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
const BouncingScrollPhysics bounce = BouncingScrollPhysics();
const ClampingScrollPhysics clamp = ClampingScrollPhysics();
const PageScrollPhysics page = PageScrollPhysics();
// Calls to createBallisticSimulation may happen on every frame (i.e. when the maxScrollExtent changes)
// Changing velocity for time 0 may cause a sudden, unwanted damping/speedup effect
expect(bounce.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000));
expect(clamp.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000));
expect(page.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000));
});
group('BouncingScrollPhysics test', () {
late BouncingScrollPhysics physicsUnderTest;
setUp(() {
physicsUnderTest = const BouncingScrollPhysics();
});
test('overscroll is progressively harder', () {
final ScrollMetrics lessOverscrolledPosition = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 1000.0,
pixels: -20.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
final ScrollMetrics moreOverscrolledPosition = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 1000.0,
pixels: -40.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
final double lessOverscrollApplied =
physicsUnderTest.applyPhysicsToUserOffset(lessOverscrolledPosition, 10.0);
final double moreOverscrollApplied =
physicsUnderTest.applyPhysicsToUserOffset(moreOverscrolledPosition, 10.0);
expect(lessOverscrollApplied, greaterThan(1.0));
expect(lessOverscrollApplied, lessThan(20.0));
expect(moreOverscrollApplied, greaterThan(1.0));
expect(moreOverscrollApplied, lessThan(20.0));
// Scrolling from a more overscrolled position meets more resistance.
expect(
lessOverscrollApplied.abs(),
greaterThan(moreOverscrollApplied.abs()),
);
});
test('easing an overscroll still has resistance', () {
final ScrollMetrics overscrolledPosition = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 1000.0,
pixels: -20.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
final double easingApplied =
physicsUnderTest.applyPhysicsToUserOffset(overscrolledPosition, -10.0);
expect(easingApplied, lessThan(-1.0));
expect(easingApplied, greaterThan(-10.0));
});
test('no resistance when not overscrolled', () {
final ScrollMetrics scrollPosition = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 1000.0,
pixels: 300.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
expect(
physicsUnderTest.applyPhysicsToUserOffset(scrollPosition, 10.0),
10.0,
);
expect(
physicsUnderTest.applyPhysicsToUserOffset(scrollPosition, -10.0),
-10.0,
);
});
test('easing an overscroll meets less resistance than tensioning', () {
final ScrollMetrics overscrolledPosition = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 1000.0,
pixels: -20.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
final double easingApplied =
physicsUnderTest.applyPhysicsToUserOffset(overscrolledPosition, -10.0);
final double tensioningApplied =
physicsUnderTest.applyPhysicsToUserOffset(overscrolledPosition, 10.0);
expect(easingApplied.abs(), greaterThan(tensioningApplied.abs()));
});
test('no easing resistance for ScrollDecelerationRate.fast', () {
const BouncingScrollPhysics desktop = BouncingScrollPhysics(decelerationRate: ScrollDecelerationRate.fast);
final ScrollMetrics overscrolledPosition = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 1000.0,
pixels: -20.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
final double easingApplied =
desktop.applyPhysicsToUserOffset(overscrolledPosition, -10.0);
final double tensioningApplied =
desktop.applyPhysicsToUserOffset(overscrolledPosition, 10.0);
expect(tensioningApplied.abs(), lessThan(easingApplied.abs()));
expect(easingApplied, -10);
});
test('overscroll a small list and a big list works the same way', () {
final ScrollMetrics smallListOverscrolledPosition = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 10.0,
pixels: -20.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
final ScrollMetrics bigListOverscrolledPosition = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 1000.0,
pixels: -20.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
final double smallListOverscrollApplied =
physicsUnderTest.applyPhysicsToUserOffset(smallListOverscrolledPosition, 10.0);
final double bigListOverscrollApplied =
physicsUnderTest.applyPhysicsToUserOffset(bigListOverscrolledPosition, 10.0);
expect(smallListOverscrollApplied, equals(bigListOverscrollApplied));
expect(smallListOverscrollApplied, greaterThan(1.0));
expect(smallListOverscrollApplied, lessThan(20.0));
});
test('frictionFactor', () {
const BouncingScrollPhysics mobile = BouncingScrollPhysics();
const BouncingScrollPhysics desktop = BouncingScrollPhysics(decelerationRate: ScrollDecelerationRate.fast);
expect(desktop.frictionFactor(0), 0.26);
expect(mobile.frictionFactor(0), 0.52);
expect(desktop.frictionFactor(0.4), moreOrLessEquals(0.0936));
expect(mobile.frictionFactor(0.4), moreOrLessEquals(0.1872));
expect(desktop.frictionFactor(0.8), moreOrLessEquals(0.0104));
expect(mobile.frictionFactor(0.8), moreOrLessEquals(0.0208));
});
});
test('ClampingScrollPhysics assertion test', () {
const ClampingScrollPhysics physics = ClampingScrollPhysics();
const double pixels = 500;
final ScrollMetrics position = FixedScrollMetrics(
pixels: pixels,
minScrollExtent: 0,
maxScrollExtent: 1000,
viewportDimension: 0,
axisDirection: AxisDirection.down,
devicePixelRatio: 3.0,
);
expect(position.pixels, pixels);
late FlutterError error;
try {
physics.applyBoundaryConditions(position, pixels);
} on FlutterError catch (e) {
error = e;
} finally {
expect(error, isNotNull);
expect(error.diagnostics.length, 4);
expect(error.diagnostics[2], isA<DiagnosticsProperty<ScrollPhysics>>());
expect(error.diagnostics[2].style, DiagnosticsTreeStyle.errorProperty);
expect(error.diagnostics[2].value, physics);
expect(error.diagnostics[3], isA<DiagnosticsProperty<ScrollMetrics>>());
expect(error.diagnostics[3].style, DiagnosticsTreeStyle.errorProperty);
expect(error.diagnostics[3].value, position);
// RegExp matcher is required here due to flutter web and flutter mobile generating
// slightly different floating point numbers
// in Flutter web 0.0 sometimes just appears as 0. or 0
expect(
error.toStringDeep(),
matches(RegExp(
r'''
FlutterError
ClampingScrollPhysics\.applyBoundaryConditions\(\) was called
redundantly\.
The proposed new position\, 500(\.\d*)?, is exactly equal to the current
position of the given FixedScrollMetrics, 500(\.\d*)?\.
The applyBoundaryConditions method should only be called when the
value is going to actually change the pixels, otherwise it is
redundant\.
The physics object in question was\:
ClampingScrollPhysics
The position object in question was\:
FixedScrollMetrics\(500(\.\d*)?..\[0(\.\d*)?\]..500(\.\d*)?\)
''',
multiLine: true,
)),
);
}
});
testWidgets('PageScrollPhysics work with NestedScrollView', (WidgetTester tester) async {
// Regression test for: https://github.com/flutter/flutter/issues/47850
await tester.pumpWidget(Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: NestedScrollView(
physics: const PageScrollPhysics(),
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverToBoxAdapter(child: Container(height: 300, color: Colors.blue)),
];
},
body: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Text('Index $index');
},
itemCount: 100,
),
),
),
));
await tester.fling(find.text('Index 2'), const Offset(0.0, -300.0), 10000.0);
});
}
| flutter/packages/flutter/test/widgets/scroll_physics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scroll_physics_test.dart",
"repo_id": "flutter",
"token_count": 5070
} | 726 |
// 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
Future<void> pumpTest(
WidgetTester tester,
TargetPlatform? platform, {
bool scrollable = true,
bool reverse = false,
Set<LogicalKeyboardKey>? axisModifier,
Axis scrollDirection = Axis.vertical,
ScrollController? controller,
bool enableMouseDrag = true,
}) async {
await tester.pumpWidget(MaterialApp(
scrollBehavior: const NoScrollbarBehavior().copyWith(
dragDevices: enableMouseDrag
? <ui.PointerDeviceKind>{...ui.PointerDeviceKind.values}
: null,
pointerAxisModifiers: axisModifier,
),
theme: ThemeData(
platform: platform,
),
home: CustomScrollView(
controller: controller,
reverse: reverse,
scrollDirection: scrollDirection,
physics: scrollable ? null : const NeverScrollableScrollPhysics(),
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(
height: scrollDirection == Axis.vertical ? 2000.0 : null,
width: scrollDirection == Axis.horizontal ? 2000.0 : null,
)),
],
),
));
await tester.pump(const Duration(seconds: 5)); // to let the theme animate
}
class NoScrollbarBehavior extends MaterialScrollBehavior {
const NoScrollbarBehavior();
@override
Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) => child;
}
// Pump a nested scrollable. The outer scrollable contains a sliver of a
// 300-pixel-long scrollable followed by a 2000-pixel-long content.
Future<void> pumpDoubleScrollableTest(
WidgetTester tester,
TargetPlatform platform,
) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
platform: platform,
),
home: const CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(
child: SizedBox(
height: 300,
child: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(height: 2000.0)),
],
),
),
),
SliverToBoxAdapter(child: SizedBox(height: 2000.0)),
],
),
));
await tester.pump(const Duration(seconds: 5)); // to let the theme animate
}
const double dragOffset = 200.0;
double getScrollOffset(WidgetTester tester, {bool last = true}) {
Finder viewportFinder = find.byType(Viewport);
if (last) {
viewportFinder = viewportFinder.last;
}
final RenderViewport viewport = tester.renderObject(viewportFinder);
return viewport.offset.pixels;
}
double getScrollVelocity(WidgetTester tester) {
final RenderViewport viewport = tester.renderObject(find.byType(Viewport));
final ScrollPosition position = viewport.offset as ScrollPosition;
return position.activity!.velocity;
}
void resetScrollOffset(WidgetTester tester) {
final RenderViewport viewport = tester.renderObject(find.byType(Viewport));
final ScrollPosition position = viewport.offset as ScrollPosition;
position.jumpTo(0.0);
}
void main() {
testWidgets('Flings on different platforms', (WidgetTester tester) async {
await pumpTest(tester, TargetPlatform.android);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
expect(getScrollOffset(tester), dragOffset);
await tester.pump(); // trigger fling
expect(getScrollOffset(tester), dragOffset);
await tester.pump(const Duration(seconds: 5));
final double androidResult = getScrollOffset(tester);
resetScrollOffset(tester);
await pumpTest(tester, TargetPlatform.iOS);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
// Scroll starts ease into the scroll on iOS.
expect(getScrollOffset(tester), moreOrLessEquals(197.16666666666669));
await tester.pump(); // trigger fling
expect(getScrollOffset(tester), moreOrLessEquals(197.16666666666669));
await tester.pump(const Duration(seconds: 5));
final double iOSResult = getScrollOffset(tester);
resetScrollOffset(tester);
await pumpTest(tester, TargetPlatform.macOS);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
// Scroll starts ease into the scroll on iOS.
expect(getScrollOffset(tester), moreOrLessEquals(197.16666666666669));
await tester.pump(); // trigger fling
expect(getScrollOffset(tester), moreOrLessEquals(197.16666666666669));
await tester.pump(const Duration(seconds: 5));
final double macOSResult = getScrollOffset(tester);
expect(macOSResult, lessThan(androidResult)); // macOS is slipperier than Android
expect(androidResult, lessThan(iOSResult)); // iOS is slipperier than Android
expect(macOSResult, lessThan(iOSResult)); // iOS is slipperier than macOS
});
testWidgets('Holding scroll', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
await tester.drag(find.byType(Scrollable), const Offset(0.0, 200.0), touchSlopY: 0.0);
expect(getScrollOffset(tester), -200.0);
await tester.pump(); // trigger ballistic
await tester.pump(const Duration(milliseconds: 10));
expect(getScrollOffset(tester), greaterThan(-200.0));
expect(getScrollOffset(tester), lessThan(0.0));
final double heldPosition = getScrollOffset(tester);
// Hold and let go while in overscroll.
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true));
expect(await tester.pumpAndSettle(), 1);
expect(getScrollOffset(tester), heldPosition);
await gesture.up();
// Once the hold is let go, it should still snap back to origin.
expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 3);
expect(getScrollOffset(tester), 0.0);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Repeated flings builds momentum', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
await tester.pump(); // trigger fling
await tester.pump(const Duration(milliseconds: 10));
// Repeat the exact same motion.
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
await tester.pump();
// On iOS, the velocity will be larger than the velocity of the last fling by a
// non-trivial amount.
expect(getScrollVelocity(tester), greaterThan(1100.0));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Repeated flings do not build momentum on Android', (WidgetTester tester) async {
await pumpTest(tester, TargetPlatform.android);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
await tester.pump(); // trigger fling
await tester.pump(const Duration(milliseconds: 10));
// Repeat the exact same motion.
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
await tester.pump();
// On Android, there is no momentum build. The final velocity is the same as the
// velocity of the last fling.
expect(getScrollVelocity(tester), moreOrLessEquals(1000.0));
});
testWidgets('A slower final fling does not apply carried momentum', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
await tester.pump(); // trigger fling
await tester.pump(const Duration(milliseconds: 10));
// Repeat the exact same motion to build momentum.
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
await tester.pump(); // trigger the second fling
await tester.pump(const Duration(milliseconds: 10));
// Make a final fling that is much slower.
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 200.0);
await tester.pump(); // trigger the third fling
await tester.pump(const Duration(milliseconds: 10));
// expect that there is no carried velocity
expect(getScrollVelocity(tester), lessThan(200.0));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('No iOS/macOS momentum build with flings in opposite directions', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
await tester.pump(); // trigger fling
await tester.pump(const Duration(milliseconds: 10));
// Repeat the exact same motion in the opposite direction.
await tester.fling(find.byType(Scrollable), const Offset(0.0, dragOffset), 1000.0);
await tester.pump();
// The only applied velocity to the scrollable is the second fling that was in the
// opposite direction.
expect(getScrollVelocity(tester), -1000.0);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('No iOS/macOS momentum kept on hold gestures', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
await tester.pump(); // trigger fling
await tester.pump(const Duration(milliseconds: 10));
expect(getScrollVelocity(tester), greaterThan(0.0));
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true));
await tester.pump(const Duration(milliseconds: 40));
await gesture.up();
// After a hold longer than 2 frames, previous velocity is lost.
expect(getScrollVelocity(tester), 0.0);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Drags creeping unaffected on Android', (WidgetTester tester) async {
await pumpTest(tester, TargetPlatform.android);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true));
await gesture.moveBy(const Offset(0.0, -0.5));
expect(getScrollOffset(tester), 0.5);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 10));
expect(getScrollOffset(tester), 1.0);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20));
expect(getScrollOffset(tester), 1.5);
});
testWidgets('Drags creeping must break threshold on iOS/macOS', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true));
await gesture.moveBy(const Offset(0.0, -0.5));
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 10));
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20));
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 30));
// Now -2.5 in total.
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 40));
// Now -3.5, just reached threshold.
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 50));
// -0.5 over threshold transferred.
expect(getScrollOffset(tester), 0.5);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Big drag over threshold magnitude preserved on iOS/macOS', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true));
await gesture.moveBy(const Offset(0.0, -30.0));
// No offset lost from threshold.
expect(getScrollOffset(tester), 30.0);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Slow threshold breaks are attenuated on iOS/macOS', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true));
// This is a typical 'hesitant' iOS scroll start.
await gesture.moveBy(const Offset(0.0, -10.0));
expect(getScrollOffset(tester), moreOrLessEquals(1.1666666666666667));
await gesture.moveBy(const Offset(0.0, -10.0), timeStamp: const Duration(milliseconds: 20));
// Subsequent motions unaffected.
expect(getScrollOffset(tester), moreOrLessEquals(11.16666666666666673));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Small continuing motion preserved on iOS/macOS', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true));
await gesture.moveBy(const Offset(0.0, -30.0)); // Break threshold.
expect(getScrollOffset(tester), 30.0);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20));
expect(getScrollOffset(tester), 30.5);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 40));
expect(getScrollOffset(tester), 31.0);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 60));
expect(getScrollOffset(tester), 31.5);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Motion stop resets threshold on iOS/macOS', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true));
await gesture.moveBy(const Offset(0.0, -30.0)); // Break threshold.
expect(getScrollOffset(tester), 30.0);
await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20));
expect(getScrollOffset(tester), 30.5);
await gesture.moveBy(Offset.zero, timeStamp: const Duration(milliseconds: 21));
// Stationary too long, threshold reset.
await gesture.moveBy(Offset.zero, timeStamp: const Duration(milliseconds: 120));
await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 140));
expect(getScrollOffset(tester), 30.5);
await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 150));
expect(getScrollOffset(tester), 30.5);
await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 160));
expect(getScrollOffset(tester), 30.5);
await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 170));
// New threshold broken.
expect(getScrollOffset(tester), 31.5);
await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 180));
expect(getScrollOffset(tester), 32.5);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Scroll pointer signals are handled on Fuchsia', (WidgetTester tester) async {
await pumpTest(tester, TargetPlatform.fuchsia);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport));
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(getScrollOffset(tester), 20.0);
// Pointer signals should not cause overscroll.
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -30.0)));
expect(getScrollOffset(tester), 0.0);
});
testWidgets('Scroll pointer signals are handled when there is competition', (WidgetTester tester) async {
// This is a regression test. When there are multiple scrollables listening
// to the same event, for example when scrollables are nested, there used
// to be exceptions at scrolling events.
await pumpDoubleScrollableTest(tester, TargetPlatform.fuchsia);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport).last);
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(getScrollOffset(tester), 20.0);
// Pointer signals should not cause overscroll.
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -30.0)));
expect(getScrollOffset(tester), 0.0);
});
testWidgets('Scroll pointer signals are ignored when scrolling is disabled', (WidgetTester tester) async {
await pumpTest(tester, TargetPlatform.fuchsia, scrollable: false);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport));
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(getScrollOffset(tester), 0.0);
});
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 pumpTest(tester, TargetPlatform.fuchsia, controller: controller);
controller.addListener(() {
if (controller.position.userScrollDirection != ScrollDirection.idle) {
lastUserScrollingDirection = controller.position.userScrollDirection;
}
});
await tester.drag(find.byType(Scrollable), const Offset(0.0, -20.0), touchSlopY: 0.0);
expect(lastUserScrollingDirection, ScrollDirection.reverse);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport));
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(Scrollable), 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);
});
testWidgets('Scrolls in correct direction when scroll axis is reversed', (WidgetTester tester) async {
await pumpTest(tester, TargetPlatform.fuchsia, reverse: true);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport));
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(getScrollOffset(tester), 20.0);
});
testWidgets('Scrolls horizontally when shift is pressed by default', (WidgetTester tester) async {
await pumpTest(
tester,
debugDefaultTargetPlatformOverride,
scrollDirection: Axis.horizontal,
);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport));
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)));
// Vertical input not accepted
expect(getScrollOffset(tester), 0.0);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
// Vertical input flipped to horizontal and accepted.
expect(getScrollOffset(tester), 20.0);
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
await tester.pump();
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
// Vertical input not accepted
expect(getScrollOffset(tester), 20.0);
}, variant: TargetPlatformVariant.all());
testWidgets('Scroll axis is not flipped for trackpad', (WidgetTester tester) async {
await pumpTest(
tester,
debugDefaultTargetPlatformOverride,
scrollDirection: Axis.horizontal,
);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport));
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.trackpad);
// 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)));
// Vertical input not accepted
expect(getScrollOffset(tester), 0.0);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
// Vertical input not flipped.
expect(getScrollOffset(tester), 0.0);
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
await tester.pump();
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
// Vertical input not accepted
expect(getScrollOffset(tester), 0.0);
}, variant: TargetPlatformVariant.all());
testWidgets('Scrolls horizontally when custom key is pressed', (WidgetTester tester) async {
await pumpTest(
tester,
debugDefaultTargetPlatformOverride,
scrollDirection: Axis.horizontal,
axisModifier: <LogicalKeyboardKey>{ LogicalKeyboardKey.altLeft },
);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport));
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)));
// Vertical input not accepted
expect(getScrollOffset(tester), 0.0);
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
// Vertical input flipped to horizontal and accepted.
expect(getScrollOffset(tester), 20.0);
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
// Vertical input not accepted
expect(getScrollOffset(tester), 20.0);
}, variant: TargetPlatformVariant.all());
testWidgets('Still scrolls horizontally when other keys are pressed at the same time', (WidgetTester tester) async {
await pumpTest(
tester,
debugDefaultTargetPlatformOverride,
scrollDirection: Axis.horizontal,
axisModifier: <LogicalKeyboardKey>{ LogicalKeyboardKey.altLeft },
);
final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport));
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)));
// Vertical input not accepted
expect(getScrollOffset(tester), 0.0);
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.sendKeyDownEvent(LogicalKeyboardKey.space);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
// Vertical flipped & accepted.
expect(getScrollOffset(tester), 20.0);
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.sendKeyUpEvent(LogicalKeyboardKey.space);
await tester.pump();
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
// Vertical input not accepted
expect(getScrollOffset(tester), 20.0);
}, variant: TargetPlatformVariant.all());
group('setCanDrag to false with active drag gesture: ', () {
Future<void> pumpTestWidget(WidgetTester tester, { required bool canDrag }) {
return tester.pumpWidget(
MaterialApp(
home: CustomScrollView(
physics: canDrag ? const AlwaysScrollableScrollPhysics() : const NeverScrollableScrollPhysics(),
slivers: <Widget>[
SliverToBoxAdapter(
child: SizedBox(
height: 2000,
child: GestureDetector(onTap: () {}),
),
),
],
),
),
);
}
testWidgets('Hold does not disable user interaction', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/66816.
await pumpTestWidget(tester, canDrag: true);
final RenderIgnorePointer renderIgnorePointer = tester.renderObject<RenderIgnorePointer>(
find.descendant(of: find.byType(CustomScrollView), matching: find.byType(IgnorePointer)),
);
expect(renderIgnorePointer.ignoring, false);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Viewport)));
expect(renderIgnorePointer.ignoring, false);
await pumpTestWidget(tester, canDrag: false);
expect(renderIgnorePointer.ignoring, false);
await gesture.up();
expect(renderIgnorePointer.ignoring, false);
});
testWidgets('Drag disables user interaction when recognized', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/66816.
await pumpTestWidget(tester, canDrag: true);
final RenderIgnorePointer renderIgnorePointer = tester.renderObject<RenderIgnorePointer>(
find.descendant(of: find.byType(CustomScrollView), matching: find.byType(IgnorePointer)),
);
expect(renderIgnorePointer.ignoring, false);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Viewport)));
expect(renderIgnorePointer.ignoring, false);
await gesture.moveBy(const Offset(0, -100));
// Starts ignoring when the drag is recognized.
expect(renderIgnorePointer.ignoring, true);
await pumpTestWidget(tester, canDrag: false);
expect(renderIgnorePointer.ignoring, false);
await gesture.up();
expect(renderIgnorePointer.ignoring, false);
});
testWidgets('Ballistic disables user interaction until it stops', (WidgetTester tester) async {
await pumpTestWidget(tester, canDrag: true);
final RenderIgnorePointer renderIgnorePointer = tester.renderObject<RenderIgnorePointer>(
find.descendant(of: find.byType(CustomScrollView), matching: find.byType(IgnorePointer)),
);
expect(renderIgnorePointer.ignoring, false);
// Starts ignoring when the drag is recognized.
await tester.fling(find.byType(Scrollable), const Offset(0, -100), 1000);
expect(renderIgnorePointer.ignoring, true);
await tester.pump();
// When the activity ends we should stop ignoring pointers.
await tester.pumpAndSettle();
expect(renderIgnorePointer.ignoring, false);
});
});
testWidgets('Can recommendDeferredLoadingForContext - animation', (WidgetTester tester) async {
final List<String> widgetTracker = <String>[];
int cheapWidgets = 0;
int expensiveWidgets = 0;
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
controller: controller,
itemBuilder: (BuildContext context, int index) {
if (Scrollable.recommendDeferredLoadingForContext(context)) {
cheapWidgets += 1;
widgetTracker.add('cheap');
return const SizedBox(height: 50.0);
}
widgetTracker.add('expensive');
expensiveWidgets += 1;
return const SizedBox(height: 50.0);
},
),
));
await tester.pumpAndSettle();
expect(expensiveWidgets, 17);
expect(cheapWidgets, 0);
// The position value here is different from the maximum velocity we will
// reach, which is controlled by a combination of curve, duration, and
// position.
// This is just meant to be a pretty good simulation. A linear curve
// with these same parameters will never back off on the velocity enough
// to reset here.
controller.animateTo(
5000,
duration: const Duration(seconds: 2),
curve: Curves.linear,
);
expect(expensiveWidgets, 17);
expect(widgetTracker.every((String type) => type == 'expensive'), true);
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(expensiveWidgets, 17);
expect(cheapWidgets, 25);
expect(widgetTracker.skip(17).every((String type) => type == 'cheap'), true);
await tester.pumpAndSettle();
expect(expensiveWidgets, 22);
expect(cheapWidgets, 95);
expect(widgetTracker.skip(17).skip(25).take(70).every((String type) => type == 'cheap'), true);
expect(widgetTracker.skip(17).skip(25).skip(70).every((String type) => type == 'expensive'), true);
});
testWidgets('Can recommendDeferredLoadingForContext - ballistics', (WidgetTester tester) async {
int cheapWidgets = 0;
int expensiveWidgets = 0;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
if (Scrollable.recommendDeferredLoadingForContext(context)) {
cheapWidgets += 1;
return const SizedBox(height: 50.0);
}
expensiveWidgets += 1;
return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0);
},
),
));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey<String>('Box 0')), findsOneWidget);
expect(find.byKey(const ValueKey<String>('Box 52')), findsNothing);
expect(expensiveWidgets, 17);
expect(cheapWidgets, 0);
// Getting the tester to simulate a life-like fling is difficult.
// Instead, just manually drive the activity with a ballistic simulation as
// if the user has flung the list.
Scrollable.of(find.byType(SizedBox).evaluate().first).position.activity!.delegate.goBallistic(4000);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey<String>('Box 0')), findsNothing);
expect(find.byKey(const ValueKey<String>('Box 52')), findsOneWidget);
expect(expensiveWidgets, 40);
expect(cheapWidgets, 21);
});
testWidgets('Can recommendDeferredLoadingForContext - override heuristic', (WidgetTester tester) async {
int cheapWidgets = 0;
int expensiveWidgets = 0;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
physics: SuperPessimisticScrollPhysics(),
itemBuilder: (BuildContext context, int index) {
if (Scrollable.recommendDeferredLoadingForContext(context)) {
cheapWidgets += 1;
return SizedBox(key: ValueKey<String>('Cheap box $index'), height: 50.0);
}
expensiveWidgets += 1;
return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0);
},
),
));
await tester.pumpAndSettle();
final ScrollPosition position = Scrollable.of(find.byType(SizedBox).evaluate().first).position;
final SuperPessimisticScrollPhysics physics = position.physics as SuperPessimisticScrollPhysics;
expect(find.byKey(const ValueKey<String>('Box 0')), findsOneWidget);
expect(find.byKey(const ValueKey<String>('Cheap box 52')), findsNothing);
expect(physics.count, 17);
expect(expensiveWidgets, 17);
expect(cheapWidgets, 0);
// Getting the tester to simulate a life-like fling is difficult.
// Instead, just manually drive the activity with a ballistic simulation as
// if the user has flung the list.
position.activity!.delegate.goBallistic(4000);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey<String>('Box 0')), findsNothing);
expect(find.byKey(const ValueKey<String>('Cheap box 52')), findsOneWidget);
expect(expensiveWidgets, 17);
expect(cheapWidgets, 44);
expect(physics.count, 44 + 17);
});
testWidgets('Can recommendDeferredLoadingForContext - override heuristic and always return true', (WidgetTester tester) async {
int cheapWidgets = 0;
int expensiveWidgets = 0;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
physics: const ExtraSuperPessimisticScrollPhysics(),
itemBuilder: (BuildContext context, int index) {
if (Scrollable.recommendDeferredLoadingForContext(context)) {
cheapWidgets += 1;
return SizedBox(key: ValueKey<String>('Cheap box $index'), height: 50.0);
}
expensiveWidgets += 1;
return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0);
},
),
));
await tester.pumpAndSettle();
final ScrollPosition position = Scrollable.of(find.byType(SizedBox).evaluate().first).position;
expect(find.byKey(const ValueKey<String>('Cheap box 0')), findsOneWidget);
expect(find.byKey(const ValueKey<String>('Cheap box 52')), findsNothing);
expect(expensiveWidgets, 0);
expect(cheapWidgets, 17);
// Getting the tester to simulate a life-like fling is difficult.
// Instead, just manually drive the activity with a ballistic simulation as
// if the user has flung the list.
position.activity!.delegate.goBallistic(4000);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey<String>('Cheap box 0')), findsNothing);
expect(find.byKey(const ValueKey<String>('Cheap box 52')), findsOneWidget);
expect(expensiveWidgets, 0);
expect(cheapWidgets, 61);
});
testWidgets('ensureVisible does not move PageViews', (WidgetTester tester) async {
final PageController controller = PageController();
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: PageView(
controller: controller,
children: List<ListView>.generate(
3,
(int pageIndex) {
return ListView(
key: Key('list_$pageIndex'),
children: List<Widget>.generate(
100,
(int listIndex) {
return Row(
children: <Widget>[
Container(
key: Key('${pageIndex}_${listIndex}_0'),
color: Colors.red,
width: 200,
height: 10,
),
Container(
key: Key('${pageIndex}_${listIndex}_1'),
color: Colors.blue,
width: 200,
height: 10,
),
Container(
key: Key('${pageIndex}_${listIndex}_2'),
color: Colors.green,
width: 200,
height: 10,
),
],
);
},
),
);
},
),
),
),
);
final Finder targetMidRightPage0 = find.byKey(const Key('0_25_2'));
final Finder targetMidRightPage1 = find.byKey(const Key('1_25_2'));
final Finder targetMidLeftPage1 = find.byKey(const Key('1_25_0'));
expect(find.byKey(const Key('list_0')), findsOneWidget);
expect(find.byKey(const Key('list_1')), findsNothing);
expect(targetMidRightPage0, findsOneWidget);
expect(targetMidRightPage1, findsNothing);
expect(targetMidLeftPage1, findsNothing);
await tester.ensureVisible(targetMidRightPage0);
await tester.pumpAndSettle();
expect(targetMidRightPage0, findsOneWidget);
expect(targetMidRightPage1, findsNothing);
expect(targetMidLeftPage1, findsNothing);
controller.jumpToPage(1);
await tester.pumpAndSettle();
expect(find.byKey(const Key('list_0')), findsNothing);
expect(find.byKey(const Key('list_1')), findsOneWidget);
await tester.ensureVisible(targetMidRightPage1);
await tester.pumpAndSettle();
expect(targetMidRightPage0, findsNothing);
expect(targetMidRightPage1, findsOneWidget);
expect(targetMidLeftPage1, findsOneWidget);
await tester.ensureVisible(targetMidLeftPage1);
await tester.pumpAndSettle();
expect(targetMidRightPage0, findsNothing);
expect(targetMidRightPage1, findsOneWidget);
expect(targetMidLeftPage1, findsOneWidget);
});
testWidgets('ensureVisible does not move TabViews', (WidgetTester tester) async {
final TickerProvider vsync = TestTickerProvider();
final TabController controller = TabController(
length: 3,
vsync: vsync,
);
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: TabBarView(
controller: controller,
children: List<ListView>.generate(
3,
(int pageIndex) {
return ListView(
key: Key('list_$pageIndex'),
children: List<Widget>.generate(
100,
(int listIndex) {
return Row(
children: <Widget>[
Container(
key: Key('${pageIndex}_${listIndex}_0'),
color: Colors.red,
width: 200,
height: 10,
),
Container(
key: Key('${pageIndex}_${listIndex}_1'),
color: Colors.blue,
width: 200,
height: 10,
),
Container(
key: Key('${pageIndex}_${listIndex}_2'),
color: Colors.green,
width: 200,
height: 10,
),
],
);
},
),
);
},
),
),
),
);
final Finder targetMidRightPage0 = find.byKey(const Key('0_25_2'));
final Finder targetMidRightPage1 = find.byKey(const Key('1_25_2'));
final Finder targetMidLeftPage1 = find.byKey(const Key('1_25_0'));
expect(find.byKey(const Key('list_0')), findsOneWidget);
expect(find.byKey(const Key('list_1')), findsNothing);
expect(targetMidRightPage0, findsOneWidget);
expect(targetMidRightPage1, findsNothing);
expect(targetMidLeftPage1, findsNothing);
await tester.ensureVisible(targetMidRightPage0);
await tester.pumpAndSettle();
expect(targetMidRightPage0, findsOneWidget);
expect(targetMidRightPage1, findsNothing);
expect(targetMidLeftPage1, findsNothing);
controller.index = 1;
await tester.pumpAndSettle();
expect(find.byKey(const Key('list_0')), findsNothing);
expect(find.byKey(const Key('list_1')), findsOneWidget);
await tester.ensureVisible(targetMidRightPage1);
await tester.pumpAndSettle();
expect(targetMidRightPage0, findsNothing);
expect(targetMidRightPage1, findsOneWidget);
expect(targetMidLeftPage1, findsOneWidget);
await tester.ensureVisible(targetMidLeftPage1);
await tester.pumpAndSettle();
expect(targetMidRightPage0, findsNothing);
expect(targetMidRightPage1, findsOneWidget);
expect(targetMidLeftPage1, findsOneWidget);
});
testWidgets('PointerScroll on nested NeverScrollable ListView goes to outer Scrollable.', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/70948
final ScrollController outerController = ScrollController();
addTearDown(outerController.dispose);
final ScrollController innerController = ScrollController();
addTearDown(innerController.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: SingleChildScrollView(
controller: outerController,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Column(
children: <Widget>[
for (int i = 0; i < 100; i++)
Text('SingleChildScrollView $i'),
],
),
SizedBox(
height: 3000,
width: 400,
child: ListView.builder(
controller: innerController,
physics: const NeverScrollableScrollPhysics(),
itemCount: 100,
itemBuilder: (BuildContext context, int index) {
return Text('Nested NeverScrollable ListView $index');
},
),
),
],
),
),
),
));
expect(outerController.position.pixels, 0.0);
expect(innerController.position.pixels, 0.0);
final Offset outerScrollable = tester.getCenter(find.text('SingleChildScrollView 3'));
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
// Hover over the outer scroll view and create a pointer scroll.
testPointer.hover(outerScrollable);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
await tester.pump(const Duration(milliseconds: 250));
expect(outerController.position.pixels, 20.0);
expect(innerController.position.pixels, 0.0);
final Offset innerScrollable = tester.getCenter(find.text('Nested NeverScrollable ListView 20'));
// Hover over the inner scroll view and create a pointer scroll.
// This inner scroll view is not scrollable, and so the outer should scroll.
testPointer.hover(innerScrollable);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -20.0)));
await tester.pump(const Duration(milliseconds: 250));
expect(outerController.position.pixels, 0.0);
expect(innerController.position.pixels, 0.0);
});
// Regression test for https://github.com/flutter/flutter/issues/71949
testWidgets('Zero offset pointer scroll should not trigger an assertion.', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
Widget build(double height) {
return MaterialApp(
home: Scaffold(
body: SizedBox(
width: double.infinity,
height: height,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: double.infinity,
height: 300.0,
),
),
),
),
);
}
await tester.pumpWidget(build(200.0));
expect(controller.position.pixels, 0.0);
controller.jumpTo(100.0);
expect(controller.position.pixels, 100.0);
// Make the outer constraints larger that the scrollable widget is no longer able to scroll.
await tester.pumpWidget(build(300.0));
expect(controller.position.pixels, 0.0);
expect(controller.position.maxScrollExtent, 0.0);
// Hover over the scroll view and create a zero offset pointer scroll.
final Offset scrollable = tester.getCenter(find.byType(SingleChildScrollView));
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
testPointer.hover(scrollable);
await tester.sendEventToBinding(testPointer.scroll(Offset.zero));
expect(tester.takeException(), null);
});
testWidgets('Accepts drag with unknown device kind by default', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/90912.
await tester.pumpWidget(
const MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(height: 2000.0)),
],
),
)
);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.unknown);
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pump();
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 200);
await gesture.moveBy(const Offset(0.0, 200));
await tester.pump();
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 0.0);
await gesture.removePointer();
await tester.pump();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android }));
testWidgets('Does not scroll with mouse pointer drag when behavior is configured to ignore them', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride, enableMouseDrag: false);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pump();
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, 200));
await tester.pump();
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 0.0);
await gesture.removePointer();
await tester.pump();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android }));
testWidgets("Support updating 'ScrollBehavior.dragDevices' at runtime", (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/111716
Widget buildFrame(Set<ui.PointerDeviceKind>? dragDevices) {
return MaterialApp(
scrollBehavior: const NoScrollbarBehavior().copyWith(
dragDevices: dragDevices,
),
home: ListView.builder(
itemCount: 1000,
itemBuilder: (BuildContext context, int index) {
return Text('Item $index');
},
),
);
}
await tester.pumpWidget(buildFrame(<ui.PointerDeviceKind>{ui.PointerDeviceKind.mouse}));
await tester.drag(find.byType(Scrollable), const Offset(0.0, -100.0), kind: ui.PointerDeviceKind.mouse);
// Matching device should allow user scrolling.
expect(getScrollOffset(tester), 100.0);
await tester.pumpWidget(buildFrame(<ui.PointerDeviceKind>{ui.PointerDeviceKind.stylus}));
await tester.drag(find.byType(Scrollable), const Offset(0.0, -100.0), kind: ui.PointerDeviceKind.mouse);
// Non-matching device should not allow user scrolling.
expect(getScrollOffset(tester), 100.0);
await tester.drag(find.byType(Scrollable), const Offset(0.0, -100.0), kind: ui.PointerDeviceKind.stylus);
// Matching device should allow user scrolling.
expect(getScrollOffset(tester), 200.0);
});
testWidgets('Does scroll with mouse pointer drag when behavior is not configured to ignore them', (WidgetTester tester) async {
await pumpTest(tester, debugDefaultTargetPlatformOverride);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pump();
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 200.0);
await gesture.moveBy(const Offset(0.0, 200));
await tester.pump();
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 0.0);
await gesture.removePointer();
await tester.pump();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android }));
testWidgets('Updated content dimensions correctly reflect in semantics', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/40419.
final SemanticsHandle handle = tester.ensureSemantics();
final UniqueKey listView = UniqueKey();
await tester.pumpWidget(MaterialApp(
home: TickerMode(
enabled: true,
child: ListView.builder(
key: listView,
itemCount: 100,
itemBuilder: (BuildContext context, int index) {
return Text('Item $index');
},
),
),
));
SemanticsNode scrollableNode = tester.getSemantics(find.descendant(of: find.byKey(listView), matching: find.byType(RawGestureDetector)));
SemanticsNode? syntheticScrollableNode;
scrollableNode.visitChildren((SemanticsNode node) {
syntheticScrollableNode = node;
return true;
});
expect(syntheticScrollableNode!.hasFlag(ui.SemanticsFlag.hasImplicitScrolling), isTrue);
// Disabled the ticker mode to trigger didChangeDependencies on Scrollable.
// This can happen when a route is push or pop from top.
// It will reconstruct the scroll position and apply content dimensions.
await tester.pumpWidget(MaterialApp(
home: TickerMode(
enabled: false,
child: ListView.builder(
key: listView,
itemCount: 100,
itemBuilder: (BuildContext context, int index) {
return Text('Item $index');
},
),
),
));
await tester.pump();
// The correct workflow will be the following:
// 1. _RenderScrollSemantics receives a new scroll position without content
// dimensions and creates a SemanticsNode without implicit scroll.
// 2. The content dimensions are applied to the scroll position during the
// layout phase, and the scroll position marks the semantics node of
// _RenderScrollSemantics dirty.
// 3. The _RenderScrollSemantics rebuilds its semantics node with implicit
// scroll.
scrollableNode = tester.getSemantics(find.descendant(of: find.byKey(listView), matching: find.byType(RawGestureDetector)));
syntheticScrollableNode = null;
scrollableNode.visitChildren((SemanticsNode node) {
syntheticScrollableNode = node;
return true;
});
expect(syntheticScrollableNode!.hasFlag(ui.SemanticsFlag.hasImplicitScrolling), isTrue);
handle.dispose();
});
testWidgets('Two panel semantics is added to the sibling nodes of direct children', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
final UniqueKey key = UniqueKey();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: ListView(
key: key,
children: const <Widget>[
TextField(
autofocus: true,
decoration: InputDecoration(
prefixText: 'prefix',
),
),
],
),
),
));
// Wait for focus.
await tester.pumpAndSettle();
final SemanticsNode scrollableNode = tester.getSemantics(find.byKey(key));
SemanticsNode? intermediateNode;
scrollableNode.visitChildren((SemanticsNode node) {
intermediateNode = node;
return true;
});
SemanticsNode? syntheticScrollableNode;
intermediateNode!.visitChildren((SemanticsNode node) {
syntheticScrollableNode = node;
return true;
});
expect(syntheticScrollableNode!.hasFlag(ui.SemanticsFlag.hasImplicitScrolling), isTrue);
int numberOfChild = 0;
syntheticScrollableNode!.visitChildren((SemanticsNode node) {
expect(node.isTagged(RenderViewport.useTwoPaneSemantics), isTrue);
numberOfChild += 1;
return true;
});
expect(numberOfChild, 2);
handle.dispose();
});
testWidgets('Scroll inertia cancel event', (WidgetTester tester) async {
await pumpTest(tester, null);
await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0);
expect(getScrollOffset(tester), dragOffset);
await tester.pump(); // trigger fling
expect(getScrollOffset(tester), dragOffset);
await tester.pump(const Duration(milliseconds: 200));
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
await tester.sendEventToBinding(testPointer.hover(tester.getCenter(find.byType(Scrollable))));
await tester.sendEventToBinding(testPointer.scrollInertiaCancel()); // Cancel partway through.
await tester.pump();
expect(getScrollOffset(tester), closeTo(344.0642, 0.0001));
await tester.pump(const Duration(milliseconds: 4800));
expect(getScrollOffset(tester), closeTo(344.0642, 0.0001));
});
testWidgets('Swapping viewports in a scrollable does not crash', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final GlobalKey key = GlobalKey();
final GlobalKey key1 = GlobalKey();
Widget buildScrollable(bool withViewPort) {
return Scrollable(
key: key,
viewportBuilder: (BuildContext context, ViewportOffset position) {
if (withViewPort) {
final ViewportOffset offset = ViewportOffset.zero();
addTearDown(() => offset.dispose());
return Viewport(
slivers: <Widget>[
SliverToBoxAdapter(child: Semantics(key: key1, container: true, child: const Text('text1')))
],
offset: offset,
);
}
return Semantics(key: key1, container: true, child: const Text('text1'));
},
);
}
// This should cache the inner node in Scrollable with the children text1.
await tester.pumpWidget(
MaterialApp(
home: buildScrollable(true),
),
);
expect(semantics, includesNodeWith(tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics}));
// This does not use two panel, this should clear cached inner node.
await tester.pumpWidget(
MaterialApp(
home: buildScrollable(false),
),
);
expect(semantics, isNot(includesNodeWith(tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics})));
// If the inner node was cleared in the previous step, this should not crash.
await tester.pumpWidget(
MaterialApp(
home: buildScrollable(true),
),
);
expect(semantics, includesNodeWith(tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics}));
expect(tester.takeException(), isNull);
semantics.dispose();
});
testWidgets('deltaToScrollOrigin getter', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(height: 2000.0)),
],
),
)
);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.unknown);
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pump();
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 200);
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
expect(scrollable.deltaToScrollOrigin, const Offset(0.0, 200));
});
testWidgets('resolvedPhysics getter', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light().copyWith(
platform: TargetPlatform.android,
),
home: const CustomScrollView(
physics: AlwaysScrollableScrollPhysics(),
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(height: 2000.0)),
],
),
)
);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.unknown);
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pump();
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 200);
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
String types(ScrollPhysics? value) => value!.parent == null ? '${value.runtimeType}' : '${value.runtimeType} ${types(value.parent)}';
expect(
types(scrollable.resolvedPhysics),
'AlwaysScrollableScrollPhysics ClampingScrollPhysics RangeMaintainingScrollPhysics',
);
});
testWidgets('dragDevices change updates widget', (WidgetTester tester) async {
bool enable = false;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Scaffold(
body: Scrollable(
scrollBehavior: const MaterialScrollBehavior().copyWith(dragDevices: <ui.PointerDeviceKind>{
if (enable) ui.PointerDeviceKind.mouse,
}),
viewportBuilder: (BuildContext context, ViewportOffset position) => Viewport(
offset: position,
slivers: const <Widget>[
SliverToBoxAdapter(child: SizedBox(height: 2000.0)),
],
),
),
floatingActionButton: FloatingActionButton(onPressed: () {
setState(() {
enable = !enable;
});
}),
),
);
},
);
},
)
);
// Gesture should not work.
TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse);
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 0.0);
// Change state to include mouse pointer device.
await tester.tap(find.byType(FloatingActionButton));
await tester.pump();
// Gesture should work after state change.
gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse);
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 200);
});
testWidgets('dragDevices change updates widget when oldWidget scrollBehavior is null', (WidgetTester tester) async {
ScrollBehavior? scrollBehavior;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Scaffold(
body: Scrollable(
physics: const ScrollPhysics(),
scrollBehavior: scrollBehavior,
viewportBuilder: (BuildContext context, ViewportOffset position) => Viewport(
offset: position,
slivers: const <Widget>[
SliverToBoxAdapter(child: SizedBox(height: 2000.0)),
],
),
),
floatingActionButton: FloatingActionButton(onPressed: () {
setState(() {
scrollBehavior = const MaterialScrollBehavior().copyWith(dragDevices: <ui.PointerDeviceKind>{
ui.PointerDeviceKind.mouse
});
});
}),
),
);
},
);
},
)
);
// Gesture should not work.
TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse);
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 0.0);
// Change state to include mouse pointer device.
await tester.tap(find.byType(FloatingActionButton));
await tester.pump();
// Gesture should work after state change.
gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse);
expect(getScrollOffset(tester), 0.0);
await gesture.moveBy(const Offset(0.0, -200));
await tester.pumpAndSettle();
expect(getScrollOffset(tester), 200);
});
}
// ignore: must_be_immutable
class SuperPessimisticScrollPhysics extends ScrollPhysics {
SuperPessimisticScrollPhysics({super.parent});
int count = 0;
@override
bool recommendDeferredLoading(double velocity, ScrollMetrics metrics, BuildContext context) {
count++;
return velocity > 1;
}
@override
ScrollPhysics applyTo(ScrollPhysics? ancestor) {
return SuperPessimisticScrollPhysics(parent: buildParent(ancestor));
}
}
class ExtraSuperPessimisticScrollPhysics extends ScrollPhysics {
const ExtraSuperPessimisticScrollPhysics({super.parent});
@override
bool recommendDeferredLoading(double velocity, ScrollMetrics metrics, BuildContext context) {
return true;
}
@override
ScrollPhysics applyTo(ScrollPhysics? ancestor) {
return ExtraSuperPessimisticScrollPhysics(parent: buildParent(ancestor));
}
}
class TestTickerProvider extends TickerProvider {
@override
Ticker createTicker(TickerCallback onTick) {
return Ticker(onTick);
}
}
| flutter/packages/flutter/test/widgets/scrollable_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scrollable_test.dart",
"repo_id": "flutter",
"token_count": 24363
} | 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
group('BlockSemantics', () {
testWidgets('hides semantic nodes of siblings', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
Semantics(
label: 'layer#1',
textDirection: TextDirection.ltr,
child: Container(),
),
const BlockSemantics(),
Semantics(
label: 'layer#2',
textDirection: TextDirection.ltr,
child: Container(),
),
],
));
expect(semantics, isNot(includesNodeWith(label: 'layer#1')));
await tester.pumpWidget(Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
Semantics(
label: 'layer#1',
textDirection: TextDirection.ltr,
child: Container(),
),
],
));
expect(semantics, includesNodeWith(label: 'layer#1'));
semantics.dispose();
});
testWidgets('does not hides semantic nodes of siblings outside the current semantic boundary', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: Stack(
children: <Widget>[
Semantics(
label: '#1',
child: Container(),
),
Semantics(
label: '#2',
container: true,
explicitChildNodes: true,
child: Stack(
children: <Widget>[
Semantics(
label: 'NOT#2.1',
child: Container(),
),
Semantics(
label: '#2.2',
child: BlockSemantics(
child: Semantics(
container: true,
label: '#2.2.1',
child: Container(),
),
),
),
Semantics(
label: '#2.3',
child: Container(),
),
],
),
),
Semantics(
label: '#3',
child: Container(),
),
],
)));
expect(semantics, includesNodeWith(label: '#1'));
expect(semantics, includesNodeWith(label: '#2'));
expect(semantics, isNot(includesNodeWith(label:'NOT#2.1')));
expect(semantics, includesNodeWith(label: '#2.2'));
expect(semantics, includesNodeWith(label: '#2.2.1'));
expect(semantics, includesNodeWith(label: '#2.3'));
expect(semantics, includesNodeWith(label: '#3'));
semantics.dispose();
});
testWidgets('node is semantic boundary and blocking previously painted nodes', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final GlobalKey stackKey = GlobalKey();
await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: Stack(
key: stackKey,
children: <Widget>[
Semantics(
label: 'NOT#1',
child: Container(),
),
BoundaryBlockSemantics(
child: Semantics(
label: '#2.1',
child: Container(),
),
),
Semantics(
label: '#3',
child: Container(),
),
],
)));
expect(semantics, isNot(includesNodeWith(label: 'NOT#1')));
expect(semantics, includesNodeWith(label: '#2.1'));
expect(semantics, includesNodeWith(label: '#3'));
semantics.dispose();
});
});
}
class BoundaryBlockSemantics extends SingleChildRenderObjectWidget {
const BoundaryBlockSemantics({ super.key, required Widget super.child });
@override
RenderBoundaryBlockSemantics createRenderObject(BuildContext context) => RenderBoundaryBlockSemantics();
}
class RenderBoundaryBlockSemantics extends RenderProxyBox {
RenderBoundaryBlockSemantics();
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
config
..isBlockingSemanticsOfPreviouslyPaintedNodes = true
..isSemanticBoundary = true;
}
}
| flutter/packages/flutter/test/widgets/semantics_9_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_9_test.dart",
"repo_id": "flutter",
"token_count": 2205
} | 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.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class Changer extends StatefulWidget {
const Changer({ super.key });
@override
ChangerState createState() => ChangerState();
}
class ChangerState extends State<Changer> {
void test0() { setState(() { }); }
void test1() { setState(() => 1); }
void test2() { setState(() async { }); }
@override
Widget build(BuildContext context) => const Text('test', textDirection: TextDirection.ltr);
}
void main() {
testWidgets('setState() catches being used with an async callback', (WidgetTester tester) async {
await tester.pumpWidget(const Changer());
final ChangerState s = tester.state(find.byType(Changer));
expect(s.test0, isNot(throwsFlutterError));
expect(s.test1, isNot(throwsFlutterError));
expect(s.test2, throwsFlutterError);
});
}
| flutter/packages/flutter/test/widgets/set_state_4_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/set_state_4_test.dart",
"repo_id": "flutter",
"token_count": 338
} | 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:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
// Helpers
final Widget sliverBox = SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: 150.0,
width: 150,
),
);
Widget boilerplate(
List<Widget> slivers, {
ScrollController? controller,
Axis scrollDirection = Axis.vertical,
}) {
return MaterialApp(
theme: ThemeData(
useMaterial3: false,
materialTapTargetSize: MaterialTapTargetSize.padded,
),
home: Scaffold(
body: CustomScrollView(
scrollDirection: scrollDirection,
slivers: slivers,
controller: controller,
),
),
);
}
group('SliverFillRemaining', () {
group('hasScrollBody: true, default', () {
testWidgets('no siblings', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
SliverFillRemaining(child: Container()),
],
),
),
);
expect(
tester.renderObject<RenderBox>(find.byType(Container)).size.height,
equals(600.0),
);
controller.jumpTo(50.0);
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byType(Container)).size.height,
equals(600.0),
);
controller.jumpTo(-100.0);
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byType(Container)).size.height,
equals(600.0),
);
controller.jumpTo(0.0);
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byType(Container)).size.height,
equals(600.0),
);
});
testWidgets('one sibling', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
const SliverToBoxAdapter(child: SizedBox(height: 100.0)),
SliverFillRemaining(child: Container()),
],
),
),
);
expect(
tester.renderObject<RenderBox>(find.byType(Container)).size.height,
equals(500.0),
);
controller.jumpTo(50.0);
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byType(Container)).size.height,
equals(550.0),
);
controller.jumpTo(-100.0);
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byType(Container)).size.height,
equals(400.0),
);
controller.jumpTo(0.0);
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byType(Container)).size.height,
equals(500.0),
);
});
testWidgets('scrolls beyond viewportMainAxisExtent', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
child: Container(color: Colors.white),
),
];
await tester.pumpWidget(boilerplate(slivers, controller: controller));
expect(controller.offset, 0.0);
expect(find.byType(Container), findsNWidgets(2));
controller.jumpTo(150.0);
await tester.pumpAndSettle();
expect(controller.offset, 150.0);
expect(find.byType(Container), findsOneWidget);
});
group('has correct semantics when', () {
testWidgets('within viewport', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight - 100,
width: 150,
),
),
// This sliver is within viewport
const SliverFillRemaining(
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is within the viewport, semantic nodes for
// it are created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsOne);
expect(textInSliverFillRemaining, containsSemantics(isHidden: false));
handle.dispose();
});
testWidgets('outside of viewport but within cache extent', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
// This sliver takes up entire viewport and leaves 250 remaining cacheExtent
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight,
width: 150,
),
),
// This sliver is not within viewport but is within remaining cacheExtent
const SliverFillRemaining(
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is not in viewport, but is within
// cacheExtent, hidden semantic nodes for it are created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsOne);
expect(textInSliverFillRemaining, containsSemantics(isHidden: true));
handle.dispose();
});
testWidgets('outside of viewport and not within cache extent', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
// This sliver takes up entire viewport and leaves 0 remaining cacheExtent
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight + cacheExtent,
width: 150,
),
),
// This sliver is not within viewport and not within remaining cacheExtent
const SliverFillRemaining(
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is not in viewport and not within
// cacheExtent, semantic nodes are not created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsNothing);
handle.dispose();
});
});
});
group('hasScrollBody: false', () {
testWidgets('does not extend past viewportMainAxisExtent', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
child: Container(color: Colors.white),
),
];
await tester.pumpWidget(boilerplate(slivers, controller: controller));
expect(controller.offset, 0.0);
expect(find.byType(Container), findsNWidgets(2));
controller.jumpTo(150.0);
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(find.byType(Container), findsNWidgets(2));
});
testWidgets('child without size is sized by extent', (WidgetTester tester) async {
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
child: Container(color: Colors.blue),
),
];
await tester.pumpWidget(boilerplate(slivers));
RenderBox box = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box.size.height, equals(450));
await tester.pumpWidget(boilerplate(
slivers,
scrollDirection: Axis.horizontal,
));
box = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box.size.width, equals(650));
});
testWidgets('child with smaller size is sized by extent', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
child: ColoredBox(
key: key,
color: Colors.blue,
child: Align(
alignment: Alignment.bottomCenter,
child: ElevatedButton(
child: const Text('bottomCenter button'),
onPressed: () {},
),
),
),
),
];
await tester.pumpWidget(boilerplate(slivers));
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
// Also check that the button alignment is true to expectations
final Finder button = find.byType(ElevatedButton);
expect(tester.getBottomLeft(button).dy, equals(600.0));
expect(tester.getCenter(button).dx, equals(400.0));
// Check Axis.horizontal
await tester.pumpWidget(boilerplate(
slivers,
scrollDirection: Axis.horizontal,
));
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.width,
equals(650),
);
});
testWidgets('extent is overridden by child with larger size', (WidgetTester tester) async {
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
child: Container(
color: Colors.blue,
height: 600,
width: 1000,
),
),
];
await tester.pumpWidget(boilerplate(slivers));
RenderBox box = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box.size.height, equals(600));
await tester.pumpWidget(boilerplate(
slivers,
scrollDirection: Axis.horizontal,
));
box = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box.size.width, equals(1000));
});
testWidgets('extent is overridden by child size if precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final List<Widget> slivers = <Widget>[
SliverFixedExtentList(
itemExtent: 150,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) => Container(color: Colors.amber),
childCount: 5,
),
),
SliverFillRemaining(
hasScrollBody: false,
child: Container(
key: key,
color: Colors.blue[300],
child: Align(
child: Padding(
padding: const EdgeInsets.all(50.0),
child: ElevatedButton(
child: const Text('center button'),
onPressed: () {},
),
),
),
),
),
];
await tester.pumpWidget(boilerplate(slivers));
await tester.drag(find.byType(Scrollable), const Offset(0.0, -750.0));
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(148.0),
);
// Also check that the button alignment is true to expectations
final Finder button = find.byType(ElevatedButton);
expect(tester.getBottomLeft(button).dy, equals(550.0));
expect(tester.getCenter(button).dx, equals(400.0));
});
testWidgets('alignment with a flexible works', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
child: Column(
key: key,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Flexible(
child: Center(child: FlutterLogo(size: 100)),
),
ElevatedButton(
child: const Text('Bottom'),
onPressed: () {},
),
],
),
),
];
await tester.pumpWidget(boilerplate(slivers));
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
// Check that the logo alignment is true to expectations
final Finder logo = find.byType(FlutterLogo);
expect(
tester.renderObject<RenderBox>(logo).size,
const Size(100.0, 100.0),
);
final VisualDensity density = VisualDensity.adaptivePlatformDensity;
expect(tester.getCenter(logo), Offset(400.0, 351.0 - density.vertical * 2.0));
// Also check that the button alignment is true to expectations
// Buttons do not decrease their horizontal padding per the VisualDensity.
final Finder button = find.byType(ElevatedButton);
expect(
tester.renderObject<RenderBox>(button).size,
Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0),
);
expect(tester.getBottomLeft(button).dy, equals(600.0));
expect(tester.getCenter(button).dx, equals(400.0));
// Overscroll and see that alignment and size is maintained
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
expect(
tester.renderObject<RenderBox>(logo).size,
const Size(100.0, 100.0),
);
expect(tester.getCenter(logo).dy, lessThan(351.0));
expect(
tester.renderObject<RenderBox>(button).size,
// Buttons do not decrease their horizontal padding per the VisualDensity.
Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0),
);
expect(tester.getBottomLeft(button).dy, lessThan(600.0));
expect(tester.getCenter(button).dx, equals(400.0));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
group('has correct semantics when', () {
testWidgets('within viewport', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight - 100,
width: 150,
),
),
// This sliver is within viewport
const SliverFillRemaining(
hasScrollBody: false,
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is within the viewport, semantic nodes for
// it are created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsOne);
expect(textInSliverFillRemaining, containsSemantics(isHidden: false));
handle.dispose();
});
testWidgets('outside of viewport but within cache extent', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
// This sliver takes up entire viewport and leaves 250 remaining cacheExtent
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight,
width: 150,
),
),
// This sliver is not within viewport but is within remaining cacheExtent
const SliverFillRemaining(
hasScrollBody: false,
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is not in viewport, but is within
// cacheExtent, hidden semantic nodes for it are created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsOne);
expect(textInSliverFillRemaining, containsSemantics(isHidden: true));
handle.dispose();
});
testWidgets('outside of viewport and not within cache extent', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
// This sliver takes up entire viewport and leaves 0 remaining cacheExtent
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight + cacheExtent,
width: 150,
),
),
// This sliver is not within viewport and not within remaining cacheExtent
const SliverFillRemaining(
hasScrollBody: false,
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is not in viewport and not within
// cacheExtent, semantic nodes are not created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsNothing);
handle.dispose();
});
});
group('fillOverscroll: true, relevant platforms', () {
testWidgets('child without size is sized by extent and overscroll', (WidgetTester tester) async {
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: Container(color: Colors.blue),
),
];
// Check size
await tester.pumpWidget(boilerplate(slivers));
final RenderBox box1 = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box1.size.height, equals(450));
// Overscroll and check size
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
final RenderBox box2 = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box2.size.height, greaterThan(450));
// Ensure overscroll retracts to original size after releasing gesture
await tester.pumpAndSettle();
final RenderBox box3 = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box3.size.height, equals(450));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('child with smaller size is overridden and sized by extent and overscroll', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: ColoredBox(
key: key,
color: Colors.blue,
child: Align(
alignment: Alignment.bottomCenter,
child: ElevatedButton(
child: const Text('bottomCenter button'),
onPressed: () {},
),
),
),
),
];
await tester.pumpWidget(boilerplate(slivers));
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
greaterThan(450),
);
// Also check that the button alignment is true to expectations, even with
// child stretching to fill overscroll
final Finder button = find.byType(ElevatedButton);
expect(tester.getBottomLeft(button).dy, equals(600.0));
expect(tester.getCenter(button).dx, equals(400.0));
// Ensure overscroll retracts to original size after releasing gesture
await tester.pumpAndSettle();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('extent is overridden by child size and overscroll if precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<Widget> slivers = <Widget>[
SliverFixedExtentList(
itemExtent: 150,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) =>
Container(color: Colors.amber),
childCount: 5,
),
),
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: Container(
key: key,
color: Colors.blue[300],
child: Align(
child: Padding(
padding: const EdgeInsets.all(50.0),
child: ElevatedButton(
child: const Text('center button'),
onPressed: () {},
),
),
),
),
),
];
await tester.pumpWidget(boilerplate(slivers, controller: controller));
// Scroll to the end
controller.jumpTo(controller.position.maxScrollExtent);
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(148.0 + VisualDensity.adaptivePlatformDensity.vertical * 4.0),
);
// Check that the button alignment is true to expectations
final Finder button = find.byType(ElevatedButton);
expect(tester.getBottomLeft(button).dy, equals(550.0));
expect(tester.getCenter(button).dx, equals(400.0));
// Drag for overscroll
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
greaterThan(148.0),
);
// Check that the button alignment is still centered in stretched child
expect(tester.getBottomLeft(button).dy, lessThan(550.0));
expect(tester.getCenter(button).dx, equals(400.0));
// Ensure overscroll retracts to original size after releasing gesture
await tester.pumpAndSettle();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(148.0 + VisualDensity.adaptivePlatformDensity.vertical * 4.0),
);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('fillOverscroll works when child has no size and precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<Widget> slivers = <Widget>[
SliverFixedExtentList(
itemExtent: 150,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Semantics(label: index.toString(), child: Container(color: Colors.amber));
},
childCount: 5,
),
),
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: Container(
key: key,
color: Colors.blue,
),
),
];
await tester.pumpWidget(boilerplate(slivers, controller: controller));
expect(find.byKey(key), findsNothing);
expect(
find.bySemanticsLabel('4'),
findsNothing,
);
// Scroll to bottom
controller.jumpTo(controller.position.maxScrollExtent);
await tester.pump();
// Check item at the end of the list
expect(find.byKey(key), findsNothing);
expect(
find.bySemanticsLabel('4'),
findsOneWidget,
);
// Overscroll
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
// Check for new item at the end of the now overscrolled list
expect(find.byKey(key), findsOneWidget);
expect(
find.bySemanticsLabel('4'),
findsOneWidget,
);
// Ensure overscroll retracts to original size after releasing gesture
await tester.pumpAndSettle();
expect(find.byKey(key), findsNothing);
expect(
find.bySemanticsLabel('4'),
findsOneWidget,
);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('alignment with a flexible works with fillOverscroll', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: Column(
key: key,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Flexible(
child: Center(child: FlutterLogo(size: 100)),
),
ElevatedButton(
child: const Text('Bottom'),
onPressed: () {},
),
],
),
),
];
await tester.pumpWidget(boilerplate(slivers));
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
// Check that the logo alignment is true to expectations.
final Finder logo = find.byType(FlutterLogo);
expect(
tester.renderObject<RenderBox>(logo).size,
const Size(100.0, 100.0),
);
final VisualDensity density = VisualDensity.adaptivePlatformDensity;
expect(tester.getCenter(logo), Offset(400.0, 351.0 - density.vertical * 2.0));
// Also check that the button alignment is true to expectations.
// Buttons do not decrease their horizontal padding per the VisualDensity.
final Finder button = find.byType(ElevatedButton);
expect(
tester.renderObject<RenderBox>(button).size,
Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0),
);
expect(tester.getBottomLeft(button).dy, equals(600.0));
expect(tester.getCenter(button).dx, equals(400.0));
// Overscroll and see that logo alignment shifts to maintain center as
// container stretches with overscroll, button remains aligned at the
// bottom.
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
greaterThan(450),
);
expect(
tester.renderObject<RenderBox>(logo).size,
const Size(100.0, 100.0),
);
expect(tester.getCenter(logo).dy, lessThan(351.0));
expect(
tester.renderObject<RenderBox>(button).size,
// Buttons do not decrease their horizontal padding per the VisualDensity.
Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0),
);
expect(tester.getBottomLeft(button).dy, equals(600.0));
expect(tester.getCenter(button).dx, equals(400.0));
// Ensure overscroll retracts to original position when gesture is
// released.
await tester.pumpAndSettle();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
expect(
tester.renderObject<RenderBox>(logo).size,
const Size(100.0, 100.0),
);
expect(tester.getCenter(logo), Offset(400.0, 351.0 - density.vertical * 2.0));
expect(
tester.renderObject<RenderBox>(button).size,
// Buttons do not decrease their horizontal padding per the VisualDensity.
Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0),
);
expect(tester.getBottomLeft(button).dy, equals(600.0));
expect(tester.getCenter(button).dx, equals(400.0));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
group('has correct semantics when', () {
testWidgets('within viewport', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight - 100,
width: 150,
),
),
// This sliver is within viewport
const SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is within the viewport, semantic nodes for
// it are created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsOne);
expect(textInSliverFillRemaining, containsSemantics(isHidden: false));
handle.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('outside of viewport but within cache extent', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
// This sliver takes up entire viewport and leaves 250 remaining cacheExtent
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight,
width: 150,
),
),
// This sliver is not within viewport but is within remaining cacheExtent
const SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is not in viewport, but is within
// cacheExtent, hidden semantic nodes for it are created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsOne);
expect(textInSliverFillRemaining, containsSemantics(isHidden: true));
handle.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('outside of viewport and not within cache extent', (WidgetTester tester) async {
// Viewport is 800x600
const double viewportHeight = 600;
const double cacheExtent = 250;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
cacheExtent: cacheExtent,
slivers: <Widget>[
// This sliver takes up entire viewport and leaves 0 remaining cacheExtent
SliverToBoxAdapter(
child: Container(
color: Colors.amber,
height: viewportHeight + cacheExtent,
width: 150,
),
),
// This sliver is not within viewport and not within remaining cacheExtent
const SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: SizedBox(
height: 100,
child: Text('Text in SliverFillRemaining'),
),
),
],
),
),
);
// When SliverFillRemaining is not in viewport and not within
// cacheExtent, semantic nodes are not created.
final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel(
'Text in SliverFillRemaining',
);
expect(textInSliverFillRemaining, findsNothing);
handle.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
});
});
group('fillOverscroll: true, is ignored on irrelevant platforms', () {
// Android/Other scroll physics when hasScrollBody: false, ignores fillOverscroll: true
testWidgets('child without size is sized by extent', (WidgetTester tester) async {
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: Container(color: Colors.blue),
),
];
await tester.pumpWidget(boilerplate(slivers));
final RenderBox box1 = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box1.size.height, equals(450));
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
final RenderBox box2 = tester.renderObject<RenderBox>(find.byType(Container).last);
expect(box2.size.height, equals(450));
});
testWidgets('child with size is overridden and sized by extent', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final List<Widget> slivers = <Widget>[
sliverBox,
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: ColoredBox(
key: key,
color: Colors.blue,
child: Align(
alignment: Alignment.bottomCenter,
child: ElevatedButton(
child: const Text('bottomCenter button'),
onPressed: () {},
),
),
),
),
];
await tester.pumpWidget(boilerplate(slivers));
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(450),
);
// Also check that the button alignment is true to expectations
final Finder button = find.byType(ElevatedButton);
expect(tester.getBottomLeft(button).dy, equals(600.0));
expect(tester.getCenter(button).dx, equals(400.0));
});
testWidgets('extent is overridden by child size if precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<Widget> slivers = <Widget>[
SliverFixedExtentList(
itemExtent: 150,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) =>
Container(color: Colors.amber),
childCount: 5,
),
),
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: Container(
key: key,
color: Colors.blue[300],
child: Align(
child: Padding(
padding: const EdgeInsets.all(50.0),
child: ElevatedButton(
child: const Text('center button'),
onPressed: () {},
),
),
),
),
),
];
await tester.pumpWidget(boilerplate(slivers, controller: controller));
// Scroll to the end
controller.jumpTo(controller.position.maxScrollExtent);
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(148.0),
);
// Check that the button alignment is true to expectations
final Finder button = find.byType(ElevatedButton);
expect(tester.getBottomLeft(button).dy, equals(550.0));
expect(tester.getCenter(button).dx, equals(400.0));
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
expect(
tester.renderObject<RenderBox>(find.byKey(key)).size.height,
equals(148.0),
);
// Check that the button alignment is still centered
expect(tester.getBottomLeft(button).dy, equals(550.0));
expect(tester.getCenter(button).dx, equals(400.0));
});
testWidgets('child has no size and precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<Widget> slivers = <Widget>[
SliverFixedExtentList(
itemExtent: 150,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Semantics(label: index.toString(), child: Container(color: Colors.amber));
},
childCount: 5,
),
),
SliverFillRemaining(
hasScrollBody: false,
fillOverscroll: true,
child: Container(
key: key,
color: Colors.blue,
),
),
];
await tester.pumpWidget(boilerplate(slivers, controller: controller));
expect(find.byKey(key), findsNothing);
expect(
find.bySemanticsLabel('4'),
findsNothing,
);
// Scroll to bottom
controller.jumpTo(controller.position.maxScrollExtent);
await tester.pump();
// End of list
expect(find.byKey(key), findsNothing);
expect(
find.bySemanticsLabel('4'),
findsOneWidget,
);
// Overscroll
await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0));
await tester.pump();
expect(find.byKey(key), findsNothing);
expect(
find.bySemanticsLabel('4'),
findsOneWidget,
);
});
});
});
});
}
| flutter/packages/flutter/test/widgets/sliver_fill_remaining_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/sliver_fill_remaining_test.dart",
"repo_id": "flutter",
"token_count": 22908
} | 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 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Sliver with keep alive without key - should dispose after reordering', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
const WidgetTest0(text: 'child 0', keepAlive: true),
const WidgetTest1(text: 'child 1', keepAlive: true),
const WidgetTest2(text: 'child 2', keepAlive: true),
];
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsNothing);
expect(state0.hasBeenDisposed, true);
expect(state2.hasBeenDisposed, false);
});
testWidgets('Sliver without keep alive without key - should dispose after reordering', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
const WidgetTest0(text: 'child 0'),
const WidgetTest1(text: 'child 1'),
const WidgetTest2(text: 'child 2'),
];
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsNothing);
expect(state0.hasBeenDisposed, true);
expect(state2.hasBeenDisposed, false);
});
testWidgets('Sliver without keep alive with key - should dispose after reordering', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: GlobalKey()),
WidgetTest1(text: 'child 1', key: GlobalKey()),
WidgetTest2(text: 'child 2', key: GlobalKey()),
];
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsNothing);
expect(state0.hasBeenDisposed, true);
expect(state2.hasBeenDisposed, false);
});
testWidgets('Sliver with keep alive with key - should not dispose after reordering', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: GlobalKey(), keepAlive: true),
WidgetTest1(text: 'child 1', key: GlobalKey(), keepAlive: true),
WidgetTest2(text: 'child 2', key: GlobalKey(), keepAlive: true),
];
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
expect(state0.hasBeenDisposed, false);
expect(state2.hasBeenDisposed, false);
});
testWidgets('Sliver with keep alive with Unique key - should not dispose after reordering', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true),
WidgetTest1(text: 'child 1', key: UniqueKey(), keepAlive: true),
WidgetTest2(text: 'child 2', key: UniqueKey(), keepAlive: true),
];
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
expect(state0.hasBeenDisposed, false);
expect(state2.hasBeenDisposed, false);
});
testWidgets('Sliver with keep alive with Value key - should not dispose after reordering', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
const WidgetTest0(text: 'child 0', key: ValueKey<int>(0), keepAlive: true),
const WidgetTest1(text: 'child 1', key: ValueKey<int>(1), keepAlive: true),
const WidgetTest2(text: 'child 2', key: ValueKey<int>(2), keepAlive: true),
];
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
expect(state0.hasBeenDisposed, false);
expect(state2.hasBeenDisposed, false);
});
testWidgets('Sliver complex case 1', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: GlobalKey(), keepAlive: true),
WidgetTest1(text: 'child 1', key: GlobalKey(), keepAlive: true),
const WidgetTest2(text: 'child 2', keepAlive: true),
];
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1));
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 2', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
childList = createSwitchedChildList(childList, 1, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsOneWidget);
expect(find.text('child 2', skipOffstage: false), findsNothing);
expect(state0.hasBeenDisposed, false);
expect(state1.hasBeenDisposed, false);
// Child 2 does not have a key.
expect(state2.hasBeenDisposed, true);
});
testWidgets('Sliver complex case 2', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: GlobalKey(), keepAlive: true),
WidgetTest1(text: 'child 1', key: UniqueKey()),
const WidgetTest2(text: 'child 2', keepAlive: true),
];
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1));
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 2', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
childList = createSwitchedChildList(childList, 1, 2);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(SwitchingChildListTest(children: childList));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
expect(state0.hasBeenDisposed, false);
expect(state1.hasBeenDisposed, true);
expect(state2.hasBeenDisposed, true);
});
testWidgets('Sliver with SliverChildBuilderDelegate', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true),
WidgetTest1(text: 'child 1', key: GlobalKey()),
const WidgetTest2(text: 'child 2', keepAlive: true),
];
await tester.pumpWidget(SwitchingChildBuilderTest(children: childList));
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(SwitchingChildBuilderTest(children: childList));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 2'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(SwitchingChildBuilderTest(children: childList));
final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1));
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 2', skipOffstage: false), findsNothing);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
childList = createSwitchedChildList(childList, 1, 2);
await tester.pumpWidget(SwitchingChildBuilderTest(children: childList));
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 0', skipOffstage: false), findsOneWidget);
expect(find.text('child 2', skipOffstage: false), findsNothing);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(SwitchingChildBuilderTest(children: childList));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1', skipOffstage: false), findsNothing);
expect(find.text('child 2', skipOffstage: false), findsNothing);
expect(state0.hasBeenDisposed, false);
expect(state1.hasBeenDisposed, true);
expect(state2.hasBeenDisposed, true);
});
testWidgets('SliverFillViewport should not dispose widget with key during in screen reordering', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true),
WidgetTest1(text: 'child 1', key: UniqueKey()),
const WidgetTest2(text: 'child 2', keepAlive: true),
];
await tester.pumpWidget(
SwitchingChildListTest(viewportFraction: 0.1, children: childList),
);
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 2'), findsOneWidget);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(
SwitchingChildListTest(viewportFraction: 0.1, children: childList),
);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(
SwitchingChildListTest(viewportFraction: 0.1, children: childList),
);
childList = createSwitchedChildList(childList, 1, 2);
await tester.pumpWidget(
SwitchingChildListTest(viewportFraction: 0.1, children: childList),
);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(
SwitchingChildListTest(viewportFraction: 0.1, children: childList),
);
expect(state0.hasBeenDisposed, false);
expect(state1.hasBeenDisposed, false);
expect(state2.hasBeenDisposed, true);
});
testWidgets('SliverList should not dispose widget with key during in screen reordering', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true),
const WidgetTest1(text: 'child 1', keepAlive: true),
WidgetTest2(text: 'child 2', key: UniqueKey()),
];
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 2'), findsOneWidget);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
childList = createSwitchedChildList(childList, 1, 2);
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
childList = createSwitchedChildList(childList, 1, 2);
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
childList = createSwitchedChildList(childList, 0, 2);
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
childList = createSwitchedChildList(childList, 0, 1);
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
expect(state0.hasBeenDisposed, false);
expect(state1.hasBeenDisposed, true);
expect(state2.hasBeenDisposed, false);
});
testWidgets('SliverList remove child from child list', (WidgetTester tester) async {
List<Widget> childList= <Widget>[
WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true),
const WidgetTest1(text: 'child 1', keepAlive: true),
WidgetTest2(text: 'child 2', key: UniqueKey()),
];
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0));
final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1));
final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2));
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 2'), findsOneWidget);
childList = createSwitchedChildList(childList, 0, 1);
childList.removeAt(2);
await tester.pumpWidget(
SwitchingSliverListTest(children: childList),
);
expect(find.text('child 0'), findsOneWidget);
expect(find.text('child 1'), findsOneWidget);
expect(find.text('child 2'), findsNothing);
expect(state0.hasBeenDisposed, false);
expect(state1.hasBeenDisposed, true);
expect(state2.hasBeenDisposed, true);
});
}
List<Widget> createSwitchedChildList(List<Widget> childList, int i, int j) {
final Widget w = childList[i];
childList[i] = childList[j];
childList[j] = w;
return List<Widget>.from(childList);
}
class SwitchingChildBuilderTest extends StatefulWidget {
const SwitchingChildBuilderTest({
required this.children,
super.key,
});
final List<Widget> children;
@override
State<SwitchingChildBuilderTest> createState() => _SwitchingChildBuilderTest();
}
class _SwitchingChildBuilderTest extends State<SwitchingChildBuilderTest> {
late List<Widget> children;
late Map<Key, int> _mapKeyToIndex;
@override
void initState() {
super.initState();
children = widget.children;
_mapKeyToIndex = <Key, int>{};
for (int index = 0; index < children.length; index += 1) {
final Key? key = children[index].key;
if (key != null) {
_mapKeyToIndex[key] = index;
}
}
}
@override
void didUpdateWidget(SwitchingChildBuilderTest oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.children != widget.children) {
children = widget.children;
_mapKeyToIndex = <Key, int>{};
for (int index = 0; index < children.length; index += 1) {
final Key? key = children[index].key;
if (key != null) {
_mapKeyToIndex[key] = index;
}
}
}
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 100,
child: CustomScrollView(
cacheExtent: 0,
slivers: <Widget>[
SliverFillViewport(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return children[index];
},
childCount: children.length,
findChildIndexCallback: (Key key) => _mapKeyToIndex[key] ?? -1,
),
),
],
),
),
),
);
}
}
class SwitchingChildListTest extends StatelessWidget {
const SwitchingChildListTest({
required this.children,
this.viewportFraction = 1.0,
super.key,
});
final List<Widget> children;
final double viewportFraction;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 100,
child: CustomScrollView(
cacheExtent: 0,
slivers: <Widget>[
SliverFillViewport(
viewportFraction: viewportFraction,
delegate: SliverChildListDelegate(children),
),
],
),
),
),
);
}
}
class SwitchingSliverListTest extends StatelessWidget {
const SwitchingSliverListTest({
required this.children,
super.key,
});
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 100,
child: CustomScrollView(
cacheExtent: 0,
slivers: <Widget>[
SliverList(
delegate: SliverChildListDelegate(children),
),
],
),
),
),
);
}
}
class WidgetTest0 extends StatefulWidget {
const WidgetTest0({
required this.text,
this.keepAlive = false,
super.key,
});
final String text;
final bool keepAlive;
@override
State<WidgetTest0> createState() => _WidgetTest0State();
}
class _WidgetTest0State extends State<WidgetTest0> with AutomaticKeepAliveClientMixin {
bool hasBeenDisposed = false;
@override
Widget build(BuildContext context) {
super.build(context);
return Text(widget.text);
}
@override
void dispose() {
hasBeenDisposed = true;
super.dispose();
}
@override
bool get wantKeepAlive => widget.keepAlive;
}
class WidgetTest1 extends StatefulWidget {
const WidgetTest1({
required this.text,
this.keepAlive = false,
super.key,
});
final String text;
final bool keepAlive;
@override
State<WidgetTest1> createState() => _WidgetTest1State();
}
class _WidgetTest1State extends State<WidgetTest1> with AutomaticKeepAliveClientMixin {
bool hasBeenDisposed = false;
@override
Widget build(BuildContext context) {
super.build(context);
return Text(widget.text);
}
@override
void dispose() {
hasBeenDisposed = true;
super.dispose();
}
@override
bool get wantKeepAlive => widget.keepAlive;
}
class WidgetTest2 extends StatefulWidget {
const WidgetTest2({
required this.text,
this.keepAlive = false,
super.key,
});
final String text;
final bool keepAlive;
@override
State<WidgetTest2> createState() => _WidgetTest2State();
}
class _WidgetTest2State extends State<WidgetTest2> with AutomaticKeepAliveClientMixin {
bool hasBeenDisposed = false;
@override
Widget build(BuildContext context) {
super.build(context);
return Text(widget.text);
}
@override
void dispose() {
hasBeenDisposed = true;
super.dispose();
}
@override
bool get wantKeepAlive => widget.keepAlive;
}
| flutter/packages/flutter/test/widgets/slivers_keepalive_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/slivers_keepalive_test.dart",
"repo_id": "flutter",
"token_count": 8790
} | 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:ui';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('TapRegionSurface detects outside taps', (WidgetTester tester) async {
final Set<String> tappedOutside = <String>{};
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
const Text('Outside'),
TapRegion(
onTapOutside: (PointerEvent event) {
tappedOutside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedOutside, isEmpty);
await click(find.text('No Group'));
expect(
tappedOutside,
unorderedEquals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedOutside.clear();
await click(find.text('Group 1 A'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
tappedOutside.clear();
await click(find.text('Group 1 B'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
tappedOutside.clear();
await click(find.text('Outside'));
expect(
tappedOutside,
unorderedEquals(<String>{
'No Group',
'Group 1 A',
'Group 1 B',
}));
tappedOutside.clear();
await click(find.text('Outside Surface'));
expect(tappedOutside, isEmpty);
});
testWidgets('TapRegionSurface consumes outside taps when asked', (WidgetTester tester) async {
final Set<String> tappedOutside = <String>{};
int propagatedTaps = 0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
GestureDetector(
onTap: () {
propagatedTaps += 1;
},
child: const Text('Outside'),
),
TapRegion(
consumeOutsideTaps: true,
onTapOutside: (PointerEvent event) {
tappedOutside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
consumeOutsideTaps: true,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedOutside, isEmpty);
expect(propagatedTaps, equals(0));
await click(find.text('No Group'));
expect(
tappedOutside,
unorderedEquals(<String>{
'Group 1 A',
'Group 1 B',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Group 1 A'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Group 1 B'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Outside'));
expect(
tappedOutside,
unorderedEquals(<String>{
'No Group',
'Group 1 A',
'Group 1 B',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Outside Surface'));
expect(tappedOutside, isEmpty);
});
testWidgets('TapRegionSurface detects inside taps', (WidgetTester tester) async {
final Set<String> tappedInside = <String>{};
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
const Text('Outside'),
TapRegion(
onTapInside: (PointerEvent event) {
tappedInside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapInside: (PointerEvent event) {
tappedInside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
onTapInside: (PointerEvent event) {
tappedInside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedInside, isEmpty);
await click(find.text('No Group'));
expect(
tappedInside,
unorderedEquals(<String>{
'No Group',
}));
tappedInside.clear();
await click(find.text('Group 1 A'));
expect(
tappedInside,
equals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedInside.clear();
await click(find.text('Group 1 B'));
expect(
tappedInside,
equals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedInside.clear();
await click(find.text('Outside'));
expect(tappedInside, isEmpty);
tappedInside.clear();
await click(find.text('Outside Surface'));
expect(tappedInside, isEmpty);
});
testWidgets('TapRegionSurface detects inside taps correctly with behavior', (WidgetTester tester) async {
final Set<String> tappedInside = <String>{};
const ValueKey<String> noGroupKey = ValueKey<String>('No Group');
const ValueKey<String> group1AKey = ValueKey<String>('Group 1 A');
const ValueKey<String> group1BKey = ValueKey<String>('Group 1 B');
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
ConstrainedBox(
constraints: const BoxConstraints.tightFor(width: 100, height: 100),
child: TapRegion(
onTapInside: (PointerEvent event) {
tappedInside.add(noGroupKey.value);
},
child: const Stack(key: noGroupKey),
),
),
ConstrainedBox(
constraints: const BoxConstraints.tightFor(width: 100, height: 100),
child: TapRegion(
groupId: 1,
behavior: HitTestBehavior.opaque,
onTapInside: (PointerEvent event) {
tappedInside.add(group1AKey.value);
},
child: const Stack(key: group1AKey),
),
),
ConstrainedBox(
constraints: const BoxConstraints.tightFor(width: 100, height: 100),
child: TapRegion(
groupId: 1,
behavior: HitTestBehavior.translucent,
onTapInside: (PointerEvent event) {
tappedInside.add(group1BKey.value);
},
child: const Stack(key: group1BKey),
),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedInside, isEmpty);
await click(find.byKey(noGroupKey));
expect(tappedInside, isEmpty); // No hittable children, so no hit.
await click(find.byKey(group1AKey));
// No hittable children, but set to opaque, so it hits, triggering the
// group.
expect(
tappedInside,
equals(<String>{
'Group 1 A',
'Group 1 B',
}),
);
tappedInside.clear();
await click(find.byKey(group1BKey));
expect(tappedInside, isEmpty); // No hittable children while translucent, so no hit.
tappedInside.clear();
});
testWidgets('Setting the group updates the registration', (WidgetTester tester) async {
final Set<String> tappedOutside = <String>{};
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: TapRegionSurface(
child: Row(
children: <Widget>[
const Text('Outside'),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedOutside, isEmpty);
await click(find.text('Group 1 A'));
expect(tappedOutside, isEmpty);
await click(find.text('Group 1 B'));
expect(tappedOutside, isEmpty);
await click(find.text('Outside'));
expect(
tappedOutside,
equals(<String>[
'Group 1 A',
'Group 1 B',
]));
tappedOutside.clear();
// Now change out the groups.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: TapRegionSurface(
child: Row(
children: <Widget>[
const Text('Outside'),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 2,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 2 A');
},
child: const Text('Group 2 A'),
),
],
),
),
),
);
await click(find.text('Group 1 A'));
expect(tappedOutside, equals(<String>['Group 2 A']));
tappedOutside.clear();
await click(find.text('Group 2 A'));
expect(tappedOutside, equals(<String>['Group 1 A']));
tappedOutside.clear();
await click(find.text('Outside'));
expect(
tappedOutside,
equals(<String>[
'Group 1 A',
'Group 2 A',
]));
tappedOutside.clear();
});
testWidgets('TapRegionSurface detects outside right click', (WidgetTester tester) async {
final Set<String> tappedOutside = <String>{};
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
const Text('Outside'),
TapRegion(
onTapOutside: (PointerEvent event) {
tappedOutside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryButton,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedOutside, isEmpty);
await click(find.text('No Group'));
expect(
tappedOutside,
unorderedEquals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedOutside.clear();
await click(find.text('Group 1 A'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
tappedOutside.clear();
await click(find.text('Group 1 B'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
tappedOutside.clear();
await click(find.text('Outside'));
expect(
tappedOutside,
unorderedEquals(<String>{
'No Group',
'Group 1 A',
'Group 1 B',
}));
tappedOutside.clear();
await click(find.text('Outside Surface'));
expect(tappedOutside, isEmpty);
});
testWidgets('TapRegionSurface detects outside middle click', (WidgetTester tester) async {
final Set<String> tappedOutside = <String>{};
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
const Text('Outside'),
TapRegion(
onTapOutside: (PointerEvent event) {
tappedOutside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
buttons: kTertiaryButton,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedOutside, isEmpty);
await click(find.text('No Group'));
expect(
tappedOutside,
unorderedEquals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedOutside.clear();
await click(find.text('Group 1 A'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
tappedOutside.clear();
await click(find.text('Group 1 B'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
tappedOutside.clear();
await click(find.text('Outside'));
expect(
tappedOutside,
unorderedEquals(<String>{
'No Group',
'Group 1 A',
'Group 1 B',
}));
tappedOutside.clear();
await click(find.text('Outside Surface'));
expect(tappedOutside, isEmpty);
});
testWidgets('TapRegionSurface consumes outside right click when asked', (WidgetTester tester) async {
final Set<String> tappedOutside = <String>{};
int propagatedTaps = 0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
GestureDetector(
onTap: () {
propagatedTaps += 1;
},
child: const Text('Outside'),
),
TapRegion(
consumeOutsideTaps: true,
onTapOutside: (PointerEvent event) {
tappedOutside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
consumeOutsideTaps: true,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryButton
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedOutside, isEmpty);
expect(propagatedTaps, equals(0));
await click(find.text('No Group'));
expect(
tappedOutside,
unorderedEquals(<String>{
'Group 1 A',
'Group 1 B',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Group 1 A'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Group 1 B'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Outside'));
expect(
tappedOutside,
unorderedEquals(<String>{
'No Group',
'Group 1 A',
'Group 1 B',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Outside Surface'));
expect(tappedOutside, isEmpty);
});
testWidgets('TapRegionSurface consumes outside middle click when asked', (WidgetTester tester) async {
final Set<String> tappedOutside = <String>{};
int propagatedTaps = 0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
GestureDetector(
onTap: () {
propagatedTaps += 1;
},
child: const Text('Outside'),
),
TapRegion(
consumeOutsideTaps: true,
onTapOutside: (PointerEvent event) {
tappedOutside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
consumeOutsideTaps: true,
onTapOutside: (PointerEvent event) {
tappedOutside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
buttons: kTertiaryButton,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedOutside, isEmpty);
expect(propagatedTaps, equals(0));
await click(find.text('No Group'));
expect(
tappedOutside,
unorderedEquals(<String>{
'Group 1 A',
'Group 1 B',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Group 1 A'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Group 1 B'));
expect(
tappedOutside,
equals(<String>{
'No Group',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Outside'));
expect(
tappedOutside,
unorderedEquals(<String>{
'No Group',
'Group 1 A',
'Group 1 B',
}));
expect(propagatedTaps, equals(0));
tappedOutside.clear();
await click(find.text('Outside Surface'));
expect(tappedOutside, isEmpty);
});
testWidgets('TapRegionSurface detects inside right click', (WidgetTester tester) async {
final Set<String> tappedInside = <String>{};
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
const Text('Outside'),
TapRegion(
onTapInside: (PointerEvent event) {
tappedInside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapInside: (PointerEvent event) {
tappedInside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
onTapInside: (PointerEvent event) {
tappedInside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryButton,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedInside, isEmpty);
await click(find.text('No Group'));
expect(
tappedInside,
unorderedEquals(<String>{
'No Group',
}));
tappedInside.clear();
await click(find.text('Group 1 A'));
expect(
tappedInside,
equals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedInside.clear();
await click(find.text('Group 1 B'));
expect(
tappedInside,
equals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedInside.clear();
await click(find.text('Outside'));
expect(tappedInside, isEmpty);
tappedInside.clear();
await click(find.text('Outside Surface'));
expect(tappedInside, isEmpty);
});
testWidgets('TapRegionSurface detects inside middle click', (WidgetTester tester) async {
final Set<String> tappedInside = <String>{};
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Outside Surface'),
TapRegionSurface(
child: Row(
children: <Widget>[
const Text('Outside'),
TapRegion(
onTapInside: (PointerEvent event) {
tappedInside.add('No Group');
},
child: const Text('No Group'),
),
TapRegion(
groupId: 1,
onTapInside: (PointerEvent event) {
tappedInside.add('Group 1 A');
},
child: const Text('Group 1 A'),
),
TapRegion(
groupId: 1,
onTapInside: (PointerEvent event) {
tappedInside.add('Group 1 B');
},
child: const Text('Group 1 B'),
),
],
),
),
],
),
),
);
await tester.pump();
Future<void> click(Finder finder) async {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(finder),
kind: PointerDeviceKind.mouse,
buttons: kTertiaryButton,
);
await gesture.up();
await gesture.removePointer();
}
expect(tappedInside, isEmpty);
await click(find.text('No Group'));
expect(
tappedInside,
unorderedEquals(<String>{
'No Group',
}));
tappedInside.clear();
await click(find.text('Group 1 A'));
expect(
tappedInside,
equals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedInside.clear();
await click(find.text('Group 1 B'));
expect(
tappedInside,
equals(<String>{
'Group 1 A',
'Group 1 B',
}));
tappedInside.clear();
await click(find.text('Outside'));
expect(tappedInside, isEmpty);
tappedInside.clear();
await click(find.text('Outside Surface'));
expect(tappedInside, isEmpty);
});
}
| flutter/packages/flutter/test/widgets/tap_region_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/tap_region_test.dart",
"repo_id": "flutter",
"token_count": 15672
} | 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:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Scrollable scaled up', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Transform.scale(
scale: 2.0,
child: Center(
child: SizedBox(
width: 200,
child: ListView.builder(
controller: controller,
cacheExtent: 0.0,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 100.0,
color: index.isEven ? Colors.blue : Colors.red,
child: Text('Tile $index'),
);
},
),
),
),
),
),
);
expect(controller.offset, 0.0);
await tester.drag(find.byType(ListView), const Offset(0.0, -100.0));
await tester.pump();
expect(controller.offset, 50.0); // 100.0 / 2.0
await tester.drag(find.byType(ListView), const Offset(80.0, -70.0));
await tester.pump();
expect(controller.offset, 85.0); // 50.0 + (70.0 / 2)
await tester.drag(find.byType(ListView), const Offset(100.0, 0.0));
await tester.pump();
expect(controller.offset, 85.0);
await tester.drag(find.byType(ListView), const Offset(0.0, 85.0));
await tester.pump();
expect(controller.offset, 42.5); // 85.0 - (85.0 / 2)
});
testWidgets('Scrollable scaled down', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Transform.scale(
scale: 0.5,
child: Center(
child: SizedBox(
width: 200,
child: ListView.builder(
controller: controller,
cacheExtent: 0.0,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 100.0,
color: index.isEven ? Colors.blue : Colors.red,
child: Text('Tile $index'),
);
},
),
),
),
),
),
);
expect(controller.offset, 0.0);
await tester.drag(find.byType(ListView), const Offset(0.0, -100.0));
await tester.pump();
expect(controller.offset, 200.0); // 100.0 * 2.0
await tester.drag(find.byType(ListView), const Offset(80.0, -70.0));
await tester.pump();
expect(controller.offset, 340.0); // 200.0 + (70.0 * 2)
await tester.drag(find.byType(ListView), const Offset(100.0, 0.0));
await tester.pump();
expect(controller.offset, 340.0);
await tester.drag(find.byType(ListView), const Offset(0.0, 170.0));
await tester.pump();
expect(controller.offset, 0.0); // 340.0 - (170.0 * 2)
});
testWidgets('Scrollable rotated 90 degrees', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Transform.rotate(
angle: math.pi / 2,
child: Center(
child: SizedBox(
width: 200,
child: ListView.builder(
controller: controller,
cacheExtent: 0.0,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 100.0,
color: index.isEven ? Colors.blue : Colors.red,
child: Text('Tile $index'),
);
},
),
),
),
),
),
);
expect(controller.offset, 0.0);
await tester.drag(find.byType(ListView), const Offset(100.0, 0.0));
await tester.pump();
expect(controller.offset, 100.0);
await tester.drag(find.byType(ListView), const Offset(0.0, -100.0));
await tester.pump();
expect(controller.offset, 100.0);
await tester.drag(find.byType(ListView), const Offset(-70.0, -50.0));
await tester.pump();
expect(controller.offset, 30.0); // 100.0 - 70.0
});
testWidgets('Perspective transform on scrollable', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Transform(
transform: Matrix4.identity()
..setEntry(3, 2, 0.001)
..rotateX(math.pi / 4),
child: Center(
child: SizedBox(
width: 200,
child: ListView.builder(
controller: controller,
cacheExtent: 0.0,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 100.0,
color: index.isEven ? Colors.blue : Colors.red,
child: Text('Tile $index'),
);
},
),
),
),
),
),
);
expect(controller.offset, 0.0);
// We want to test that the point in the ListView that the finger touches
// on the screen stays under the finger as the finger scrolls the ListView
// in vertical direction. For this, we pick a point in the ListView (here
// the center of Tile 5) and calculate its position in the coordinate space
// of the screen. We then place our finger on that point and drag that
// point up in vertical direction. After the scroll activity is done,
// we verify that - in the coordinate space of the screen (!) - the point
// has moved the same distance as the finger. Due to the perspective
// transform the point will have moved more distance in the *local*
// coordinate system of the ListView.
// Calculate where the center of Tile 5 is located in the coordinate
// space of the screen. We cannot use `tester.getCenter` because it
// does not properly remove the perspective component from the transform
// to give us the place on the screen at which we need to touch the screen
// to have the center of Tile 5 directly under our finger.
final RenderBox tile5 = tester.renderObject(find.text('Tile 5'));
final Offset pointOnScreenStart = MatrixUtils.transformPoint(
PointerEvent.removePerspectiveTransform(tile5.getTransformTo(null)),
tile5.size.center(Offset.zero),
);
// Place the finger on the tracked point and move the finger upwards for
// 50 pixels to scroll the ListView (the ListView's scroll offset will
// move more then 50 pixels due to the perspective transform).
await tester.dragFrom(pointOnScreenStart, const Offset(0.0, -50.0));
await tester.pump();
// Get the new position of the tracked point in the screen's coordinate
// system.
final Offset pointOnScreenEnd = MatrixUtils.transformPoint(
PointerEvent.removePerspectiveTransform(tile5.getTransformTo(null)),
tile5.size.center(Offset.zero),
);
// The tracked point (in the coordinate space of the screen) and the finger
// should have moved the same vertical distance over the screen.
expect(
pointOnScreenStart.dy - pointOnScreenEnd.dy,
within(distance: 0.00001, from: 50.0),
);
// While the point traveled the same distance as the finger in the
// coordinate space of the screen, the scroll view actually moved far more
// pixels in its local coordinate system due to the perspective transform.
expect(controller.offset, greaterThan(100));
});
}
| flutter/packages/flutter/test/widgets/transformed_scrollable_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/transformed_scrollable_test.dart",
"repo_id": "flutter",
"token_count": 3409
} | 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 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('WidgetStateProperty.resolveWith()', () {
final WidgetStateProperty<WidgetState> value = WidgetStateProperty.resolveWith<WidgetState>(
(Set<WidgetState> states) => states.first,
);
expect(value.resolve(<WidgetState>{WidgetState.hovered}), WidgetState.hovered);
expect(value.resolve(<WidgetState>{WidgetState.focused}), WidgetState.focused);
expect(value.resolve(<WidgetState>{WidgetState.pressed}), WidgetState.pressed);
expect(value.resolve(<WidgetState>{WidgetState.dragged}), WidgetState.dragged);
expect(value.resolve(<WidgetState>{WidgetState.selected}), WidgetState.selected);
expect(value.resolve(<WidgetState>{WidgetState.disabled}), WidgetState.disabled);
expect(value.resolve(<WidgetState>{WidgetState.error}), WidgetState.error);
});
test('WidgetStateProperty.all()', () {
final WidgetStateProperty<int> value = WidgetStateProperty.all<int>(123);
expect(value.resolve(<WidgetState>{WidgetState.hovered}), 123);
expect(value.resolve(<WidgetState>{WidgetState.focused}), 123);
expect(value.resolve(<WidgetState>{WidgetState.pressed}), 123);
expect(value.resolve(<WidgetState>{WidgetState.dragged}), 123);
expect(value.resolve(<WidgetState>{WidgetState.selected}), 123);
expect(value.resolve(<WidgetState>{WidgetState.disabled}), 123);
expect(value.resolve(<WidgetState>{WidgetState.error}), 123);
});
test('WidgetStatePropertyAll', () {
const WidgetStatePropertyAll<int> value = WidgetStatePropertyAll<int>(123);
expect(value.resolve(<WidgetState>{}), 123);
expect(value.resolve(<WidgetState>{WidgetState.hovered}), 123);
expect(value.resolve(<WidgetState>{WidgetState.focused}), 123);
expect(value.resolve(<WidgetState>{WidgetState.pressed}), 123);
expect(value.resolve(<WidgetState>{WidgetState.dragged}), 123);
expect(value.resolve(<WidgetState>{WidgetState.selected}), 123);
expect(value.resolve(<WidgetState>{WidgetState.disabled}), 123);
expect(value.resolve(<WidgetState>{WidgetState.error}), 123);
});
test('toString formats correctly', () {
const WidgetStateProperty<Color?> colorProperty = WidgetStatePropertyAll<Color?>(Color(0xFFFFFFFF));
expect(colorProperty.toString(), equals('WidgetStatePropertyAll(Color(0xffffffff))'));
const WidgetStateProperty<double?> doubleProperty = WidgetStatePropertyAll<double?>(33 + 1/3);
expect(doubleProperty.toString(), equals('WidgetStatePropertyAll(33.3)'));
});
test("Can interpolate between two WidgetStateProperty's", () {
const WidgetStateProperty<TextStyle?> textStyle1 = WidgetStatePropertyAll<TextStyle?>(
TextStyle(fontSize: 14.0),
);
const WidgetStateProperty<TextStyle?> textStyle2 = WidgetStatePropertyAll<TextStyle?>(
TextStyle(fontSize: 20.0),
);
// Using `0.0` interpolation value.
TextStyle textStyle = WidgetStateProperty.lerp<TextStyle?>(
textStyle1,
textStyle2,
0.0,
TextStyle.lerp,
)!.resolve(enabled)!;
expect(textStyle.fontSize, 14.0);
// Using `0.5` interpolation value.
textStyle = WidgetStateProperty.lerp<TextStyle?>(
textStyle1,
textStyle2,
0.5,
TextStyle.lerp,
)!.resolve(enabled)!;
expect(textStyle.fontSize, 17.0);
// Using `1.0` interpolation value.
textStyle = WidgetStateProperty.lerp<TextStyle?>(
textStyle1,
textStyle2,
1.0,
TextStyle.lerp,
)!.resolve(enabled)!;
expect(textStyle.fontSize, 20.0);
});
}
Set<WidgetState> enabled = <WidgetState>{};
| flutter/packages/flutter/test/widgets/widget_state_property_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/widget_state_property_test.dart",
"repo_id": "flutter",
"token_count": 1369
} | 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 'package:flutter/material.dart';
void main() {
// Changes made in https://github.com/flutter/flutter/pull/93427
ColorScheme colorScheme = ColorScheme();
colorScheme = ColorScheme(primaryVariant: Colors.black, secondaryVariant: Colors.white);
colorScheme = ColorScheme.light(primaryVariant: Colors.black, secondaryVariant: Colors.white);
colorScheme = ColorScheme.dark(primaryVariant: Colors.black, secondaryVariant: Colors.white);
colorScheme = ColorScheme.highContrastLight(primaryVariant: Colors.black, secondaryVariant: Colors.white);
colorScheme = ColorScheme.highContrastDark(primaryVariant: Colors.black, secondaryVariant: Colors.white);
colorScheme = colorScheme.copyWith(primaryVariant: Colors.black, secondaryVariant: Colors.white);
colorScheme.primaryVariant; // Removing field reference not supported.
colorScheme.secondaryVariant;
// Changes made in https://github.com/flutter/flutter/pull/138521
ColorScheme colorScheme = ColorScheme();
colorScheme = ColorScheme(background: Colors.black, onBackground: Colors.white, surfaceVariant: Colors.red);
colorScheme = ColorScheme(background: Colors.black, surface: Colors.orange, onBackground: Colors.white, onSurface: Colors.yellow, surfaceVariant: Colors.red, surfaceContainerHighest: Colors.blue);
colorScheme = ColorScheme.light(background: Colors.black, onBackground: Colors.white, surfaceVariant: Colors.red);
colorScheme = ColorScheme.light(background: Colors.black, surface: Colors.orange, onBackground: Colors.white, onSurface: Colors.yellow, surfaceVariant: Colors.red, surfaceContainerHighest: Colors.blue);
colorScheme = ColorScheme.dark(background: Colors.black, onBackground: Colors.white, surfaceVariant: Colors.red);
colorScheme = ColorScheme.dark(background: Colors.black, surface: Colors.orange, onBackground: Colors.white, onSurface: Colors.yellow, surfaceVariant: Colors.red, surfaceContainerHighest: Colors.blue);
colorScheme = ColorScheme.highContrastLight(background: Colors.black, onBackground: Colors.white, surfaceVariant: Colors.red);
colorScheme = ColorScheme.highContrastLight(background: Colors.black, surface: Colors.orange, onBackground: Colors.white, onSurface: Colors.yellow, surfaceVariant: Colors.red, surfaceContainerHighest: Colors.blue);
colorScheme = ColorScheme.highContrastDark(background: Colors.black, onBackground: Colors.white, surfaceVariant: Colors.red);
colorScheme = ColorScheme.highContrastDark(background: Colors.black, surface: Colors.orange, onBackground: Colors.white, onSurface: Colors.yellow, surfaceVariant: Colors.red, surfaceContainerHighest: Colors.blue);
colorScheme = colorScheme.copyWith(background: Colors.black, onBackground: Colors.white, surfaceVariant: Colors.red);
colorScheme = colorScheme.copyWith(background: Colors.black, surface: Colors.orange, onBackground: Colors.white, onSurface: Colors.yellow, surfaceVariant: Colors.red, surfaceContainerHighest: Colors.blue);
colorScheme.background;
colorScheme.onBackground;
colorScheme.surfaceVariant;
}
| flutter/packages/flutter/test_fixes/material/color_scheme.dart/0 | {
"file_path": "flutter/packages/flutter/test_fixes/material/color_scheme.dart",
"repo_id": "flutter",
"token_count": 907
} | 735 |
// 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';
void main() {
// Changes made in https://github.com/flutter/flutter/pull/66305
RenderStack renderStack = RenderStack();
renderStack = RenderStack(overflow: Overflow.visible);
renderStack = RenderStack(overflow: Overflow.clip);
renderStack = RenderStack(error: '');
renderStack.overflow;
// Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior
RenderListWheelViewport renderListWheelViewport = RenderListWheelViewport();
renderListWheelViewport = RenderListWheelViewport(clipToSize: true);
renderListWheelViewport = RenderListWheelViewport(clipToSize: false);
renderListWheelViewport = RenderListWheelViewport(error: '');
renderListWheelViewport.clipToSize;
// Change made in https://github.com/flutter/flutter/pull/128522
RenderParagraph(textScaleFactor: math.min(123, 456));
RenderParagraph();
RenderEditable(textScaleFactor: math.min(123, 456));
RenderEditable();
}
| flutter/packages/flutter/test_fixes/rendering/rendering.dart/0 | {
"file_path": "flutter/packages/flutter/test_fixes/rendering/rendering.dart",
"repo_id": "flutter",
"token_count": 334
} | 736 |
// 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';
void main() {
test('TextTreeRenderer returns an empty string in release mode', () {
final TextTreeRenderer renderer = TextTreeRenderer();
final TestDiagnosticsNode node = TestDiagnosticsNode();
expect(renderer.render(node), '');
});
}
class TestDiagnosticsNode extends DiagnosticsNode {
TestDiagnosticsNode() : super(
name: 'test',
style: DiagnosticsTreeStyle.singleLine,
);
@override
List<DiagnosticsNode> getChildren() {
return <DiagnosticsNode>[];
}
@override
List<DiagnosticsNode> getProperties() {
return <DiagnosticsNode>[];
}
@override
String toDescription({TextTreeConfiguration? parentConfiguration}) {
return 'Test Description';
}
@override
final Object? value = Object();
}
| flutter/packages/flutter/test_release/diagnostics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test_release/diagnostics_test.dart",
"repo_id": "flutter",
"token_count": 319
} | 737 |
// 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';
import 'package:meta/meta.dart';
import 'deserialization_factory.dart';
import 'error.dart';
import 'message.dart';
const List<Type> _supportedKeyValueTypes = <Type>[String, int];
DriverError _createInvalidKeyValueTypeError(String invalidType) {
return DriverError('Unsupported key value type $invalidType. Flutter Driver only supports ${_supportedKeyValueTypes.join(", ")}');
}
/// A Flutter Driver command aimed at an object to be located by [finder].
///
/// Implementations must provide a concrete [kind]. If additional data is
/// required beyond the [finder] the implementation may override [serialize]
/// and add more keys to the returned map.
abstract class CommandWithTarget extends Command {
/// Constructs this command given a [finder].
CommandWithTarget(this.finder, {super.timeout});
/// Deserializes this command from the value generated by [serialize].
CommandWithTarget.deserialize(super.json, DeserializeFinderFactory finderFactory)
: finder = finderFactory.deserializeFinder(json),
super.deserialize();
/// Locates the object or objects targeted by this command.
final SerializableFinder finder;
/// This method is meant to be overridden if data in addition to [finder]
/// is serialized to JSON.
///
/// Example:
///
/// Map<String, String> toJson() => super.toJson()..addAll({
/// 'foo': this.foo,
/// });
@override
Map<String, String> serialize() =>
super.serialize()..addAll(finder.serialize());
}
/// A Flutter Driver command that waits until [finder] can locate the target.
class WaitFor extends CommandWithTarget {
/// Creates a command that waits for the widget identified by [finder] to
/// appear within the [timeout] amount of time.
///
/// If [timeout] is not specified, the command defaults to no timeout.
WaitFor(super.finder, {super.timeout});
/// Deserializes this command from the value generated by [serialize].
WaitFor.deserialize(super.json, super.finderFactory) : super.deserialize();
@override
String get kind => 'waitFor';
}
/// A Flutter Driver command that waits until [finder] can no longer locate the target.
class WaitForAbsent extends CommandWithTarget {
/// Creates a command that waits for the widget identified by [finder] to
/// disappear within the [timeout] amount of time.
///
/// If [timeout] is not specified, the command defaults to no timeout.
WaitForAbsent(super.finder, {super.timeout});
/// Deserializes this command from the value generated by [serialize].
WaitForAbsent.deserialize(super.json, super.finderFactory) : super.deserialize();
@override
String get kind => 'waitForAbsent';
}
/// A Flutter Driver command that waits until [finder] can be tapped.
class WaitForTappable extends CommandWithTarget {
/// Creates a command that waits for the widget identified by [finder] to
/// be tappable within the [timeout] amount of time.
///
/// If [timeout] is not specified, the command defaults to no timeout.
WaitForTappable(super.finder, {super.timeout});
/// Deserialized this command from the value generated by [serialize].
WaitForTappable.deserialize(
super.json, super.finderFactory)
: super.deserialize();
@override
String get kind => 'waitForTappable';
}
/// Base class for Flutter Driver finders, objects that describe how the driver
/// should search for elements.
abstract class SerializableFinder {
/// A const constructor to allow subclasses to be const.
const SerializableFinder();
/// Identifies the type of finder to be used by the driver extension.
String get finderType;
/// Serializes common fields to JSON.
///
/// Methods that override [serialize] are expected to call `super.serialize`
/// and add more fields to the returned [Map].
@mustCallSuper
Map<String, String> serialize() => <String, String>{
'finderType': finderType,
};
}
/// A Flutter Driver finder that finds widgets by tooltip text.
class ByTooltipMessage extends SerializableFinder {
/// Creates a tooltip finder given the tooltip's message [text].
const ByTooltipMessage(this.text);
/// Tooltip message text.
final String text;
@override
String get finderType => 'ByTooltipMessage';
@override
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
'text': text,
});
/// Deserializes the finder from JSON generated by [serialize].
static ByTooltipMessage deserialize(Map<String, String> json) {
return ByTooltipMessage(json['text']!);
}
}
/// A Flutter Driver finder that finds widgets by semantic label.
///
/// If the [label] property is a [String], the finder will try to find an exact
/// match. If it is a [RegExp], it will return true for [RegExp.hasMatch].
class BySemanticsLabel extends SerializableFinder {
/// Creates a semantic label finder given the [label].
const BySemanticsLabel(this.label);
/// A [Pattern] matching the label of a [SemanticsNode].
///
/// If this is a [String], it will be treated as an exact match.
final Pattern label;
@override
String get finderType => 'BySemanticsLabel';
@override
Map<String, String> serialize() {
if (label is RegExp) {
final RegExp regExp = label as RegExp;
return super.serialize()..addAll(<String, String>{
'label': regExp.pattern,
'isRegExp': 'true',
});
} else {
return super.serialize()..addAll(<String, String>{
'label': label as String,
});
}
}
/// Deserializes the finder from JSON generated by [serialize].
static BySemanticsLabel deserialize(Map<String, String> json) {
final bool isRegExp = json['isRegExp'] == 'true';
return BySemanticsLabel(isRegExp ? RegExp(json['label']!) : json['label']!);
}
}
/// A Flutter Driver finder that finds widgets by [text] inside a
/// [widgets.Text] or [widgets.EditableText] widget.
class ByText extends SerializableFinder {
/// Creates a text finder given the text.
const ByText(this.text);
/// The text that appears inside the [widgets.Text] or [widgets.EditableText]
/// widget.
final String text;
@override
String get finderType => 'ByText';
@override
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
'text': text,
});
/// Deserializes the finder from JSON generated by [serialize].
static ByText deserialize(Map<String, String> json) {
return ByText(json['text']!);
}
}
/// A Flutter Driver finder that finds widgets by `ValueKey`.
class ByValueKey extends SerializableFinder {
/// Creates a finder given the key value.
ByValueKey(this.keyValue)
: keyValueString = '$keyValue',
keyValueType = '${keyValue.runtimeType}' {
if (!_supportedKeyValueTypes.contains(keyValue.runtimeType)) {
throw _createInvalidKeyValueTypeError('$keyValue.runtimeType');
}
}
/// The true value of the key.
final dynamic keyValue;
/// Stringified value of the key (we can only send strings to the VM service)
final String keyValueString;
/// The type name of the key.
///
/// May be one of "String", "int". The list of supported types may change.
final String keyValueType;
@override
String get finderType => 'ByValueKey';
@override
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
'keyValueString': keyValueString,
'keyValueType': keyValueType,
});
/// Deserializes the finder from JSON generated by [serialize].
static ByValueKey deserialize(Map<String, String> json) {
final String keyValueString = json['keyValueString']!;
final String keyValueType = json['keyValueType']!;
switch (keyValueType) {
case 'int':
return ByValueKey(int.parse(keyValueString));
case 'String':
return ByValueKey(keyValueString);
default:
throw _createInvalidKeyValueTypeError(keyValueType);
}
}
}
/// A Flutter Driver finder that finds widgets by their [runtimeType].
class ByType extends SerializableFinder {
/// Creates a finder given the runtime type in string form.
const ByType(this.type);
/// The widget's [runtimeType], in string form.
final String type;
@override
String get finderType => 'ByType';
@override
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
'type': type,
});
/// Deserializes the finder from JSON generated by [serialize].
static ByType deserialize(Map<String, String> json) {
return ByType(json['type']!);
}
}
/// A Flutter Driver finder that finds the back button on the page's Material
/// or Cupertino scaffold.
///
/// See also:
///
/// * [WidgetTester.pageBack], for a similar functionality in widget tests.
class PageBack extends SerializableFinder {
/// Creates a [PageBack].
const PageBack();
@override
String get finderType => 'PageBack';
}
/// A Flutter Driver finder that finds a descendant of [of] that matches
/// [matching].
///
/// If the `matchRoot` argument is true, then the widget specified by [of] will
/// be considered for a match. The argument defaults to false.
class Descendant extends SerializableFinder {
/// Creates a descendant finder.
const Descendant({
required this.of,
required this.matching,
this.matchRoot = false,
this.firstMatchOnly = false,
});
/// The finder specifying the widget of which the descendant is to be found.
final SerializableFinder of;
/// Only a descendant of [of] matching this finder will be found.
final SerializableFinder matching;
/// Whether the widget matching [of] will be considered for a match.
final bool matchRoot;
/// If true then only the first descendant matching `matching` will be returned.
final bool firstMatchOnly;
@override
String get finderType => 'Descendant';
@override
Map<String, String> serialize() {
return super.serialize()
..addAll(<String, String>{
'of': jsonEncode(of.serialize()),
'matching': jsonEncode(matching.serialize()),
'matchRoot': matchRoot ? 'true' : 'false',
'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
});
}
/// Deserializes the finder from JSON generated by [serialize].
static Descendant deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory) {
final Map<String, String> jsonOfMatcher =
Map<String, String>.from(jsonDecode(json['of']!) as Map<String, dynamic>);
final Map<String, String> jsonMatchingMatcher =
Map<String, String>.from(jsonDecode(json['matching']!) as Map<String, dynamic>);
return Descendant(
of: finderFactory.deserializeFinder(jsonOfMatcher),
matching: finderFactory.deserializeFinder(jsonMatchingMatcher),
matchRoot: json['matchRoot'] == 'true',
firstMatchOnly: json['firstMatchOnly'] == 'true',
);
}
}
/// A Flutter Driver finder that finds an ancestor of [of] that matches
/// [matching].
///
/// If the `matchRoot` argument is true, then the widget specified by [of] will
/// be considered for a match. The argument defaults to false.
class Ancestor extends SerializableFinder {
/// Creates an ancestor finder.
const Ancestor({
required this.of,
required this.matching,
this.matchRoot = false,
this.firstMatchOnly = false,
});
/// The finder specifying the widget of which the ancestor is to be found.
final SerializableFinder of;
/// Only an ancestor of [of] matching this finder will be found.
final SerializableFinder matching;
/// Whether the widget matching [of] will be considered for a match.
final bool matchRoot;
/// If true then only the first ancestor matching `matching` will be returned.
final bool firstMatchOnly;
@override
String get finderType => 'Ancestor';
@override
Map<String, String> serialize() {
return super.serialize()
..addAll(<String, String>{
'of': jsonEncode(of.serialize()),
'matching': jsonEncode(matching.serialize()),
'matchRoot': matchRoot ? 'true' : 'false',
'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
});
}
/// Deserializes the finder from JSON generated by [serialize].
static Ancestor deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory) {
final Map<String, String> jsonOfMatcher =
Map<String, String>.from(jsonDecode(json['of']!) as Map<String, dynamic>);
final Map<String, String> jsonMatchingMatcher =
Map<String, String>.from(jsonDecode(json['matching']!) as Map<String, dynamic>);
return Ancestor(
of: finderFactory.deserializeFinder(jsonOfMatcher),
matching: finderFactory.deserializeFinder(jsonMatchingMatcher),
matchRoot: json['matchRoot'] == 'true',
firstMatchOnly: json['firstMatchOnly'] == 'true',
);
}
}
/// A Flutter driver command that retrieves a semantics id using a specified finder.
///
/// This command requires assertions to be enabled on the device.
///
/// If the object returned by the finder does not have its own semantics node,
/// then the semantics node of the first ancestor is returned instead.
///
/// Throws an error if a finder returns multiple objects or if there are no
/// semantics nodes.
///
/// Semantics must be enabled to use this method, either using a platform
/// specific shell command or [FlutterDriver.setSemantics].
class GetSemanticsId extends CommandWithTarget {
/// Creates a command which finds a Widget and then looks up the semantic id.
GetSemanticsId(super.finder, {super.timeout});
/// Creates a command from a JSON map.
GetSemanticsId.deserialize(super.json, super.finderFactory)
: super.deserialize();
@override
String get kind => 'get_semantics_id';
}
/// The result of a [GetSemanticsId] command.
class GetSemanticsIdResult extends Result {
/// Creates a new [GetSemanticsId] result.
const GetSemanticsIdResult(this.id);
/// The semantics id of the node.
final int id;
/// Deserializes this result from JSON.
static GetSemanticsIdResult fromJson(Map<String, dynamic> json) {
return GetSemanticsIdResult(json['id'] as int);
}
@override
Map<String, dynamic> toJson() => <String, dynamic>{'id': id};
}
| flutter/packages/flutter_driver/lib/src/common/find.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/common/find.dart",
"repo_id": "flutter",
"token_count": 4473
} | 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:io';
import 'package:meta/meta.dart';
import 'package:vm_service/vm_service.dart' as vms;
import 'package:webdriver/async_io.dart' as async_io;
import '../common/diagnostics_tree.dart';
import '../common/error.dart';
import '../common/find.dart';
import '../common/frame_sync.dart';
import '../common/geometry.dart';
import '../common/gesture.dart';
import '../common/health.dart';
import '../common/layer_tree.dart';
import '../common/message.dart';
import '../common/render_tree.dart';
import '../common/request_data.dart';
import '../common/semantics.dart';
import '../common/text.dart';
import '../common/text_input_action.dart';
import '../common/wait.dart';
import 'timeline.dart';
import 'vmservice_driver.dart';
import 'web_driver.dart';
export 'vmservice_driver.dart';
export 'web_driver.dart';
/// Timeline stream identifier.
enum TimelineStream {
/// A meta-identifier that instructs the Dart VM to record all streams.
all,
/// Marks events related to calls made via Dart's C API.
api,
/// Marks events from the Dart VM's JIT compiler.
compiler,
/// The verbose version of compiler.
compilerVerbose,
/// Marks events emitted using the `dart:developer` API.
dart,
/// Marks events from the Dart VM debugger.
debugger,
/// Marks events emitted using the `dart_tools_api.h` C API.
embedder,
/// Marks events from the garbage collector.
gc,
/// Marks events related to message passing between Dart isolates.
isolate,
/// Marks internal VM events.
vm,
}
/// How long to wait before showing a message saying that
/// things seem to be taking a long time.
@internal
const Duration kUnusuallyLongTimeout = Duration(seconds: 5);
/// A convenient accessor to frequently used finders.
///
/// Examples:
///
/// driver.tap(find.text('Save'));
/// driver.scroll(find.byValueKey(42));
const CommonFinders find = CommonFinders._();
/// Computes a value.
///
/// If computation is asynchronous, the function may return a [Future].
///
/// See also [FlutterDriver.waitFor].
typedef EvaluatorFunction = dynamic Function();
// Examples can assume:
// import 'package:flutter_driver/flutter_driver.dart';
// import 'package:test/test.dart';
// late FlutterDriver driver;
/// Drives a Flutter Application running in another process.
abstract class FlutterDriver {
/// Default constructor.
@visibleForTesting
FlutterDriver();
/// Creates a driver that uses a connection provided by either the combination
/// of [webConnection], or the combination of [serviceClient] and [appIsolate]
/// for the VM.
@visibleForTesting
factory FlutterDriver.connectedTo({
FlutterWebConnection? webConnection,
vms.VmService? serviceClient,
vms.Isolate? appIsolate,
}) {
if (webConnection != null) {
return WebFlutterDriver.connectedTo(webConnection);
}
return VMServiceFlutterDriver.connectedTo(serviceClient!, appIsolate!);
}
/// Connects to a Flutter application.
///
/// Resumes the application if it is currently paused (e.g. at a breakpoint).
///
/// The `dartVmServiceUrl` parameter is the URL to Dart observatory
/// (a.k.a. VM service). If not specified, the URL specified by the
/// `VM_SERVICE_URL` environment variable is used. One or the other must be
/// specified.
///
/// The `printCommunication` parameter determines whether the command
/// communication between the test and the app should be printed to stdout.
///
/// The `logCommunicationToFile` parameter determines whether the command
/// communication between the test and the app should be logged to
/// `flutter_driver_commands.log`.
///
/// The `isolateNumber` parameter determines the specific isolate to connect
/// to. If this is left as `null`, will connect to the first isolate found
/// running on `dartVmServiceUrl`.
///
/// The `fuchsiaModuleTarget` parameter specifies the pattern for determining
/// which mod to control. When running on a Fuchsia device, either this or the
/// environment variable `FUCHSIA_MODULE_TARGET` must be set (the environment
/// variable is treated as a substring pattern). This field will be ignored if
/// `isolateNumber` is set, as this is already enough information to connect
/// to an isolate. This parameter is ignored on non-fuchsia devices.
///
/// The `headers` parameter optionally specifies HTTP headers to be included
/// in the [WebSocket] connection. This is only used for
/// [VMServiceFlutterDriver] connections.
///
/// The return value is a future. This method never times out, though it may
/// fail (completing with an error). A timeout can be applied by the caller
/// using [Future.timeout] if necessary.
static Future<FlutterDriver> connect({
String? dartVmServiceUrl,
bool printCommunication = false,
bool logCommunicationToFile = true,
int? isolateNumber,
Pattern? fuchsiaModuleTarget,
Duration? timeout,
Map<String, dynamic>? headers,
}) async {
if (Platform.environment['FLUTTER_WEB_TEST'] != null) {
return WebFlutterDriver.connectWeb(
hostUrl: dartVmServiceUrl,
timeout: timeout,
printCommunication: printCommunication,
logCommunicationToFile: logCommunicationToFile,
);
}
return VMServiceFlutterDriver.connect(
dartVmServiceUrl: dartVmServiceUrl,
printCommunication: printCommunication,
logCommunicationToFile: logCommunicationToFile,
isolateNumber: isolateNumber,
fuchsiaModuleTarget: fuchsiaModuleTarget,
headers: headers,
);
}
/// Getter of appIsolate.
vms.Isolate get appIsolate => throw UnimplementedError();
/// Getter of serviceClient.
vms.VmService get serviceClient => throw UnimplementedError();
/// Getter of webDriver.
async_io.WebDriver get webDriver => throw UnimplementedError();
/// Sends [command] to the Flutter Driver extensions.
/// This must be implemented by subclass.
///
/// See also:
///
/// * [VMServiceFlutterDriver], which uses vmservice to implement.
/// * [WebFlutterDriver], which uses webdriver to implement.
Future<Map<String, dynamic>> sendCommand(Command command) async => throw UnimplementedError();
/// Checks the status of the Flutter Driver extension.
Future<Health> checkHealth({ Duration? timeout }) async {
return Health.fromJson(await sendCommand(GetHealth(timeout: timeout)));
}
/// Returns a dump of the render tree.
Future<RenderTree> getRenderTree({ Duration? timeout }) async {
return RenderTree.fromJson(await sendCommand(GetRenderTree(timeout: timeout)));
}
/// Returns a dump of the layer tree.
Future<LayerTree> getLayerTree({ Duration? timeout }) async {
return LayerTree.fromJson(await sendCommand(GetLayerTree(timeout: timeout)));
}
/// Taps at the center of the widget located by [finder].
Future<void> tap(SerializableFinder finder, { Duration? timeout }) async {
await sendCommand(Tap(finder, timeout: timeout));
}
/// Waits until [finder] locates the target.
///
/// The [finder] will wait until there is no pending frame scheduled
/// in the app under test before executing an action.
///
/// See also:
///
/// * [FlutterDriver.runUnsynchronized], which will execute an action
/// with frame sync disabled even while frames are pending.
Future<void> waitFor(SerializableFinder finder, { Duration? timeout }) async {
await sendCommand(WaitFor(finder, timeout: timeout));
}
/// Waits until [finder] can no longer locate the target.
Future<void> waitForAbsent(SerializableFinder finder, { Duration? timeout }) async {
await sendCommand(WaitForAbsent(finder, timeout: timeout));
}
/// Waits until [finder] is tappable.
Future<void> waitForTappable(SerializableFinder finder, { Duration? timeout }) async {
await sendCommand(WaitForTappable(finder, timeout: timeout));
}
/// Waits until the given [waitCondition] is satisfied.
Future<void> waitForCondition(SerializableWaitCondition waitCondition, {Duration? timeout}) async {
await sendCommand(WaitForCondition(waitCondition, timeout: timeout));
}
/// Waits until there are no more transient callbacks in the queue.
///
/// Use this method when you need to wait for the moment when the application
/// becomes "stable", for example, prior to taking a [screenshot].
Future<void> waitUntilNoTransientCallbacks({ Duration? timeout }) async {
await sendCommand(WaitForCondition(const NoTransientCallbacks(), timeout: timeout));
}
/// Waits until the next [dart:ui.PlatformDispatcher.onReportTimings] is
/// called.
///
/// Use this method to wait for the first frame to be rasterized during the
/// app launch.
///
/// Throws [UnimplementedError] on [WebFlutterDriver] instances.
Future<void> waitUntilFirstFrameRasterized() async {
await sendCommand(const WaitForCondition(FirstFrameRasterized()));
}
Future<DriverOffset> _getOffset(SerializableFinder finder, OffsetType type, { Duration? timeout }) async {
final GetOffset command = GetOffset(finder, type, timeout: timeout);
final GetOffsetResult result = GetOffsetResult.fromJson(await sendCommand(command));
return DriverOffset(result.dx, result.dy);
}
/// Returns the point at the top left of the widget identified by `finder`.
///
/// The offset is expressed in logical pixels and can be translated to
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
Future<DriverOffset> getTopLeft(SerializableFinder finder, { Duration? timeout }) async {
return _getOffset(finder, OffsetType.topLeft, timeout: timeout);
}
/// Returns the point at the top right of the widget identified by `finder`.
///
/// The offset is expressed in logical pixels and can be translated to
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
Future<DriverOffset> getTopRight(SerializableFinder finder, { Duration? timeout }) async {
return _getOffset(finder, OffsetType.topRight, timeout: timeout);
}
/// Returns the point at the bottom left of the widget identified by `finder`.
///
/// The offset is expressed in logical pixels and can be translated to
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
Future<DriverOffset> getBottomLeft(SerializableFinder finder, { Duration? timeout }) async {
return _getOffset(finder, OffsetType.bottomLeft, timeout: timeout);
}
/// Returns the point at the bottom right of the widget identified by `finder`.
///
/// The offset is expressed in logical pixels and can be translated to
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
Future<DriverOffset> getBottomRight(SerializableFinder finder, { Duration? timeout }) async {
return _getOffset(finder, OffsetType.bottomRight, timeout: timeout);
}
/// Returns the point at the center of the widget identified by `finder`.
///
/// The offset is expressed in logical pixels and can be translated to
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
Future<DriverOffset> getCenter(SerializableFinder finder, { Duration? timeout }) async {
return _getOffset(finder, OffsetType.center, timeout: timeout);
}
/// Returns a JSON map of the [DiagnosticsNode] that is associated with the
/// [RenderObject] identified by `finder`.
///
/// The `subtreeDepth` argument controls how many layers of children will be
/// included in the result. It defaults to zero, which means that no children
/// of the [RenderObject] identified by `finder` will be part of the result.
///
/// The `includeProperties` argument controls whether properties of the
/// [DiagnosticsNode]s will be included in the result. It defaults to true.
///
/// [RenderObject]s are responsible for positioning, layout, and painting on
/// the screen, based on the configuration from a [Widget]. Callers that need
/// information about size or position should use this method.
///
/// A widget may indirectly create multiple [RenderObject]s, which each
/// implement some aspect of the widget configuration. A 1:1 relationship
/// should not be assumed.
///
/// See also:
///
/// * [getWidgetDiagnostics], which gets the [DiagnosticsNode] of a [Widget].
Future<Map<String, Object?>> getRenderObjectDiagnostics(
SerializableFinder finder, {
int subtreeDepth = 0,
bool includeProperties = true,
Duration? timeout,
}) async {
return sendCommand(GetDiagnosticsTree(
finder,
DiagnosticsType.renderObject,
subtreeDepth: subtreeDepth,
includeProperties: includeProperties,
timeout: timeout,
));
}
/// Returns a JSON map of the [DiagnosticsNode] that is associated with the
/// [Widget] identified by `finder`.
///
/// The `subtreeDepth` argument controls how many layers of children will be
/// included in the result. It defaults to zero, which means that no children
/// of the [Widget] identified by `finder` will be part of the result.
///
/// The `includeProperties` argument controls whether properties of the
/// [DiagnosticsNode]s will be included in the result. It defaults to true.
///
/// [Widget]s describe configuration for the rendering tree. Individual
/// widgets may create multiple [RenderObject]s to actually layout and paint
/// the desired configuration.
///
/// See also:
///
/// * [getRenderObjectDiagnostics], which gets the [DiagnosticsNode] of a
/// [RenderObject].
Future<Map<String, Object?>> getWidgetDiagnostics(
SerializableFinder finder, {
int subtreeDepth = 0,
bool includeProperties = true,
Duration? timeout,
}) async {
return sendCommand(GetDiagnosticsTree(
finder,
DiagnosticsType.widget,
subtreeDepth: subtreeDepth,
includeProperties: includeProperties,
timeout: timeout,
));
}
/// Tell the driver to perform a scrolling action.
///
/// A scrolling action begins with a "pointer down" event, which commonly maps
/// to finger press on the touch screen or mouse button press. A series of
/// "pointer move" events follow. The action is completed by a "pointer up"
/// event.
///
/// [dx] and [dy] specify the total offset for the entire scrolling action.
///
/// [duration] specifies the length of the action.
///
/// The move events are generated at a given [frequency] in Hz (or events per
/// second). It defaults to 60Hz.
Future<void> scroll(SerializableFinder finder, double dx, double dy, Duration duration, { int frequency = 60, Duration? timeout }) async {
await sendCommand(Scroll(finder, dx, dy, duration, frequency, timeout: timeout));
}
/// Scrolls the Scrollable ancestor of the widget located by [finder]
/// until the widget is completely visible.
///
/// If the widget located by [finder] is contained by a scrolling widget
/// that lazily creates its children, like [ListView] or [CustomScrollView],
/// then this method may fail because [finder] doesn't actually exist.
/// The [scrollUntilVisible] method can be used in this case.
Future<void> scrollIntoView(SerializableFinder finder, { double alignment = 0.0, Duration? timeout }) async {
await sendCommand(ScrollIntoView(finder, alignment: alignment, timeout: timeout));
}
/// Repeatedly [scroll] the widget located by [scrollable] by [dxScroll] and
/// [dyScroll] until [item] is visible, and then use [scrollIntoView] to
/// ensure the item's final position matches [alignment].
///
/// The [scrollable] must locate the scrolling widget that contains [item].
/// Typically `find.byType('ListView')` or `find.byType('CustomScrollView')`.
///
/// At least one of [dxScroll] and [dyScroll] must be non-zero.
///
/// If [item] is below the currently visible items, then specify a negative
/// value for [dyScroll] that's a small enough increment to expose [item]
/// without potentially scrolling it up and completely out of view. Similarly
/// if [item] is above, then specify a positive value for [dyScroll].
///
/// If [item] is to the right of the currently visible items, then
/// specify a negative value for [dxScroll] that's a small enough increment to
/// expose [item] without potentially scrolling it up and completely out of
/// view. Similarly if [item] is to the left, then specify a positive value
/// for [dyScroll].
///
/// The [timeout] value should be long enough to accommodate as many scrolls
/// as needed to bring an item into view. The default is to not time out.
Future<void> scrollUntilVisible(
SerializableFinder scrollable,
SerializableFinder item, {
double alignment = 0.0,
double dxScroll = 0.0,
double dyScroll = 0.0,
Duration? timeout,
}) async {
assert(dxScroll != 0.0 || dyScroll != 0.0);
// Kick off an (unawaited) waitFor that will complete when the item we're
// looking for finally scrolls onscreen. We add an initial pause to give it
// the chance to complete if the item is already onscreen; if not, scroll
// repeatedly until we either find the item or time out.
bool isVisible = false;
waitFor(item, timeout: timeout).then<void>((_) { isVisible = true; });
await Future<void>.delayed(const Duration(milliseconds: 500));
while (!isVisible) {
await scroll(scrollable, dxScroll, dyScroll, const Duration(milliseconds: 100));
await Future<void>.delayed(const Duration(milliseconds: 500));
}
return scrollIntoView(item, alignment: alignment);
}
/// Returns the text in the `Text` widget located by [finder].
Future<String> getText(SerializableFinder finder, { Duration? timeout }) async {
return GetTextResult.fromJson(await sendCommand(GetText(finder, timeout: timeout))).text;
}
/// Enters `text` into the currently focused text input, such as the
/// [EditableText] widget.
///
/// This method does not use the operating system keyboard to enter text.
/// Instead it emulates text entry by sending events identical to those sent
/// by the operating system keyboard (the "TextInputClient.updateEditingState"
/// method channel call).
///
/// Generally the behavior is dependent on the implementation of the widget
/// receiving the input. Usually, editable widgets, such as [EditableText] and
/// those built on top of it would replace the currently entered text with the
/// provided `text`.
///
/// It is assumed that the widget receiving text input is focused prior to
/// calling this method. Typically, a test would activate a widget, e.g. using
/// [tap], then call this method.
///
/// For this method to work, text emulation must be enabled (see
/// [setTextEntryEmulation]). Text emulation is enabled by default.
///
/// Example:
///
/// ```dart
/// test('enters text in a text field', () async {
/// final SerializableFinder textField = find.byValueKey('enter-text-field');
/// await driver.tap(textField); // acquire focus
/// await driver.enterText('Hello!'); // enter text
/// await driver.waitFor(find.text('Hello!')); // verify text appears on UI
/// await driver.enterText('World!'); // enter another piece of text
/// await driver.waitFor(find.text('World!')); // verify new text appears
/// });
/// ```
Future<void> enterText(String text, { Duration? timeout }) async {
await sendCommand(EnterText(text, timeout: timeout));
}
/// Configures text entry emulation.
///
/// If `enabled` is true, enables text entry emulation via [enterText]. If
/// `enabled` is false, disables it. By default text entry emulation is
/// enabled.
///
/// When disabled, [enterText] will fail with a [DriverError]. When an
/// [EditableText] is focused, the operating system's configured keyboard
/// method is invoked, such as an on-screen keyboard on a phone or a tablet.
///
/// When enabled, the operating system's configured keyboard will not be
/// invoked when the widget is focused, as the [SystemChannels.textInput]
/// channel will be mocked out.
Future<void> setTextEntryEmulation({ required bool enabled, Duration? timeout }) async {
await sendCommand(SetTextEntryEmulation(enabled, timeout: timeout));
}
/// Simulate the user posting a text input action.
///
/// The available action types can be found in [TextInputAction]. The [sendTextInputAction]
/// does not check whether the [TextInputAction] performed is acceptable
/// based on the client arguments of the text input.
///
/// This can be called even if the [TestTextInput] has not been [TestTextInput.register]ed.
///
/// Example:
/// {@tool snippet}
///
/// ```dart
/// test('submit text in a text field', () async {
/// final SerializableFinder textField = find.byValueKey('enter-text-field');
/// await driver.tap(textField); // acquire focus
/// await driver.enterText('Hello!'); // enter text
/// await driver.waitFor(find.text('Hello!')); // verify text appears on UI
/// await driver.sendTextInputAction(TextInputAction.done); // submit text
/// });
/// ```
/// {@end-tool}
///
Future<void> sendTextInputAction(TextInputAction action,
{Duration? timeout}) async {
await sendCommand(SendTextInputAction(action, timeout: timeout));
}
/// Sends a string and returns a string.
///
/// This enables generic communication between the driver and the application.
/// It's expected that the application has registered a [DataHandler]
/// callback in [enableFlutterDriverExtension] that can successfully handle
/// these requests.
Future<String> requestData(String? message, { Duration? timeout }) async {
return RequestDataResult.fromJson(await sendCommand(RequestData(message, timeout: timeout))).message;
}
/// Turns semantics on or off in the Flutter app under test.
///
/// Returns true when the call actually changed the state from on to off or
/// vice versa.
///
/// Does not enable or disable the assistive technology installed on the
/// device. For example, this does not enable VoiceOver on iOS, TalkBack on
/// Android, or NVDA on Windows.
///
/// Enabling semantics on the web causes the engine to render ARIA-annotated
/// HTML.
Future<bool> setSemantics(bool enabled, { Duration? timeout }) async {
final SetSemanticsResult result = SetSemanticsResult.fromJson(await sendCommand(SetSemantics(enabled, timeout: timeout)));
return result.changedState;
}
/// Retrieves the semantics node id for the object returned by `finder`, or
/// the nearest ancestor with a semantics node.
///
/// Throws an error if `finder` returns multiple elements or a semantics
/// node is not found.
///
/// Semantics must be enabled to use this method, either using a platform
/// specific shell command or [setSemantics].
Future<int> getSemanticsId(SerializableFinder finder, { Duration? timeout }) async {
final Map<String, dynamic> jsonResponse = await sendCommand(GetSemanticsId(finder, timeout: timeout));
final GetSemanticsIdResult result = GetSemanticsIdResult.fromJson(jsonResponse);
return result.id;
}
/// Take a screenshot.
///
/// The image will be returned as a PNG.
///
/// **Warning:** This is not reliable.
///
/// There is a two-second artificial delay before screenshotting. The delay
/// here is to deal with a race between the driver script and the raster
/// thread (formerly known as the GPU thread). The issue is that the driver
/// API synchronizes with the framework based on transient callbacks, which
/// are out of sync with the raster thread.
///
/// Here's the timeline of events in ASCII art:
///
/// ---------------------------------------------------------------
/// Without this delay:
/// ---------------------------------------------------------------
/// UI : <-- build -->
/// Raster: <-- rasterize -->
/// Gap : | random |
/// Driver: <-- screenshot -->
///
/// In the diagram above, the gap is the time between the last driver action
/// taken, such as a `tap()`, and the subsequent call to `screenshot()`. The
/// gap is random because it is determined by the unpredictable communication
/// channel between the driver process and the application. If this gap is too
/// short, which it typically will be, the screenshot is taken before the
/// raster thread is done rasterizing the frame, so the screenshot of the
/// previous frame is taken, which is not what is intended.
///
/// ---------------------------------------------------------------
/// With this delay, if we're lucky:
/// ---------------------------------------------------------------
/// UI : <-- build -->
/// Raster: <-- rasterize -->
/// Gap : | 2 seconds or more |
/// Driver: <-- screenshot -->
///
/// The two-second gap should be long enough for the raster thread to finish
/// rasterizing the frame, but not longer than necessary to keep driver tests
/// as fast a possible.
///
/// ---------------------------------------------------------------
/// With this delay, if we're not lucky:
/// ---------------------------------------------------------------
/// UI : <-- build -->
/// Raster: <-- rasterize randomly slow today -->
/// Gap : | 2 seconds or more |
/// Driver: <-- screenshot -->
///
/// In practice, sometimes the device gets really busy for a while and even
/// two seconds isn't enough, which means that this is still racy and a source
/// of flakes.
Future<List<int>> screenshot() async {
throw UnimplementedError();
}
/// Returns the Flags set in the Dart VM as JSON.
///
/// See the complete documentation for [the `getFlagList` Dart VM service
/// method][getFlagList].
///
/// Example return value:
///
/// [
/// {
/// "name": "timeline_recorder",
/// "comment": "Select the timeline recorder used. Valid values: ring, endless, startup, and systrace.",
/// "modified": false,
/// "_flagType": "String",
/// "valueAsString": "ring"
/// },
/// ...
/// ]
///
/// [getFlagList]: https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md#getflaglist
///
/// Throws [UnimplementedError] on [WebFlutterDriver] instances.
Future<List<Map<String, dynamic>>> getVmFlags() async {
throw UnimplementedError();
}
/// Starts recording performance traces.
///
/// The `timeout` argument causes a warning to be displayed to the user if the
/// operation exceeds the specified timeout; it does not actually cancel the
/// operation.
///
/// For [WebFlutterDriver], this is only supported for Chrome.
Future<void> startTracing({
List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all],
Duration timeout = kUnusuallyLongTimeout,
}) async {
throw UnimplementedError();
}
/// Stops recording performance traces and downloads the timeline.
///
/// The `timeout` argument causes a warning to be displayed to the user if the
/// operation exceeds the specified timeout; it does not actually cancel the
/// operation.
///
/// For [WebFlutterDriver], this is only supported for Chrome.
Future<Timeline> stopTracingAndDownloadTimeline({
Duration timeout = kUnusuallyLongTimeout,
}) async {
throw UnimplementedError();
}
/// Runs [action] and outputs a performance trace for it.
///
/// Waits for the `Future` returned by [action] to complete prior to stopping
/// the trace.
///
/// This is merely a convenience wrapper on top of [startTracing] and
/// [stopTracingAndDownloadTimeline].
///
/// [streams] limits the recorded timeline event streams to only the ones
/// listed. By default, all streams are recorded.
///
/// If [retainPriorEvents] is true, retains events recorded prior to calling
/// [action]. Otherwise, prior events are cleared before calling [action]. By
/// default, prior events are cleared.
///
/// If this is run in debug mode, a warning message will be printed to suggest
/// running the benchmark in profile mode instead.
///
/// For [WebFlutterDriver], this is only supported for Chrome.
Future<Timeline> traceAction(
Future<dynamic> Function() action, {
List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all],
bool retainPriorEvents = false,
}) async {
throw UnimplementedError();
}
/// Clears all timeline events recorded up until now.
///
/// The `timeout` argument causes a warning to be displayed to the user if the
/// operation exceeds the specified timeout; it does not actually cancel the
/// operation.
///
/// For [WebFlutterDriver], this is only supported for Chrome.
Future<void> clearTimeline({
Duration timeout = kUnusuallyLongTimeout,
}) async {
throw UnimplementedError();
}
/// [action] will be executed with the frame sync mechanism disabled.
///
/// By default, Flutter Driver waits until there is no pending frame scheduled
/// in the app under test before executing an action. This mechanism is called
/// "frame sync". It greatly reduces flakiness because Flutter Driver will not
/// execute an action while the app under test is undergoing a transition.
///
/// Having said that, sometimes it is necessary to disable the frame sync
/// mechanism (e.g. if there is an ongoing animation in the app, it will
/// never reach a state where there are no pending frames scheduled and the
/// action will time out). For these cases, the sync mechanism can be disabled
/// by wrapping the actions to be performed by this [runUnsynchronized] method.
///
/// With frame sync disabled, it's the responsibility of the test author to
/// ensure that no action is performed while the app is undergoing a
/// transition to avoid flakiness.
Future<T> runUnsynchronized<T>(Future<T> Function() action, { Duration? timeout }) async {
await sendCommand(SetFrameSync(false, timeout: timeout));
T result;
try {
result = await action();
} finally {
await sendCommand(SetFrameSync(true, timeout: timeout));
}
return result;
}
/// Force a garbage collection run in the VM.
///
/// Throws [UnimplementedError] on [WebFlutterDriver] instances.
Future<void> forceGC() async {
throw UnimplementedError();
}
/// Closes the underlying connection to the VM service.
///
/// Returns a [Future] that fires once the connection has been closed.
Future<void> close() async {
throw UnimplementedError();
}
}
/// Provides convenient accessors to frequently used finders.
class CommonFinders {
const CommonFinders._();
/// Finds [widgets.Text] and [widgets.EditableText] widgets containing string
/// equal to [text].
SerializableFinder text(String text) => ByText(text);
/// Finds widgets by [key]. Only [String] and [int] values can be used.
SerializableFinder byValueKey(dynamic key) => ByValueKey(key);
/// Finds widgets with a tooltip with the given [message].
SerializableFinder byTooltip(String message) => ByTooltipMessage(message);
/// Finds widgets with the given semantics [label].
SerializableFinder bySemanticsLabel(Pattern label) => BySemanticsLabel(label);
/// Finds widgets whose class name matches the given string.
SerializableFinder byType(String type) => ByType(type);
/// Finds the back button on a Material or Cupertino page's scaffold.
SerializableFinder pageBack() => const PageBack();
/// Finds the widget that is an ancestor of the `of` parameter and that
/// matches the `matching` parameter.
///
/// If the `matchRoot` argument is true then the widget specified by `of` will
/// be considered for a match. The argument defaults to false.
///
/// If `firstMatchOnly` is true then only the first ancestor matching
/// `matching` will be returned. Defaults to false.
SerializableFinder ancestor({
required SerializableFinder of,
required SerializableFinder matching,
bool matchRoot = false,
bool firstMatchOnly = false,
}) => Ancestor(of: of, matching: matching, matchRoot: matchRoot, firstMatchOnly: firstMatchOnly);
/// Finds the widget that is an descendant of the `of` parameter and that
/// matches the `matching` parameter.
///
/// If the `matchRoot` argument is true then the widget specified by `of` will
/// be considered for a match. The argument defaults to false.
///
/// If `firstMatchOnly` is true then only the first descendant matching
/// `matching` will be returned. Defaults to false.
SerializableFinder descendant({
required SerializableFinder of,
required SerializableFinder matching,
bool matchRoot = false,
bool firstMatchOnly = false,
}) => Descendant(of: of, matching: matching, matchRoot: matchRoot, firstMatchOnly: firstMatchOnly);
}
/// An immutable 2D floating-point offset used by Flutter Driver.
@immutable
class DriverOffset {
/// Creates an offset.
const DriverOffset(this.dx, this.dy);
/// The x component of the offset.
final double dx;
/// The y component of the offset.
final double dy;
@override
String toString() => '$runtimeType($dx, $dy)'; // ignore: no_runtimetype_tostring, can't access package:flutter here to use objectRuntimeType
@override
bool operator ==(Object other) {
return other is DriverOffset
&& other.dx == dx
&& other.dy == dy;
}
@override
int get hashCode => Object.hash(dx, dy);
}
| flutter/packages/flutter_driver/lib/src/driver/driver.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/driver/driver.dart",
"repo_id": "flutter",
"token_count": 9840
} | 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 'dart:convert';
import 'dart:html' as html;
import 'dart:js';
import 'dart:js_util' as js_util;
/// The dart:html implementation of [registerWebServiceExtension].
///
/// Registers Web Service Extension for Flutter Web application.
///
/// window.$flutterDriver will be called by Flutter Web Driver to process
/// Flutter Command.
///
/// See also:
///
/// * [_extension_io.dart], which has the dart:io implementation
void registerWebServiceExtension(Future<Map<String, dynamic>> Function(Map<String, String>) call) {
// Define the result variable because packages/flutter_driver/lib/src/driver/web_driver.dart
// checks for this value to become non-null when waiting for the result. If this value is
// undefined at the time of the check, WebDriver throws an exception.
context[r'$flutterDriverResult'] = null;
js_util.setProperty(html.window, r'$flutterDriver', allowInterop((dynamic message) async {
final Map<String, String> params = Map<String, String>.from(
jsonDecode(message as String) as Map<String, dynamic>);
final Map<String, dynamic> result = Map<String, dynamic>.from(
await call(params));
context[r'$flutterDriverResult'] = json.encode(result);
}));
}
| flutter/packages/flutter_driver/lib/src/extension/_extension_web.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/extension/_extension_web.dart",
"repo_id": "flutter",
"token_count": 417
} | 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:flutter_driver/flutter_driver.dart' as flutter_driver;
import 'package:flutter_test/flutter_test.dart';
void main() {
test('flutter_driver.TextInputAction should be sync with TextInputAction',
() {
final List<String> actual = flutter_driver.TextInputAction.values
.map((flutter_driver.TextInputAction action) => action.name)
.toList();
final List<String> matcher = TextInputAction.values
.map((TextInputAction action) => action.name)
.toList();
expect(actual, matcher);
});
}
| flutter/packages/flutter_driver/test/src/real_tests/text_input_action_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test/src/real_tests/text_input_action_test.dart",
"repo_id": "flutter",
"token_count": 243
} | 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 'dart:async' show FutureOr;
import 'dart:io' as io show OSError, SocketException;
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform/platform.dart';
import 'skia_client.dart';
export 'skia_client.dart';
// If you are here trying to figure out how to use golden files in the Flutter
// repo itself, consider reading this wiki page:
// https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package%3Aflutter
// If you are trying to debug this package, you may like to use the golden test
// titled "Inconsequential golden test" in this file:
// /packages/flutter/test/widgets/basic_test.dart
const String _kFlutterRootKey = 'FLUTTER_ROOT';
bool _isMainBranch(String? branch) {
return branch == 'main'
|| branch == 'master';
}
/// Main method that can be used in a `flutter_test_config.dart` file to set
/// [goldenFileComparator] to an instance of [FlutterGoldenFileComparator] that
/// works for the current test. _Which_ FlutterGoldenFileComparator is
/// instantiated is based on the current testing environment.
///
/// When set, the `namePrefix` is prepended to the names of all gold images.
Future<void> testExecutable(FutureOr<void> Function() testMain, {String? namePrefix}) async {
const Platform platform = LocalPlatform();
if (FlutterPostSubmitFileComparator.isForEnvironment(platform)) {
goldenFileComparator = await FlutterPostSubmitFileComparator.fromDefaultComparator(platform, namePrefix: namePrefix, log: print);
} else if (FlutterPreSubmitFileComparator.isForEnvironment(platform)) {
goldenFileComparator = await FlutterPreSubmitFileComparator.fromDefaultComparator(platform, namePrefix: namePrefix, log: print);
} else if (FlutterSkippingFileComparator.isForEnvironment(platform)) {
goldenFileComparator = FlutterSkippingFileComparator.fromDefaultComparator(
'Golden file testing is not executed on Cirrus, or LUCI environments outside of flutter/flutter.',
namePrefix: namePrefix,
log: print
);
} else {
goldenFileComparator = await FlutterLocalFileComparator.fromDefaultComparator(platform, log: print);
}
await testMain();
}
/// Abstract base class golden file comparator specific to the `flutter/flutter`
/// repository.
///
/// Golden file testing for the `flutter/flutter` repository is handled by three
/// different [FlutterGoldenFileComparator]s, depending on the current testing
/// environment.
///
/// * The [FlutterPostSubmitFileComparator] is utilized during post-submit
/// testing, after a pull request has landed on the master branch. This
/// comparator uses the [SkiaGoldClient] and the `goldctl` tool to upload
/// tests to the [Flutter Gold dashboard](https://flutter-gold.skia.org).
/// Flutter Gold manages the master golden files for the `flutter/flutter`
/// repository.
///
/// * The [FlutterPreSubmitFileComparator] is utilized in pre-submit testing,
/// before a pull request lands on the master branch. This
/// comparator uses the [SkiaGoldClient] to execute tryjobs, allowing
/// contributors to view and check in visual differences before landing the
/// change.
///
/// * The [FlutterLocalFileComparator] is used for local development testing.
/// This comparator will use the [SkiaGoldClient] to request baseline images
/// from [Flutter Gold](https://flutter-gold.skia.org) and manually compare
/// pixels. If a difference is detected, this comparator will
/// generate failure output illustrating the found difference. If a baseline
/// is not found for a given test image, it will consider it a new test and
/// output the new image for verification.
///
/// The [FlutterSkippingFileComparator] is utilized to skip tests outside
/// of the appropriate environments described above. Currently, some Luci
/// environments do not execute golden file testing, and as such do not require
/// a comparator. This comparator is also used when an internet connection is
/// unavailable.
abstract class FlutterGoldenFileComparator extends GoldenFileComparator {
/// Creates a [FlutterGoldenFileComparator] that will resolve golden file
/// URIs relative to the specified [basedir], and retrieve golden baselines
/// using the [skiaClient]. The [basedir] is used for writing and accessing
/// information and files for interacting with the [skiaClient]. When testing
/// locally, the [basedir] will also contain any diffs from failed tests, or
/// goldens generated from newly introduced tests.
///
/// The [fs] and [platform] parameters are useful in tests, where the default
/// file system and platform can be replaced by mock instances.
@visibleForTesting
FlutterGoldenFileComparator(
this.basedir,
this.skiaClient, {
this.fs = const LocalFileSystem(),
this.platform = const LocalPlatform(),
this.namePrefix,
required this.log,
});
/// The directory to which golden file URIs will be resolved in [compare] and
/// [update].
final Uri basedir;
/// A client for uploading image tests and making baseline requests to the
/// Flutter Gold Dashboard.
final SkiaGoldClient skiaClient;
/// The file system used to perform file access.
@visibleForTesting
final FileSystem fs;
/// A wrapper for the [dart:io.Platform] API.
@visibleForTesting
final Platform platform;
/// The prefix that is added to all golden names.
final String? namePrefix;
/// The logging function to use when reporting messages to the console.
final LogCallback log;
@override
Future<void> update(Uri golden, Uint8List imageBytes) async {
final File goldenFile = getGoldenFile(golden);
await goldenFile.parent.create(recursive: true);
await goldenFile.writeAsBytes(imageBytes, flush: true);
}
@override
Uri getTestUri(Uri key, int? version) => key;
/// Calculate the appropriate basedir for the current test context.
///
/// The optional [suffix] argument is used by the
/// [FlutterPostSubmitFileComparator] and the [FlutterPreSubmitFileComparator].
/// These [FlutterGoldenFileComparators] randomize their base directories to
/// maintain thread safety while using the `goldctl` tool.
@protected
@visibleForTesting
static Directory getBaseDirectory(
LocalFileComparator defaultComparator,
Platform platform, {
String? suffix,
}) {
const FileSystem fs = LocalFileSystem();
final Directory flutterRoot = fs.directory(platform.environment[_kFlutterRootKey]);
Directory comparisonRoot;
if (suffix != null) {
comparisonRoot = fs.systemTempDirectory.createTempSync(suffix);
} else {
comparisonRoot = flutterRoot.childDirectory(
fs.path.join(
'bin',
'cache',
'pkg',
'skia_goldens',
)
);
}
final Directory testDirectory = fs.directory(defaultComparator.basedir);
final String testDirectoryRelativePath = fs.path.relative(
testDirectory.path,
from: flutterRoot.path,
);
return comparisonRoot.childDirectory(testDirectoryRelativePath);
}
/// Returns the golden [File] identified by the given [Uri].
@protected
File getGoldenFile(Uri uri) {
final File goldenFile = fs.directory(basedir).childFile(fs.file(uri).path);
return goldenFile;
}
/// Prepends the golden URL with the library name that encloses the current
/// test.
Uri _addPrefix(Uri golden) {
// Ensure the Uri ends in .png as the SkiaClient expects
assert(
golden.toString().split('.').last == 'png',
'Golden files in the Flutter framework must end with the file extension '
'.png.'
);
return Uri.parse(<String>[
if (namePrefix != null)
namePrefix!,
basedir.pathSegments[basedir.pathSegments.length - 2],
golden.toString(),
].join('.'));
}
}
/// A [FlutterGoldenFileComparator] for testing golden images with Skia Gold in
/// post-submit.
///
/// For testing across all platforms, the [SkiaGoldClient] is used to upload
/// images for framework-related golden tests and process results.
///
/// See also:
///
/// * [GoldenFileComparator], the abstract class that
/// [FlutterGoldenFileComparator] implements.
/// * [FlutterPreSubmitFileComparator], another
/// [FlutterGoldenFileComparator] that tests golden images before changes are
/// merged into the master branch.
/// * [FlutterLocalFileComparator], another
/// [FlutterGoldenFileComparator] that tests golden images locally on your
/// current machine.
class FlutterPostSubmitFileComparator extends FlutterGoldenFileComparator {
/// Creates a [FlutterPostSubmitFileComparator] that will test golden file
/// images against Skia Gold.
///
/// The [fs] and [platform] parameters are useful in tests, where the default
/// file system and platform can be replaced by mock instances.
FlutterPostSubmitFileComparator(
super.basedir,
super.skiaClient, {
super.fs,
super.platform,
super.namePrefix,
required super.log,
});
/// Creates a new [FlutterPostSubmitFileComparator] that mirrors the relative
/// path resolution of the default [goldenFileComparator].
///
/// The [goldens] and [defaultComparator] parameters are visible for testing
/// purposes only.
static Future<FlutterPostSubmitFileComparator> fromDefaultComparator(
final Platform platform, {
SkiaGoldClient? goldens,
LocalFileComparator? defaultComparator,
String? namePrefix,
required LogCallback log,
}) async {
defaultComparator ??= goldenFileComparator as LocalFileComparator;
final Directory baseDirectory = FlutterGoldenFileComparator.getBaseDirectory(
defaultComparator,
platform,
suffix: 'flutter_goldens_postsubmit.',
);
baseDirectory.createSync(recursive: true);
goldens ??= SkiaGoldClient(baseDirectory, log: log);
await goldens.auth();
return FlutterPostSubmitFileComparator(baseDirectory.uri, goldens, namePrefix: namePrefix, log: log);
}
@override
Future<bool> compare(Uint8List imageBytes, Uri golden) async {
await skiaClient.imgtestInit();
golden = _addPrefix(golden);
await update(golden, imageBytes);
final File goldenFile = getGoldenFile(golden);
return skiaClient.imgtestAdd(golden.path, goldenFile);
}
/// Decides based on the current environment if goldens tests should be
/// executed through Skia Gold.
static bool isForEnvironment(Platform platform) {
final bool luciPostSubmit = platform.environment.containsKey('SWARMING_TASK_ID')
&& platform.environment.containsKey('GOLDCTL')
// Luci tryjob environments contain this value to inform the [FlutterPreSubmitComparator].
&& !platform.environment.containsKey('GOLD_TRYJOB')
// Only run on main branch.
&& _isMainBranch(platform.environment['GIT_BRANCH']);
return luciPostSubmit;
}
}
/// A [FlutterGoldenFileComparator] for testing golden images before changes are
/// merged into the master branch. The comparator executes tryjobs using the
/// [SkiaGoldClient].
///
/// See also:
///
/// * [GoldenFileComparator], the abstract class that
/// [FlutterGoldenFileComparator] implements.
/// * [FlutterPostSubmitFileComparator], another
/// [FlutterGoldenFileComparator] that uploads tests to the Skia Gold
/// dashboard in post-submit.
/// * [FlutterLocalFileComparator], another
/// [FlutterGoldenFileComparator] that tests golden images locally on your
/// current machine.
class FlutterPreSubmitFileComparator extends FlutterGoldenFileComparator {
/// Creates a [FlutterPreSubmitFileComparator] that will test golden file
/// images against baselines requested from Flutter Gold.
///
/// The [fs] and [platform] parameters are useful in tests, where the default
/// file system and platform can be replaced by mock instances.
FlutterPreSubmitFileComparator(
super.basedir,
super.skiaClient, {
super.fs,
super.platform,
super.namePrefix,
required super.log,
});
/// Creates a new [FlutterPreSubmitFileComparator] that mirrors the
/// relative path resolution of the default [goldenFileComparator].
///
/// The [goldens] and [defaultComparator] parameters are visible for testing
/// purposes only.
static Future<FlutterGoldenFileComparator> fromDefaultComparator(
final Platform platform, {
SkiaGoldClient? goldens,
LocalFileComparator? defaultComparator,
Directory? testBasedir,
String? namePrefix,
required LogCallback log,
}) async {
defaultComparator ??= goldenFileComparator as LocalFileComparator;
final Directory baseDirectory = testBasedir ?? FlutterGoldenFileComparator.getBaseDirectory(
defaultComparator,
platform,
suffix: 'flutter_goldens_presubmit.',
);
if (!baseDirectory.existsSync()) {
baseDirectory.createSync(recursive: true);
}
goldens ??= SkiaGoldClient(baseDirectory, log: log);
await goldens.auth();
return FlutterPreSubmitFileComparator(
baseDirectory.uri,
goldens, platform: platform,
namePrefix: namePrefix,
log: log,
);
}
@override
Future<bool> compare(Uint8List imageBytes, Uri golden) async {
await skiaClient.tryjobInit();
golden = _addPrefix(golden);
await update(golden, imageBytes);
final File goldenFile = getGoldenFile(golden);
await skiaClient.tryjobAdd(golden.path, goldenFile);
// This will always return true since golden file test failures are managed
// in pre-submit checks by the flutter-gold status check.
return true;
}
/// Decides based on the current environment if goldens tests should be
/// executed as pre-submit tests with Skia Gold.
static bool isForEnvironment(Platform platform) {
final bool luciPreSubmit = platform.environment.containsKey('SWARMING_TASK_ID')
&& platform.environment.containsKey('GOLDCTL')
&& platform.environment.containsKey('GOLD_TRYJOB')
// Only run on the main branch
&& _isMainBranch(platform.environment['GIT_BRANCH']);
return luciPreSubmit;
}
}
/// A [FlutterGoldenFileComparator] for testing conditions that do not execute
/// golden file tests.
///
/// Currently, this comparator is used on Cirrus, or in Luci environments when executing tests
/// outside of the flutter/flutter repository.
///
/// See also:
///
/// * [FlutterPostSubmitFileComparator], another [FlutterGoldenFileComparator]
/// that tests golden images through Skia Gold.
/// * [FlutterPreSubmitFileComparator], another
/// [FlutterGoldenFileComparator] that tests golden images before changes are
/// merged into the master branch.
/// * [FlutterLocalFileComparator], another
/// [FlutterGoldenFileComparator] that tests golden images locally on your
/// current machine.
class FlutterSkippingFileComparator extends FlutterGoldenFileComparator {
/// Creates a [FlutterSkippingFileComparator] that will skip tests that
/// are not in the right environment for golden file testing.
FlutterSkippingFileComparator(
super.basedir,
super.skiaClient,
this.reason, {
super.namePrefix,
required super.log,
});
/// Describes the reason for using the [FlutterSkippingFileComparator].
final String reason;
/// Creates a new [FlutterSkippingFileComparator] that mirrors the
/// relative path resolution of the default [goldenFileComparator].
static FlutterSkippingFileComparator fromDefaultComparator(
String reason, {
LocalFileComparator? defaultComparator,
String? namePrefix,
required LogCallback log,
}) {
defaultComparator ??= goldenFileComparator as LocalFileComparator;
const FileSystem fs = LocalFileSystem();
final Uri basedir = defaultComparator.basedir;
final SkiaGoldClient skiaClient = SkiaGoldClient(fs.directory(basedir), log: log);
return FlutterSkippingFileComparator(basedir, skiaClient, reason, namePrefix: namePrefix, log: log);
}
@override
Future<bool> compare(Uint8List imageBytes, Uri golden) async {
log('Skipping "$golden" test: $reason');
return true;
}
@override
Future<void> update(Uri golden, Uint8List imageBytes) async {}
/// Decides, based on the current environment, if this comparator should be
/// used.
///
/// If we are in a CI environment, LUCI or Cirrus, but are not using the other
/// comparators, we skip.
static bool isForEnvironment(Platform platform) {
return (platform.environment.containsKey('SWARMING_TASK_ID')
// Some builds are still being run on Cirrus, we should skip these.
|| platform.environment.containsKey('CIRRUS_CI'))
// If we are in CI, skip on branches that are not main.
&& !_isMainBranch(platform.environment['GIT_BRANCH']);
}
}
/// A [FlutterGoldenFileComparator] for testing golden images locally on your
/// current machine.
///
/// This comparator utilizes the [SkiaGoldClient] to request baseline images for
/// the given device under test for comparison. This comparator is initialized
/// when conditions for all other [FlutterGoldenFileComparators] have not been
/// met, see the `isForEnvironment` method for each one listed below.
///
/// The [FlutterLocalFileComparator] is intended to run on local machines and
/// serve as a smoke test during development. As such, it will not be able to
/// detect unintended changes on environments other than the currently executing
/// machine, until they are tested using the [FlutterPreSubmitFileComparator].
///
/// See also:
///
/// * [GoldenFileComparator], the abstract class that
/// [FlutterGoldenFileComparator] implements.
/// * [FlutterPostSubmitFileComparator], another
/// [FlutterGoldenFileComparator] that uploads tests to the Skia Gold
/// dashboard.
/// * [FlutterPreSubmitFileComparator], another
/// [FlutterGoldenFileComparator] that tests golden images before changes are
/// merged into the master branch.
/// * [FlutterSkippingFileComparator], another
/// [FlutterGoldenFileComparator] that controls post-submit testing
/// conditions that do not execute golden file tests.
class FlutterLocalFileComparator extends FlutterGoldenFileComparator with LocalComparisonOutput {
/// Creates a [FlutterLocalFileComparator] that will test golden file
/// images against baselines requested from Flutter Gold.
///
/// The [fs] and [platform] parameters are useful in tests, where the default
/// file system and platform can be replaced by mock instances.
FlutterLocalFileComparator(
super.basedir,
super.skiaClient, {
super.fs,
super.platform,
required super.log,
});
/// Creates a new [FlutterLocalFileComparator] that mirrors the
/// relative path resolution of the default [goldenFileComparator].
///
/// The [goldens], [defaultComparator], and [baseDirectory] parameters are
/// visible for testing purposes only.
static Future<FlutterGoldenFileComparator> fromDefaultComparator(
final Platform platform, {
SkiaGoldClient? goldens,
LocalFileComparator? defaultComparator,
Directory? baseDirectory,
required LogCallback log,
}) async {
defaultComparator ??= goldenFileComparator as LocalFileComparator;
baseDirectory ??= FlutterGoldenFileComparator.getBaseDirectory(
defaultComparator,
platform,
);
if (!baseDirectory.existsSync()) {
baseDirectory.createSync(recursive: true);
}
goldens ??= SkiaGoldClient(baseDirectory, log: log);
try {
// Check if we can reach Gold.
await goldens.getExpectationForTest('');
} on io.OSError catch (_) {
return FlutterSkippingFileComparator(
baseDirectory.uri,
goldens,
'OSError occurred, could not reach Gold. '
'Switching to FlutterSkippingGoldenFileComparator.',
log: log,
);
} on io.SocketException catch (_) {
return FlutterSkippingFileComparator(
baseDirectory.uri,
goldens,
'SocketException occurred, could not reach Gold. '
'Switching to FlutterSkippingGoldenFileComparator.',
log: log,
);
} on FormatException catch (_) {
return FlutterSkippingFileComparator(
baseDirectory.uri,
goldens,
'FormatException occurred, could not reach Gold. '
'Switching to FlutterSkippingGoldenFileComparator.',
log: log,
);
}
return FlutterLocalFileComparator(baseDirectory.uri, goldens, log: log);
}
@override
Future<bool> compare(Uint8List imageBytes, Uri golden) async {
golden = _addPrefix(golden);
final String testName = skiaClient.cleanTestName(golden.path);
late String? testExpectation;
testExpectation = await skiaClient.getExpectationForTest(testName);
if (testExpectation == null || testExpectation.isEmpty) {
log(
'No expectations provided by Skia Gold for test: $golden. '
'This may be a new test. If this is an unexpected result, check '
'https://flutter-gold.skia.org.\n'
'Validate image output found at $basedir'
);
update(golden, imageBytes);
return true;
}
ComparisonResult result;
final List<int> goldenBytes = await skiaClient.getImageBytes(testExpectation);
result = await GoldenFileComparator.compareLists(
imageBytes,
goldenBytes,
);
if (result.passed) {
result.dispose();
return true;
}
final String error = await generateFailureOutput(result, golden, basedir);
result.dispose();
throw FlutterError(error);
}
}
| flutter/packages/flutter_goldens/lib/flutter_goldens.dart/0 | {
"file_path": "flutter/packages/flutter_goldens/lib/flutter_goldens.dart",
"repo_id": "flutter",
"token_count": 6770
} | 742 |
{
"datePickerHourSemanticsLabelOne": "$hour часа",
"datePickerHourSemanticsLabelOther": "$hour часа",
"datePickerMinuteSemanticsLabelOne": "1 минута",
"datePickerMinuteSemanticsLabelOther": "$minute минути",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "Днес",
"alertDialogLabel": "Сигнал",
"timerPickerHourLabelOne": "час",
"timerPickerHourLabelOther": "часа",
"timerPickerMinuteLabelOne": "мин",
"timerPickerMinuteLabelOther": "мин",
"timerPickerSecondLabelOne": "сек",
"timerPickerSecondLabelOther": "сек",
"cutButtonLabel": "Изрязване",
"copyButtonLabel": "Копиране",
"pasteButtonLabel": "Поставяне",
"clearButtonLabel": "Clear",
"selectAllButtonLabel": "Избиране на всички",
"tabSemanticsLabel": "Раздел $tabIndex от $tabCount",
"modalBarrierDismissLabel": "Отхвърляне",
"searchTextFieldPlaceholderLabel": "Търсене",
"noSpellCheckReplacementsLabel": "Не бяха намерени замествания",
"menuDismissLabel": "Отхвърляне на менюто",
"lookUpButtonLabel": "Look Up",
"searchWebButtonLabel": "Търсене в мрежата",
"shareButtonLabel": "Споделяне..."
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_bg.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_bg.arb",
"repo_id": "flutter",
"token_count": 591
} | 743 |
{
"datePickerHourSemanticsLabelOne": "$hour Uhr",
"datePickerHourSemanticsLabelOther": "$hour Uhr",
"datePickerMinuteSemanticsLabelOne": "1 Minute",
"datePickerMinuteSemanticsLabelOther": "$minute Minuten",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "Heute",
"alertDialogLabel": "Benachrichtigung",
"timerPickerHourLabelOne": "Stunde",
"timerPickerHourLabelOther": "Stunden",
"timerPickerMinuteLabelOne": "Min.",
"timerPickerMinuteLabelOther": "Min.",
"timerPickerSecondLabelOne": "s",
"timerPickerSecondLabelOther": "s",
"cutButtonLabel": "Ausschneiden",
"copyButtonLabel": "Kopieren",
"pasteButtonLabel": "Einsetzen",
"selectAllButtonLabel": "Alle auswählen",
"tabSemanticsLabel": "Tab $tabIndex von $tabCount",
"modalBarrierDismissLabel": "Schließen",
"searchTextFieldPlaceholderLabel": "Suche",
"noSpellCheckReplacementsLabel": "Keine Ersetzungen gefunden",
"menuDismissLabel": "Menü schließen",
"lookUpButtonLabel": "Nachschlagen",
"searchWebButtonLabel": "Im Web suchen",
"shareButtonLabel": "Teilen…",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_gsw.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_gsw.arb",
"repo_id": "flutter",
"token_count": 449
} | 744 |
{
"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": "$tabCount ичинен $tabIndex-өтмөк",
"modalBarrierDismissLabel": "Жабуу",
"searchTextFieldPlaceholderLabel": "Издөө",
"noSpellCheckReplacementsLabel": "Алмаштыруу үчүн сөз табылган жок",
"menuDismissLabel": "Менюну жабуу",
"lookUpButtonLabel": "Издөө",
"searchWebButtonLabel": "Интернеттен издөө",
"shareButtonLabel": "Бөлүшүү…",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ky.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ky.arb",
"repo_id": "flutter",
"token_count": 632
} | 745 |
{
"datePickerHourSemanticsLabelFew": "$hour",
"datePickerHourSemanticsLabelMany": "$hour",
"datePickerMinuteSemanticsLabelFew": "$minute minuty",
"datePickerMinuteSemanticsLabelMany": "$minute minut",
"timerPickerHourLabelFew": "godziny",
"timerPickerHourLabelMany": "godzin",
"timerPickerMinuteLabelFew": "min",
"timerPickerMinuteLabelMany": "min",
"timerPickerSecondLabelFew": "s",
"timerPickerSecondLabelMany": "s",
"datePickerHourSemanticsLabelOne": "$hour",
"datePickerHourSemanticsLabelOther": "$hour",
"datePickerMinuteSemanticsLabelOne": "1 minuta",
"datePickerMinuteSemanticsLabelOther": "$minute minuty",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "Dziś",
"alertDialogLabel": "Alert",
"timerPickerHourLabelOne": "godzina",
"timerPickerHourLabelOther": "godziny",
"timerPickerMinuteLabelOne": "min",
"timerPickerMinuteLabelOther": "min",
"timerPickerSecondLabelOne": "s",
"timerPickerSecondLabelOther": "s",
"cutButtonLabel": "Wytnij",
"copyButtonLabel": "Kopiuj",
"pasteButtonLabel": "Wklej",
"selectAllButtonLabel": "Wybierz wszystkie",
"tabSemanticsLabel": "Karta $tabIndex z $tabCount",
"modalBarrierDismissLabel": "Zamknij",
"searchTextFieldPlaceholderLabel": "Szukaj",
"noSpellCheckReplacementsLabel": "Brak wyników zamieniania",
"menuDismissLabel": "Zamknij menu",
"lookUpButtonLabel": "Sprawdź",
"searchWebButtonLabel": "Szukaj w internecie",
"shareButtonLabel": "Udostępnij…",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_pl.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_pl.arb",
"repo_id": "flutter",
"token_count": 603
} | 746 |
{
"licensesPackageDetailTextTwo": "ترخيصان ($licenseCount)",
"licensesPackageDetailTextMany": "$licenseCount ترخيصًا",
"licensesPackageDetailTextFew": "$licenseCount تراخيص",
"remainingTextFieldCharacterCountTwo": "حرفان ($remainingCount) متبقيان",
"remainingTextFieldCharacterCountMany": "$remainingCount حرفًا متبقيًا",
"remainingTextFieldCharacterCountFew": "$remainingCount أحرف متبقية",
"selectedRowCountTitleOne": "تم اختيار عنصر واحد",
"selectedRowCountTitleZero": "لم يتم اختيار أي عنصر",
"selectedRowCountTitleTwo": "تم اختيار عنصرين ($selectedRowCount)",
"selectedRowCountTitleFew": "تم اختيار $selectedRowCount عنصر",
"selectedRowCountTitleMany": "تم اختيار $selectedRowCount عنصرًا",
"scriptCategory": "tall",
"timeOfDayFormat": "h:mm a",
"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",
"selectedRowCountTitleOther": "تم اختيار $selectedRowCount عنصر",
"cancelButtonLabel": "الإلغاء",
"closeButtonLabel": "الإغلاق",
"continueButtonLabel": "المتابعة",
"copyButtonLabel": "نسخ",
"cutButtonLabel": "قص",
"scanTextButtonLabel": "مسح النص ضوئيًا",
"okButtonLabel": "حسنًا",
"pasteButtonLabel": "لصق",
"selectAllButtonLabel": "اختيار الكل",
"viewLicensesButtonLabel": "الاطّلاع على التراخيص",
"anteMeridiemAbbreviation": "ص",
"postMeridiemAbbreviation": "م",
"timePickerHourModeAnnouncement": "اختيار الساعات",
"timePickerMinuteModeAnnouncement": "اختيار الدقائق",
"signedInLabel": "تم تسجيل الدخول",
"hideAccountsLabel": "إخفاء الحسابات",
"showAccountsLabel": "إظهار الحسابات",
"modalBarrierDismissLabel": "رفض",
"drawerLabel": "قائمة تنقل",
"popupMenuLabel": "قائمة منبثقة",
"dialogLabel": "مربع حوار",
"alertDialogLabel": "تنبيه",
"searchFieldLabel": "بحث",
"reorderItemToStart": "نقل إلى بداية القائمة",
"reorderItemToEnd": "نقل إلى نهاية القائمة",
"reorderItemUp": "نقل لأعلى",
"reorderItemDown": "نقل لأسفل",
"reorderItemLeft": "نقل لليمين",
"reorderItemRight": "نقل لليسار",
"expandedIconTapHint": "تصغير",
"collapsedIconTapHint": "توسيع",
"remainingTextFieldCharacterCountZero": "لا أحرف متبقية",
"remainingTextFieldCharacterCountOne": "حرف واحد متبقٍ",
"remainingTextFieldCharacterCountOther": "$remainingCount حرف متبقٍ",
"refreshIndicatorSemanticLabel": "إعادة تحميل",
"moreButtonTooltip": "المزيد",
"dateSeparator": "/",
"dateHelpText": "yyyy/mm/dd",
"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": "ما مِن تراخيص",
"licensesPackageDetailTextOne": "ترخيص واحد",
"licensesPackageDetailTextOther": "$licenseCount ترخيص",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "القناة التالية",
"keyboardKeyChannelUp": "القناة السابقة",
"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": "المفتاح Enter",
"keyboardKeyNumpadEqual": "علامة التساوي =",
"keyboardKeyNumpadMultiply": "علامة الضرب *",
"keyboardKeyNumpadParenLeft": "القوس الأيسر )",
"keyboardKeyNumpadParenRight": "القوس الأيمن (",
"keyboardKeyNumpadSubtract": "علامة الطرح -",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "زر التشغيل",
"keyboardKeyPowerOff": "زر الإطفاء",
"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_ar.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ar.arb",
"repo_id": "flutter",
"token_count": 3511
} | 747 |
{
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"openAppDrawerTooltip": "Buksan ang menu ng navigation",
"backButtonTooltip": "Bumalik",
"closeButtonTooltip": "Isara",
"deleteButtonTooltip": "I-delete",
"nextMonthTooltip": "Susunod na buwan",
"previousMonthTooltip": "Nakaraang buwan",
"nextPageTooltip": "Susunod na page",
"previousPageTooltip": "Nakaraang page",
"firstPageTooltip": "Unang page",
"lastPageTooltip": "Huling page",
"showMenuTooltip": "Ipakita ang menu",
"aboutListTileTitle": "Tungkol sa $applicationName",
"licensesPageTitle": "Mga Lisensya",
"pageRowsInfoTitle": "$firstRow–$lastRow ng $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow ng humigit kumulang $rowCount",
"rowsPerPageTitle": "Mga row bawat page:",
"tabLabel": "Tab $tabIndex ng $tabCount",
"selectedRowCountTitleOne": "1 item ang napili",
"selectedRowCountTitleOther": "$selectedRowCount na item ang napili",
"cancelButtonLabel": "Kanselahin",
"closeButtonLabel": "Isara",
"continueButtonLabel": "Magpatuloy",
"copyButtonLabel": "Kopyahin",
"cutButtonLabel": "I-cut",
"scanTextButtonLabel": "I-scan ang text",
"okButtonLabel": "OK",
"pasteButtonLabel": "I-paste",
"selectAllButtonLabel": "Piliin lahat",
"viewLicensesButtonLabel": "Tingnan ang mga lisensya",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "Pumili ng mga oras",
"timePickerMinuteModeAnnouncement": "Pumili ng mga minuto",
"modalBarrierDismissLabel": "I-dismiss",
"signedInLabel": "Naka-sign in",
"hideAccountsLabel": "Itago ang mga account",
"showAccountsLabel": "Ipakita ang mga account",
"drawerLabel": "Menu ng navigation",
"popupMenuLabel": "Popup na menu",
"dialogLabel": "Dialog",
"alertDialogLabel": "Alerto",
"searchFieldLabel": "Maghanap",
"reorderItemToStart": "Ilipat sa simula",
"reorderItemToEnd": "Ilipat sa dulo",
"reorderItemUp": "Ilipat pataas",
"reorderItemDown": "Ilipat pababa",
"reorderItemLeft": "Ilipat pakaliwa",
"reorderItemRight": "Ilipat pakanan",
"expandedIconTapHint": "I-collapse",
"collapsedIconTapHint": "I-expand",
"remainingTextFieldCharacterCountOne": "1 character ang natitira",
"remainingTextFieldCharacterCountOther": "$remainingCount na character ang natitira",
"refreshIndicatorSemanticLabel": "Nagre-refresh",
"moreButtonTooltip": "Higit Pa",
"dateSeparator": "/",
"dateHelpText": "mm/dd/yyyy",
"selectYearSemanticsLabel": "Pumili ng taon",
"unspecifiedDate": "Petsa",
"unspecifiedDateRange": "Hanay ng Petsa",
"dateInputLabel": "Ilagay ang Petsa",
"dateRangeStartLabel": "Petsa ng Pagsisimula",
"dateRangeEndLabel": "Petsa ng Pagtatapos",
"dateRangeStartDateSemanticLabel": "Petsa ng pagsisimula $fullDate",
"dateRangeEndDateSemanticLabel": "Petsa ng pagtatapos $fullDate",
"invalidDateFormatLabel": "Invalid ang format.",
"invalidDateRangeLabel": "Invalid ang hanay.",
"dateOutOfRangeLabel": "Wala sa hanay.",
"saveButtonLabel": "I-save",
"datePickerHelpText": "Pumili ng petsa",
"dateRangePickerHelpText": "Pumili ng hanay",
"calendarModeButtonLabel": "Lumipat sa kalendaryo",
"inputDateModeButtonLabel": "Lumipat sa input",
"timePickerDialHelpText": "Pumili ng oras",
"timePickerInputHelpText": "Maglagay ng oras",
"timePickerHourLabel": "Oras",
"timePickerMinuteLabel": "Minuto",
"invalidTimeLabel": "Maglagay ng valid na oras",
"dialModeButtonLabel": "Lumipat sa dial picker mode",
"inputTimeModeButtonLabel": "Lumipat sa text input mode",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 lisensya",
"licensesPackageDetailTextOther": "$licenseCount na lisensya",
"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": "I-off",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Piliin",
"keyboardKeySpace": "Puwang",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Menu sa menu bar",
"currentDateLabel": "Ngayon",
"scrimLabel": "Scrim",
"bottomSheetLabel": "Bottom Sheet",
"scrimOnTapHint": "Isara ang $modalRouteContentName",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "i-double tap para i-collapse",
"expansionTileCollapsedHint": "i-double tap para i-expand",
"expansionTileExpandedTapHint": "I-collapse",
"expansionTileCollapsedTapHint": "I-expand para sa higit pang detalye",
"expandedHint": "Naka-collapse",
"collapsedHint": "Naka-expand",
"menuDismissLabel": "I-dismiss ang menu",
"lookUpButtonLabel": "Tumingin sa Itaas",
"searchWebButtonLabel": "Maghanap sa Web",
"shareButtonLabel": "Ibahagi...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_fil.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_fil.arb",
"repo_id": "flutter",
"token_count": 2283
} | 748 |
{
"selectedRowCountTitleOne": "1 элемент таңдалды.",
"remainingTextFieldCharacterCountOne": "1 таңба қалды.",
"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 қойынды",
"selectedRowCountTitleZero": "Тармақ таңдалмаған",
"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": "Жаю",
"remainingTextFieldCharacterCountZero": "Таңбалар қалмады",
"remainingTextFieldCharacterCountOther": "$remainingCount таңба қалды.",
"refreshIndicatorSemanticLabel": "Жаңарту",
"moreButtonTooltip": "Жаю",
"dateSeparator": ".",
"dateHelpText": "кк.аа.жжжж",
"selectYearSemanticsLabel": "Жылды таңдау",
"unspecifiedDate": "Күн",
"unspecifiedDateRange": "Күндер ауқымы",
"dateInputLabel": "Күнді енгізу",
"dateRangeStartLabel": "Басталу күні",
"dateRangeEndLabel": "Аяқталу күні",
"dateRangeStartDateSemanticLabel": "Басталу күні $fullDate",
"dateRangeEndDateSemanticLabel": "Аяқталу күні $fullDate",
"invalidDateFormatLabel": "Формат жарамсыз.",
"invalidDateRangeLabel": "Ауқым жарамсыз.",
"dateOutOfRangeLabel": "Ауқымнан тыc.",
"saveButtonLabel": "Сақтау",
"datePickerHelpText": "Күнді таңдау",
"dateRangePickerHelpText": "Аралықты таңдау",
"calendarModeButtonLabel": "Күнтізбеге ауысу",
"inputDateModeButtonLabel": "Мәтін енгізуге ауысу",
"timePickerDialHelpText": "Уақытты таңдау",
"timePickerInputHelpText": "Уақытты енгізу",
"timePickerHourLabel": "Сағат",
"timePickerMinuteLabel": "Mинут",
"invalidTimeLabel": "Жарамды уақыт мәліметін енгізіңіз.",
"dialModeButtonLabel": "Таңдау режиміне ауысу",
"inputTimeModeButtonLabel": "Мәтін енгізу режиміне ауысу",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 лицензия",
"licensesPackageDetailTextOther": "$licenseCount лицензия",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Келесі арна",
"keyboardKeyChannelUp": "Алдыңғы арна",
"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": "Қуат",
"keyboardKeyPowerOff": "Қуатты өшіру",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Select",
"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_kk.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_kk.arb",
"repo_id": "flutter",
"token_count": 3369
} | 749 |
{
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"openAppDrawerTooltip": "Navigatiemenu openen",
"backButtonTooltip": "Terug",
"closeButtonTooltip": "Sluiten",
"deleteButtonTooltip": "Verwijderen",
"nextMonthTooltip": "Volgende maand",
"previousMonthTooltip": "Vorige maand",
"nextPageTooltip": "Volgende pagina",
"previousPageTooltip": "Vorige pagina",
"firstPageTooltip": "Eerste pagina",
"lastPageTooltip": "Laatste pagina",
"showMenuTooltip": "Menu tonen",
"aboutListTileTitle": "Over $applicationName",
"licensesPageTitle": "Licenties",
"pageRowsInfoTitle": "$firstRow-$lastRow van $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow-$lastRow van ongeveer $rowCount",
"rowsPerPageTitle": "Rijen per pagina:",
"tabLabel": "Tabblad $tabIndex van $tabCount",
"selectedRowCountTitleOne": "1 item geselecteerd",
"selectedRowCountTitleOther": "$selectedRowCount items geselecteerd",
"cancelButtonLabel": "Annuleren",
"closeButtonLabel": "Sluiten",
"continueButtonLabel": "Doorgaan",
"copyButtonLabel": "Kopiëren",
"cutButtonLabel": "Knippen",
"scanTextButtonLabel": "Tekst scannen",
"okButtonLabel": "OK",
"pasteButtonLabel": "Plakken",
"selectAllButtonLabel": "Alles selecteren",
"viewLicensesButtonLabel": "Licenties bekijken",
"anteMeridiemAbbreviation": "am",
"postMeridiemAbbreviation": "pm",
"timePickerHourModeAnnouncement": "Uren selecteren",
"timePickerMinuteModeAnnouncement": "Minuten selecteren",
"signedInLabel": "Ingelogd",
"hideAccountsLabel": "Accounts verbergen",
"showAccountsLabel": "Accounts tonen",
"modalBarrierDismissLabel": "Sluiten",
"drawerLabel": "Navigatiemenu",
"popupMenuLabel": "Pop-upmenu",
"dialogLabel": "Dialoogvenster",
"alertDialogLabel": "Melding",
"searchFieldLabel": "Zoeken",
"reorderItemToStart": "Naar het begin verplaatsen",
"reorderItemToEnd": "Naar het einde verplaatsen",
"reorderItemUp": "Omhoog verplaatsen",
"reorderItemDown": "Omlaag verplaatsen",
"reorderItemLeft": "Naar links verplaatsen",
"reorderItemRight": "Naar rechts verplaatsen",
"expandedIconTapHint": "Samenvouwen",
"collapsedIconTapHint": "Uitvouwen",
"remainingTextFieldCharacterCountOne": "1 teken resterend",
"remainingTextFieldCharacterCountOther": "$remainingCount tekens resterend",
"refreshIndicatorSemanticLabel": "Vernieuwen",
"moreButtonTooltip": "Meer",
"dateSeparator": "-",
"dateHelpText": "dd-mm-jjjj",
"selectYearSemanticsLabel": "Jaar selecteren",
"unspecifiedDate": "Datum",
"unspecifiedDateRange": "Periode",
"dateInputLabel": "Datum opgeven",
"dateRangeStartLabel": "Startdatum",
"dateRangeEndLabel": "Einddatum",
"dateRangeStartDateSemanticLabel": "Startdatum $fullDate",
"dateRangeEndDateSemanticLabel": "Einddatum $fullDate",
"invalidDateFormatLabel": "Ongeldige indeling.",
"invalidDateRangeLabel": "Ongeldige periode.",
"dateOutOfRangeLabel": "Buiten bereik.",
"saveButtonLabel": "Opslaan",
"datePickerHelpText": "Datum selecteren",
"dateRangePickerHelpText": "Periode selecteren",
"calendarModeButtonLabel": "Overschakelen naar kalender",
"inputDateModeButtonLabel": "Overschakelen naar invoer",
"timePickerDialHelpText": "Tijd selecteren",
"timePickerInputHelpText": "Tijd opgeven",
"timePickerHourLabel": "Uur",
"timePickerMinuteLabel": "Minuut",
"invalidTimeLabel": "Geef een geldige tijd op",
"dialModeButtonLabel": "Overschakelen naar klok",
"inputTimeModeButtonLabel": "Overschakelen naar tekstinvoer",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 licentie",
"licensesPackageDetailTextOther": "$licenseCount licenties",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Kanaal omlaag",
"keyboardKeyChannelUp": "Kanaal omhoog",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Uitwerpen",
"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": "Aan/uit",
"keyboardKeyPowerOff": "Uit",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Selecteren",
"keyboardKeySpace": "Spatie",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Menu van menubalk",
"currentDateLabel": "Vandaag",
"scrimLabel": "Scrim",
"bottomSheetLabel": "Blad onderaan",
"scrimOnTapHint": "$modalRouteContentName sluiten",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "dubbeltik om samen te vouwen",
"expansionTileCollapsedHint": "dubbeltik om uit te vouwen",
"expansionTileExpandedTapHint": "Samenvouwen",
"expansionTileCollapsedTapHint": "Uitvouwen voor meer informatie",
"expandedHint": "Samengevouwen",
"collapsedHint": "Uitgevouwen",
"menuDismissLabel": "Menu sluiten",
"lookUpButtonLabel": "Opzoeken",
"searchWebButtonLabel": "Op internet zoeken",
"shareButtonLabel": "Delen...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_nl.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_nl.arb",
"repo_id": "flutter",
"token_count": 2278
} | 750 |
{
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"openAppDrawerTooltip": "Öppna navigeringsmenyn",
"backButtonTooltip": "Tillbaka",
"closeButtonTooltip": "Stäng",
"deleteButtonTooltip": "Radera",
"nextMonthTooltip": "Nästa månad",
"previousMonthTooltip": "Föregående månad",
"nextPageTooltip": "Nästa sida",
"previousPageTooltip": "Föregående sida",
"firstPageTooltip": "Första sidan",
"lastPageTooltip": "Sista sidan",
"showMenuTooltip": "Visa meny",
"aboutListTileTitle": "Om $applicationName",
"licensesPageTitle": "Licenser",
"pageRowsInfoTitle": "$firstRow–$lastRow av $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow av ungefär $rowCount",
"rowsPerPageTitle": "Rader per sida:",
"tabLabel": "Flik $tabIndex av $tabCount",
"selectedRowCountTitleOne": "1 objekt har markerats",
"selectedRowCountTitleOther": "$selectedRowCount objekt har markerats",
"cancelButtonLabel": "Avbryt",
"closeButtonLabel": "Stäng",
"continueButtonLabel": "Fortsätt",
"copyButtonLabel": "Kopiera",
"cutButtonLabel": "Klipp ut",
"scanTextButtonLabel": "Skanna text",
"okButtonLabel": "OK",
"pasteButtonLabel": "Klistra in",
"selectAllButtonLabel": "Markera allt",
"viewLicensesButtonLabel": "Visa licenser",
"anteMeridiemAbbreviation": "FM",
"postMeridiemAbbreviation": "EM",
"timePickerHourModeAnnouncement": "Välj timmar",
"timePickerMinuteModeAnnouncement": "Välj minuter",
"modalBarrierDismissLabel": "Stäng",
"signedInLabel": "Inloggad",
"hideAccountsLabel": "Dölj konton",
"showAccountsLabel": "Visa konton",
"drawerLabel": "Navigeringsmeny",
"popupMenuLabel": "Popup-meny",
"dialogLabel": "Dialogruta",
"alertDialogLabel": "Varning",
"searchFieldLabel": "Sök",
"reorderItemToStart": "Flytta till början",
"reorderItemToEnd": "Flytta till slutet",
"reorderItemUp": "Flytta uppåt",
"reorderItemDown": "Flytta nedåt",
"reorderItemLeft": "Flytta åt vänster",
"reorderItemRight": "Flytta åt höger",
"expandedIconTapHint": "Dölj",
"collapsedIconTapHint": "Utöka",
"remainingTextFieldCharacterCountOne": "1 tecken kvar",
"remainingTextFieldCharacterCountOther": "$remainingCount tecken kvar",
"refreshIndicatorSemanticLabel": "Uppdatera",
"moreButtonTooltip": "Mer",
"dateSeparator": ".",
"dateHelpText": "åååå-mm-dd",
"selectYearSemanticsLabel": "Välj år",
"unspecifiedDate": "Datum",
"unspecifiedDateRange": "Datumintervall",
"dateInputLabel": "Ange datum",
"dateRangeStartLabel": "Startdatum",
"dateRangeEndLabel": "Slutdatum",
"dateRangeStartDateSemanticLabel": "Startdatum $fullDate",
"dateRangeEndDateSemanticLabel": "Slutdatum $fullDate",
"invalidDateFormatLabel": "Ogiltigt format.",
"invalidDateRangeLabel": "Ogiltigt intervall.",
"dateOutOfRangeLabel": "Utanför intervallet.",
"saveButtonLabel": "Spara",
"datePickerHelpText": "Välj datum",
"dateRangePickerHelpText": "Välj intervall",
"calendarModeButtonLabel": "Byt till kalender",
"inputDateModeButtonLabel": "Byt till inmatning",
"timePickerDialHelpText": "Välj tid",
"timePickerInputHelpText": "Ange tid",
"timePickerHourLabel": "Timme",
"timePickerMinuteLabel": "Minut",
"invalidTimeLabel": "Ange en giltig tid",
"dialModeButtonLabel": "Byt till läget urtavleväljare",
"inputTimeModeButtonLabel": "Byt till text som inmatningsläge",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 licens",
"licensesPackageDetailTextOther": "$licenseCount licenser",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backsteg",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Byt kanal nedåt",
"keyboardKeyChannelUp": "Byt kanal uppåt",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Mata ut",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Hem",
"keyboardKeyInsert": "Infoga",
"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": "Av/på",
"keyboardKeyPowerOff": "Stäng av",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Välj",
"keyboardKeySpace": "Blanksteg",
"keyboardKeyMetaMacOs": "Kommando",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Menyrad",
"currentDateLabel": "I dag",
"scrimLabel": "Scrim",
"bottomSheetLabel": "Ark på nedre delen av skärmen",
"scrimOnTapHint": "Stäng $modalRouteContentName",
"keyboardKeyShift": "Skift",
"expansionTileExpandedHint": "tryck snabbt två gånger för att komprimera",
"expansionTileCollapsedHint": "tryck snabbt två gånger för att utöka",
"expansionTileExpandedTapHint": "Komprimera",
"expansionTileCollapsedTapHint": "Utöka för mer information",
"expandedHint": "Komprimerades",
"collapsedHint": "Utökades",
"menuDismissLabel": "Stäng menyn",
"lookUpButtonLabel": "Titta upp",
"searchWebButtonLabel": "Sök på webben",
"shareButtonLabel": "Dela …",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_sv.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_sv.arb",
"repo_id": "flutter",
"token_count": 2291
} | 751 |
{
"reorderItemToStart": "ወደ መጀመሪያ ውሰድ",
"reorderItemToEnd": "ወደ መጨረሻ ውሰድ",
"reorderItemUp": "ወደ ላይ ውሰድ",
"reorderItemDown": "ወደ ታች ውሰድ",
"reorderItemLeft": "ወደ ግራ ውሰድ",
"reorderItemRight": "ወደ ቀኝ ውሰድ"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_am.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_am.arb",
"repo_id": "flutter",
"token_count": 207
} | 752 |
{
"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"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_en_AU.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_en_AU.arb",
"repo_id": "flutter",
"token_count": 86
} | 753 |
{
"reorderItemToStart": "Siirrä alkuun",
"reorderItemToEnd": "Siirrä loppuun",
"reorderItemUp": "Siirrä ylös",
"reorderItemDown": "Siirrä alas",
"reorderItemLeft": "Siirrä vasemmalle",
"reorderItemRight": "Siirrä oikealle"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_fi.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_fi.arb",
"repo_id": "flutter",
"token_count": 109
} | 754 |
{
"reorderItemToStart": "დასაწყისში გადატანა",
"reorderItemToEnd": "ბოლოში გადატანა",
"reorderItemUp": "ზემოთ გადატანა",
"reorderItemDown": "ქვემოთ გადატანა",
"reorderItemLeft": "მარცხნივ გადატანა",
"reorderItemRight": "მარჯვნივ გადატანა"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_ka.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ka.arb",
"repo_id": "flutter",
"token_count": 339
} | 755 |
{
"reorderItemToStart": "सुरुमा सार्नुहोस्",
"reorderItemToEnd": "अन्त्यमा जानुहोस्",
"reorderItemUp": "माथि सार्नुहोस्",
"reorderItemDown": "तल सार्नुहोस्",
"reorderItemLeft": "बायाँ सार्नुहोस्",
"reorderItemRight": "दायाँ सार्नुहोस्"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_ne.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ne.arb",
"repo_id": "flutter",
"token_count": 229
} | 756 |
{
"reorderItemToStart": "Pomerite na početak",
"reorderItemToEnd": "Pomerite na kraj",
"reorderItemUp": "Pomerite nagore",
"reorderItemDown": "Pomerite nadole",
"reorderItemLeft": "Pomerite ulevo",
"reorderItemRight": "Pomerite udesno"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_sr_Latn.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_sr_Latn.arb",
"repo_id": "flutter",
"token_count": 105
} | 757 |
// 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:intl/intl.dart' as intl;
import 'cupertino_localizations.dart';
import 'l10n/generated_material_localizations.dart';
import 'utils/date_localizations.dart' as util;
import 'widgets_localizations.dart';
// Examples can assume:
// import 'package:flutter_localizations/flutter_localizations.dart';
// import 'package:flutter/material.dart';
/// Implementation of localized strings for the material widgets using the
/// `intl` package for date and time formatting.
///
/// ## Supported languages
///
/// This class supports locales with the following [Locale.languageCode]s:
///
/// {@macro flutter.localizations.material.languages}
///
/// This list is available programmatically via [kMaterialSupportedLanguages].
///
/// ## Sample code
///
/// To include the localizations provided by this class in a [MaterialApp],
/// add [GlobalMaterialLocalizations.delegates] to
/// [MaterialApp.localizationsDelegates], and specify the locales your
/// app supports with [MaterialApp.supportedLocales]:
///
/// ```dart
/// const MaterialApp(
/// localizationsDelegates: GlobalMaterialLocalizations.delegates,
/// supportedLocales: <Locale>[
/// Locale('en', 'US'), // American English
/// Locale('he', 'IL'), // Israeli Hebrew
/// // ...
/// ],
/// // ...
/// )
/// ```
///
/// ## Overriding translations
///
/// To create a translation that's similar to an existing language's translation
/// but has slightly different strings, subclass the relevant translation
/// directly and then create a [LocalizationsDelegate<MaterialLocalizations>]
/// subclass to define how to load it.
///
/// Avoid subclassing an unrelated language (for example, subclassing
/// [MaterialLocalizationEn] and then passing a non-English `localeName` to the
/// constructor). Doing so will cause confusion for locale-specific behaviors;
/// in particular, translations that use the `localeName` for determining how to
/// pluralize will end up doing invalid things. Subclassing an existing
/// language's translations is only suitable for making small changes to the
/// existing strings. For providing a new language entirely, implement
/// [MaterialLocalizations] directly.
///
/// See also:
///
/// * The Flutter Internationalization Tutorial,
/// <https://flutter.dev/tutorials/internationalization/>.
/// * [DefaultMaterialLocalizations], which only provides US English translations.
abstract class GlobalMaterialLocalizations implements MaterialLocalizations {
/// Initializes an object that defines the material widgets' localized strings
/// for the given `locale`.
///
/// The arguments are used for further runtime localization of data,
/// specifically for selecting plurals, date and time formatting, and number
/// formatting. They correspond to the following values:
///
/// 1. The string that would be returned by [Intl.canonicalizedLocale] for
/// the locale.
/// 2. The [DateFormat] for [formatYear].
/// 3. The [DateFormat] for [formatShortDate].
/// 4. The [DateFormat] for [formatMediumDate].
/// 5. The [DateFormat] for [formatFullDate].
/// 6. The [DateFormat] for [formatMonthYear].
/// 7. The [DateFormat] for [formatShortMonthDay].
/// 8. The [NumberFormat] for [formatDecimal] (also used by [formatHour] and
/// [formatTimeOfDay] when [timeOfDayFormat] doesn't use [HourFormat.HH]).
/// 9. The [NumberFormat] for [formatHour] and the hour part of
/// [formatTimeOfDay] when [timeOfDayFormat] uses [HourFormat.HH], and for
/// [formatMinute] and the minute part of [formatTimeOfDay].
///
/// The [narrowWeekdays] and [firstDayOfWeekIndex] properties use the values
/// from the [intl.DateFormat] used by [formatFullDate].
const GlobalMaterialLocalizations({
required String localeName,
required intl.DateFormat fullYearFormat,
required intl.DateFormat compactDateFormat,
required intl.DateFormat shortDateFormat,
required intl.DateFormat mediumDateFormat,
required intl.DateFormat longDateFormat,
required intl.DateFormat yearMonthFormat,
required intl.DateFormat shortMonthDayFormat,
required intl.NumberFormat decimalFormat,
required intl.NumberFormat twoDigitZeroPaddedFormat,
}) : _localeName = localeName,
_fullYearFormat = fullYearFormat,
_compactDateFormat = compactDateFormat,
_shortDateFormat = shortDateFormat,
_mediumDateFormat = mediumDateFormat,
_longDateFormat = longDateFormat,
_yearMonthFormat = yearMonthFormat,
_shortMonthDayFormat = shortMonthDayFormat,
_decimalFormat = decimalFormat,
_twoDigitZeroPaddedFormat = twoDigitZeroPaddedFormat;
final String _localeName;
final intl.DateFormat _fullYearFormat;
final intl.DateFormat _compactDateFormat;
final intl.DateFormat _shortDateFormat;
final intl.DateFormat _mediumDateFormat;
final intl.DateFormat _longDateFormat;
final intl.DateFormat _yearMonthFormat;
final intl.DateFormat _shortMonthDayFormat;
final intl.NumberFormat _decimalFormat;
final intl.NumberFormat _twoDigitZeroPaddedFormat;
@override
String formatHour(TimeOfDay timeOfDay, { bool alwaysUse24HourFormat = false }) {
switch (hourFormat(of: timeOfDayFormat(alwaysUse24HourFormat: alwaysUse24HourFormat))) {
case HourFormat.HH:
return _twoDigitZeroPaddedFormat.format(timeOfDay.hour);
case HourFormat.H:
return formatDecimal(timeOfDay.hour);
case HourFormat.h:
final int hour = timeOfDay.hourOfPeriod;
return formatDecimal(hour == 0 ? 12 : hour);
}
}
@override
String formatMinute(TimeOfDay timeOfDay) {
return _twoDigitZeroPaddedFormat.format(timeOfDay.minute);
}
@override
String formatYear(DateTime date) {
return _fullYearFormat.format(date);
}
@override
String formatCompactDate(DateTime date) {
return _compactDateFormat.format(date);
}
@override
String formatShortDate(DateTime date) {
return _shortDateFormat.format(date);
}
@override
String formatMediumDate(DateTime date) {
return _mediumDateFormat.format(date);
}
@override
String formatFullDate(DateTime date) {
return _longDateFormat.format(date);
}
@override
String formatMonthYear(DateTime date) {
return _yearMonthFormat.format(date);
}
@override
String formatShortMonthDay(DateTime date) {
return _shortMonthDayFormat.format(date);
}
@override
DateTime? parseCompactDate(String? inputString) {
try {
return inputString != null ? _compactDateFormat.parseStrict(inputString) : null;
} on FormatException {
return null;
}
}
@override
List<String> get narrowWeekdays {
return _longDateFormat.dateSymbols.NARROWWEEKDAYS;
}
@override
int get firstDayOfWeekIndex => (_longDateFormat.dateSymbols.FIRSTDAYOFWEEK + 1) % 7;
@override
String formatDecimal(int number) {
return _decimalFormat.format(number);
}
@override
String formatTimeOfDay(TimeOfDay timeOfDay, { bool alwaysUse24HourFormat = false }) {
// Not using intl.DateFormat for two reasons:
//
// - DateFormat supports more formats than our material time picker does,
// and we want to be consistent across time picker format and the string
// formatting of the time of day.
// - DateFormat operates on DateTime, which is sensitive to time eras and
// time zones, while here we want to format hour and minute within one day
// no matter what date the day falls on.
final String hour = formatHour(timeOfDay, alwaysUse24HourFormat: alwaysUse24HourFormat);
final String minute = formatMinute(timeOfDay);
switch (timeOfDayFormat(alwaysUse24HourFormat: alwaysUse24HourFormat)) {
case TimeOfDayFormat.h_colon_mm_space_a:
return '$hour:$minute ${_formatDayPeriod(timeOfDay)!}';
case TimeOfDayFormat.H_colon_mm:
case TimeOfDayFormat.HH_colon_mm:
return '$hour:$minute';
case TimeOfDayFormat.HH_dot_mm:
return '$hour.$minute';
case TimeOfDayFormat.a_space_h_colon_mm:
return '${_formatDayPeriod(timeOfDay)!} $hour:$minute';
case TimeOfDayFormat.frenchCanadian:
return '$hour h $minute';
}
}
String? _formatDayPeriod(TimeOfDay timeOfDay) {
switch (timeOfDay.period) {
case DayPeriod.am:
return anteMeridiemAbbreviation;
case DayPeriod.pm:
return postMeridiemAbbreviation;
}
}
/// The raw version of [dateRangeStartDateSemanticLabel], with `$formattedDate` verbatim
/// in the string.
@protected
String get dateRangeStartDateSemanticLabelRaw;
@override
String dateRangeStartDateSemanticLabel(String formattedDate) {
return dateRangeStartDateSemanticLabelRaw.replaceFirst(r'$fullDate', formattedDate);
}
/// The raw version of [dateRangeEndDateSemanticLabel], with `$fullDate` verbatim
/// in the string.
@protected
String get dateRangeEndDateSemanticLabelRaw;
@override
String dateRangeEndDateSemanticLabel(String formattedDate) {
return dateRangeEndDateSemanticLabelRaw.replaceFirst(r'$fullDate', formattedDate);
}
/// The raw version of [scrimOnTapHint], with `$modalRouteContentName` verbatim
/// in the string.
@protected
String get scrimOnTapHintRaw;
@override
String scrimOnTapHint(String modalRouteContentName) {
final String text = scrimOnTapHintRaw;
return text.replaceFirst(r'$modalRouteContentName', modalRouteContentName);
}
/// The raw version of [aboutListTileTitle], with `$applicationName` verbatim
/// in the string.
@protected
String get aboutListTileTitleRaw;
@override
String aboutListTileTitle(String applicationName) {
final String text = aboutListTileTitleRaw;
return text.replaceFirst(r'$applicationName', applicationName);
}
/// The raw version of [pageRowsInfoTitle], with `$firstRow`, `$lastRow`' and
/// `$rowCount` verbatim in the string, for the case where the value is
/// approximate.
@protected
String get pageRowsInfoTitleApproximateRaw;
/// The raw version of [pageRowsInfoTitle], with `$firstRow`, `$lastRow`' and
/// `$rowCount` verbatim in the string, for the case where the value is
/// precise.
@protected
String get pageRowsInfoTitleRaw;
@override
String pageRowsInfoTitle(int firstRow, int lastRow, int rowCount, bool rowCountIsApproximate) {
String? text = rowCountIsApproximate ? pageRowsInfoTitleApproximateRaw : null;
text ??= pageRowsInfoTitleRaw;
return text
.replaceFirst(r'$firstRow', formatDecimal(firstRow))
.replaceFirst(r'$lastRow', formatDecimal(lastRow))
.replaceFirst(r'$rowCount', formatDecimal(rowCount));
}
/// The raw version of [tabLabel], with `$tabIndex` and `$tabCount` verbatim
/// in the string.
@protected
String get tabLabelRaw;
@override
String tabLabel({ required int tabIndex, required int tabCount }) {
assert(tabIndex >= 1);
assert(tabCount >= 1);
final String template = tabLabelRaw;
return template
.replaceFirst(r'$tabIndex', formatDecimal(tabIndex))
.replaceFirst(r'$tabCount', formatDecimal(tabCount));
}
/// The "zero" form of [selectedRowCountTitle].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [selectedRowCountTitleOne], the "one" form
/// * [selectedRowCountTitleTwo], the "two" form
/// * [selectedRowCountTitleFew], the "few" form
/// * [selectedRowCountTitleMany], the "many" form
/// * [selectedRowCountTitleOther], the "other" form
@protected
String? get selectedRowCountTitleZero => null;
/// The "one" form of [selectedRowCountTitle].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [selectedRowCountTitleZero], the "zero" form
/// * [selectedRowCountTitleTwo], the "two" form
/// * [selectedRowCountTitleFew], the "few" form
/// * [selectedRowCountTitleMany], the "many" form
/// * [selectedRowCountTitleOther], the "other" form
@protected
String? get selectedRowCountTitleOne => null;
/// The "two" form of [selectedRowCountTitle].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [selectedRowCountTitleZero], the "zero" form
/// * [selectedRowCountTitleOne], the "one" form
/// * [selectedRowCountTitleFew], the "few" form
/// * [selectedRowCountTitleMany], the "many" form
/// * [selectedRowCountTitleOther], the "other" form
@protected
String? get selectedRowCountTitleTwo => null;
/// The "few" form of [selectedRowCountTitle].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [selectedRowCountTitleZero], the "zero" form
/// * [selectedRowCountTitleOne], the "one" form
/// * [selectedRowCountTitleTwo], the "two" form
/// * [selectedRowCountTitleMany], the "many" form
/// * [selectedRowCountTitleOther], the "other" form
@protected
String? get selectedRowCountTitleFew => null;
/// The "many" form of [selectedRowCountTitle].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [selectedRowCountTitleZero], the "zero" form
/// * [selectedRowCountTitleOne], the "one" form
/// * [selectedRowCountTitleTwo], the "two" form
/// * [selectedRowCountTitleFew], the "few" form
/// * [selectedRowCountTitleOther], the "other" form
@protected
String? get selectedRowCountTitleMany => null;
/// The "other" form of [selectedRowCountTitle].
///
/// This form is required.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [selectedRowCountTitleZero], the "zero" form
/// * [selectedRowCountTitleOne], the "one" form
/// * [selectedRowCountTitleTwo], the "two" form
/// * [selectedRowCountTitleFew], the "few" form
/// * [selectedRowCountTitleMany], the "many" form
@protected
String get selectedRowCountTitleOther;
@override
String selectedRowCountTitle(int selectedRowCount) {
return intl.Intl.pluralLogic(
selectedRowCount,
zero: selectedRowCountTitleZero,
one: selectedRowCountTitleOne,
two: selectedRowCountTitleTwo,
few: selectedRowCountTitleFew,
many: selectedRowCountTitleMany,
other: selectedRowCountTitleOther,
locale: _localeName,
).replaceFirst(r'$selectedRowCount', formatDecimal(selectedRowCount));
}
/// The format to use for [timeOfDayFormat].
@protected
TimeOfDayFormat get timeOfDayFormatRaw;
/// The [TimeOfDayFormat] corresponding to one of the following supported
/// patterns:
///
/// * `HH:mm`
/// * `HH.mm`
/// * `HH 'h' mm`
/// * `HH:mm น.`
/// * `H:mm`
/// * `h:mm a`
/// * `a h:mm`
/// * `ah:mm`
///
/// See also:
///
/// * <http://demo.icu-project.org/icu-bin/locexp?d_=en&_=en_US>, which shows
/// the short time pattern used in the `en_US` locale.
@override
TimeOfDayFormat timeOfDayFormat({ bool alwaysUse24HourFormat = false }) {
if (alwaysUse24HourFormat) {
return _get24HourVersionOf(timeOfDayFormatRaw);
}
return timeOfDayFormatRaw;
}
/// The "zero" form of [licensesPackageDetailText].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [licensesPackageDetailTextZero], the "zero" form
/// * [licensesPackageDetailTextOne], the "one" form
/// * [licensesPackageDetailTextTwo], the "two" form
/// * [licensesPackageDetailTextFew], the "few" form
/// * [licensesPackageDetailTextMany], the "many" form
/// * [licensesPackageDetailTextOther], the "other" form
@protected
String? get licensesPackageDetailTextZero => null;
/// The "one" form of [licensesPackageDetailText].
///
/// This form is optional.
///
/// See also:
///
/// * [licensesPackageDetailTextZero], the "zero" form
/// * [licensesPackageDetailTextOne], the "one" form
/// * [licensesPackageDetailTextTwo], the "two" form
/// * [licensesPackageDetailTextFew], the "few" form
/// * [licensesPackageDetailTextMany], the "many" form
/// * [licensesPackageDetailTextOther], the "other" form
@protected
String? get licensesPackageDetailTextOne => null;
/// The "two" form of [licensesPackageDetailText].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [licensesPackageDetailTextZero], the "zero" form
/// * [licensesPackageDetailTextOne], the "one" form
/// * [licensesPackageDetailTextTwo], the "two" form
/// * [licensesPackageDetailTextFew], the "few" form
/// * [licensesPackageDetailTextMany], the "many" form
/// * [licensesPackageDetailTextOther], the "other" form
@protected
String? get licensesPackageDetailTextTwo => null;
/// The "many" form of [licensesPackageDetailText].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [licensesPackageDetailTextZero], the "zero" form
/// * [licensesPackageDetailTextOne], the "one" form
/// * [licensesPackageDetailTextTwo], the "two" form
/// * [licensesPackageDetailTextFew], the "few" form
/// * [licensesPackageDetailTextMany], the "many" form
/// * [licensesPackageDetailTextOther], the "other" form
@protected
String? get licensesPackageDetailTextMany => null;
/// The "few" form of [licensesPackageDetailText].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [licensesPackageDetailTextZero], the "zero" form
/// * [licensesPackageDetailTextOne], the "one" form
/// * [licensesPackageDetailTextTwo], the "two" form
/// * [licensesPackageDetailTextFew], the "few" form
/// * [licensesPackageDetailTextMany], the "many" form
/// * [licensesPackageDetailTextOther], the "other" form
@protected
String? get licensesPackageDetailTextFew => null;
/// The "other" form of [licensesPackageDetailText].
///
/// This form is required.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [licensesPackageDetailTextZero], the "zero" form
/// * [licensesPackageDetailTextOne], the "one" form
/// * [licensesPackageDetailTextTwo], the "two" form
/// * [licensesPackageDetailTextFew], the "few" form
/// * [licensesPackageDetailTextMany], the "many" form
/// * [licensesPackageDetailTextOther], the "other" form
@protected
String get licensesPackageDetailTextOther;
@override
String licensesPackageDetailText(int licenseCount) {
return intl.Intl.pluralLogic(
licenseCount,
zero: licensesPackageDetailTextZero,
one: licensesPackageDetailTextOne,
two: licensesPackageDetailTextTwo,
many: licensesPackageDetailTextMany,
few: licensesPackageDetailTextFew,
other: licensesPackageDetailTextOther,
locale: _localeName,
).replaceFirst(r'$licenseCount', formatDecimal(licenseCount));
}
/// The "zero" form of [remainingTextFieldCharacterCount].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [remainingTextFieldCharacterCountZero], the "zero" form
/// * [remainingTextFieldCharacterCountOne], the "one" form
/// * [remainingTextFieldCharacterCountTwo], the "two" form
/// * [remainingTextFieldCharacterCountFew], the "few" form
/// * [remainingTextFieldCharacterCountMany], the "many" form
/// * [remainingTextFieldCharacterCountOther], the "other" form
@protected
String? get remainingTextFieldCharacterCountZero => null;
/// The "one" form of [remainingTextFieldCharacterCount].
///
/// This form is optional.
///
/// See also:
///
/// * [remainingTextFieldCharacterCountZero], the "zero" form
/// * [remainingTextFieldCharacterCountOne], the "one" form
/// * [remainingTextFieldCharacterCountTwo], the "two" form
/// * [remainingTextFieldCharacterCountFew], the "few" form
/// * [remainingTextFieldCharacterCountMany], the "many" form
/// * [remainingTextFieldCharacterCountOther], the "other" form
@protected
String? get remainingTextFieldCharacterCountOne => null;
/// The "two" form of [remainingTextFieldCharacterCount].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [remainingTextFieldCharacterCountZero], the "zero" form
/// * [remainingTextFieldCharacterCountOne], the "one" form
/// * [remainingTextFieldCharacterCountTwo], the "two" form
/// * [remainingTextFieldCharacterCountFew], the "few" form
/// * [remainingTextFieldCharacterCountMany], the "many" form
/// * [remainingTextFieldCharacterCountOther], the "other" form
@protected
String? get remainingTextFieldCharacterCountTwo => null;
/// The "many" form of [remainingTextFieldCharacterCount].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [remainingTextFieldCharacterCountZero], the "zero" form
/// * [remainingTextFieldCharacterCountOne], the "one" form
/// * [remainingTextFieldCharacterCountTwo], the "two" form
/// * [remainingTextFieldCharacterCountFew], the "few" form
/// * [remainingTextFieldCharacterCountMany], the "many" form
/// * [remainingTextFieldCharacterCountOther], the "other" form
@protected
String? get remainingTextFieldCharacterCountMany => null;
/// The "few" form of [remainingTextFieldCharacterCount].
///
/// This form is optional.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [remainingTextFieldCharacterCountZero], the "zero" form
/// * [remainingTextFieldCharacterCountOne], the "one" form
/// * [remainingTextFieldCharacterCountTwo], the "two" form
/// * [remainingTextFieldCharacterCountFew], the "few" form
/// * [remainingTextFieldCharacterCountMany], the "many" form
/// * [remainingTextFieldCharacterCountOther], the "other" form
@protected
String? get remainingTextFieldCharacterCountFew => null;
/// The "other" form of [remainingTextFieldCharacterCount].
///
/// This form is required.
///
/// See also:
///
/// * [Intl.plural], to which this form is passed.
/// * [remainingTextFieldCharacterCountZero], the "zero" form
/// * [remainingTextFieldCharacterCountOne], the "one" form
/// * [remainingTextFieldCharacterCountTwo], the "two" form
/// * [remainingTextFieldCharacterCountFew], the "few" form
/// * [remainingTextFieldCharacterCountMany], the "many" form
/// * [remainingTextFieldCharacterCountOther], the "other" form
@protected
String get remainingTextFieldCharacterCountOther;
@override
String remainingTextFieldCharacterCount(int remaining) {
return intl.Intl.pluralLogic(
remaining,
zero: remainingTextFieldCharacterCountZero,
one: remainingTextFieldCharacterCountOne,
two: remainingTextFieldCharacterCountTwo,
many: remainingTextFieldCharacterCountMany,
few: remainingTextFieldCharacterCountFew,
other: remainingTextFieldCharacterCountOther,
locale: _localeName,
).replaceFirst(r'$remainingCount', formatDecimal(remaining));
}
@override
ScriptCategory get scriptCategory;
/// A [LocalizationsDelegate] for [MaterialLocalizations].
///
/// Most internationalized apps will use [GlobalMaterialLocalizations.delegates]
/// as the value of [MaterialApp.localizationsDelegates] to include
/// the localizations for both the material and widget libraries.
static const LocalizationsDelegate<MaterialLocalizations> delegate = _MaterialLocalizationsDelegate();
/// A value for [MaterialApp.localizationsDelegates] that's typically used by
/// internationalized apps.
///
/// ## Sample code
///
/// To include the localizations provided by this class and by
/// [GlobalWidgetsLocalizations] in a [MaterialApp],
/// use [GlobalMaterialLocalizations.delegates] as the value of
/// [MaterialApp.localizationsDelegates], and specify the locales your
/// app supports with [MaterialApp.supportedLocales]:
///
/// ```dart
/// const MaterialApp(
/// localizationsDelegates: GlobalMaterialLocalizations.delegates,
/// supportedLocales: <Locale>[
/// Locale('en', 'US'), // English
/// Locale('he', 'IL'), // Hebrew
/// ],
/// // ...
/// )
/// ```
static const List<LocalizationsDelegate<dynamic>> delegates = <LocalizationsDelegate<dynamic>>[
GlobalCupertinoLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
];
}
/// Finds the [TimeOfDayFormat] to use instead of the `original` when the
/// `original` uses 12-hour format and [MediaQueryData.alwaysUse24HourFormat]
/// is true.
TimeOfDayFormat _get24HourVersionOf(TimeOfDayFormat original) {
switch (original) {
case TimeOfDayFormat.HH_colon_mm:
case TimeOfDayFormat.HH_dot_mm:
case TimeOfDayFormat.frenchCanadian:
case TimeOfDayFormat.H_colon_mm:
return original;
case TimeOfDayFormat.h_colon_mm_space_a:
case TimeOfDayFormat.a_space_h_colon_mm:
return TimeOfDayFormat.HH_colon_mm;
}
}
class _MaterialLocalizationsDelegate extends LocalizationsDelegate<MaterialLocalizations> {
const _MaterialLocalizationsDelegate();
@override
bool isSupported(Locale locale) => kMaterialSupportedLanguages.contains(locale.languageCode);
static final Map<Locale, Future<MaterialLocalizations>> _loadedTranslations = <Locale, Future<MaterialLocalizations>>{};
@override
Future<MaterialLocalizations> load(Locale locale) {
assert(isSupported(locale));
return _loadedTranslations.putIfAbsent(locale, () {
util.loadDateIntlDataIfNotLoaded();
final String localeName = intl.Intl.canonicalizedLocale(locale.toString());
assert(
locale.toString() == localeName,
'Flutter does not support the non-standard locale form $locale (which '
'might be $localeName',
);
intl.DateFormat fullYearFormat;
intl.DateFormat compactDateFormat;
intl.DateFormat shortDateFormat;
intl.DateFormat mediumDateFormat;
intl.DateFormat longDateFormat;
intl.DateFormat yearMonthFormat;
intl.DateFormat shortMonthDayFormat;
if (intl.DateFormat.localeExists(localeName)) {
fullYearFormat = intl.DateFormat.y(localeName);
compactDateFormat = intl.DateFormat.yMd(localeName);
shortDateFormat = intl.DateFormat.yMMMd(localeName);
mediumDateFormat = intl.DateFormat.MMMEd(localeName);
longDateFormat = intl.DateFormat.yMMMMEEEEd(localeName);
yearMonthFormat = intl.DateFormat.yMMMM(localeName);
shortMonthDayFormat = intl.DateFormat.MMMd(localeName);
} else if (intl.DateFormat.localeExists(locale.languageCode)) {
fullYearFormat = intl.DateFormat.y(locale.languageCode);
compactDateFormat = intl.DateFormat.yMd(locale.languageCode);
shortDateFormat = intl.DateFormat.yMMMd(locale.languageCode);
mediumDateFormat = intl.DateFormat.MMMEd(locale.languageCode);
longDateFormat = intl.DateFormat.yMMMMEEEEd(locale.languageCode);
yearMonthFormat = intl.DateFormat.yMMMM(locale.languageCode);
shortMonthDayFormat = intl.DateFormat.MMMd(locale.languageCode);
} else {
fullYearFormat = intl.DateFormat.y();
compactDateFormat = intl.DateFormat.yMd();
shortDateFormat = intl.DateFormat.yMMMd();
mediumDateFormat = intl.DateFormat.MMMEd();
longDateFormat = intl.DateFormat.yMMMMEEEEd();
yearMonthFormat = intl.DateFormat.yMMMM();
shortMonthDayFormat = intl.DateFormat.MMMd();
}
intl.NumberFormat decimalFormat;
intl.NumberFormat twoDigitZeroPaddedFormat;
if (intl.NumberFormat.localeExists(localeName)) {
decimalFormat = intl.NumberFormat.decimalPattern(localeName);
twoDigitZeroPaddedFormat = intl.NumberFormat('00', localeName);
} else if (intl.NumberFormat.localeExists(locale.languageCode)) {
decimalFormat = intl.NumberFormat.decimalPattern(locale.languageCode);
twoDigitZeroPaddedFormat = intl.NumberFormat('00', locale.languageCode);
} else {
decimalFormat = intl.NumberFormat.decimalPattern();
twoDigitZeroPaddedFormat = intl.NumberFormat('00');
}
return SynchronousFuture<MaterialLocalizations>(getMaterialTranslation(
locale,
fullYearFormat,
compactDateFormat,
shortDateFormat,
mediumDateFormat,
longDateFormat,
yearMonthFormat,
shortMonthDayFormat,
decimalFormat,
twoDigitZeroPaddedFormat,
)!);
});
}
@override
bool shouldReload(_MaterialLocalizationsDelegate old) => false;
@override
String toString() => 'GlobalMaterialLocalizations.delegate(${kMaterialSupportedLanguages.length} locales)';
}
| flutter/packages/flutter_localizations/lib/src/material_localizations.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/material_localizations.dart",
"repo_id": "flutter",
"token_count": 9686
} | 758 |
// 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_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
class TestLocalizations {
TestLocalizations(this.locale, this.prefix);
final Locale locale;
final String? prefix;
static Future<TestLocalizations> loadSync(Locale locale, String? prefix) {
return SynchronousFuture<TestLocalizations>(TestLocalizations(locale, prefix));
}
static Future<TestLocalizations> loadAsync(Locale locale, String? prefix) {
return Future<TestLocalizations>.delayed(
const Duration(milliseconds: 100),
() => TestLocalizations(locale, prefix)
);
}
static TestLocalizations of(BuildContext context) {
return Localizations.of<TestLocalizations>(context, TestLocalizations)!;
}
String get message => '${prefix ?? ""}$locale';
}
class SyncTestLocalizationsDelegate extends LocalizationsDelegate<TestLocalizations> {
SyncTestLocalizationsDelegate([this.prefix]);
final String? prefix; // Changing this value triggers a rebuild
final List<bool> shouldReloadValues = <bool>[];
@override
bool isSupported(Locale locale) => true;
@override
Future<TestLocalizations> load(Locale locale) => TestLocalizations.loadSync(locale, prefix);
@override
bool shouldReload(SyncTestLocalizationsDelegate old) {
shouldReloadValues.add(prefix != old.prefix);
return prefix != old.prefix;
}
@override
String toString() => '${objectRuntimeType(this, 'SyncTestLocalizationsDelegate')}($prefix)';
}
class AsyncTestLocalizationsDelegate extends LocalizationsDelegate<TestLocalizations> {
AsyncTestLocalizationsDelegate([this.prefix]);
final String? prefix; // Changing this value triggers a rebuild
final List<bool> shouldReloadValues = <bool>[];
@override
bool isSupported(Locale locale) => true;
@override
Future<TestLocalizations> load(Locale locale) => TestLocalizations.loadAsync(locale, prefix);
@override
bool shouldReload(AsyncTestLocalizationsDelegate old) {
shouldReloadValues.add(prefix != old.prefix);
return prefix != old.prefix;
}
@override
String toString() => '${objectRuntimeType(this, 'AsyncTestLocalizationsDelegate')}($prefix)';
}
class MoreLocalizations {
MoreLocalizations(this.locale);
final Locale locale;
static Future<MoreLocalizations> loadSync(Locale locale) {
return SynchronousFuture<MoreLocalizations>(MoreLocalizations(locale));
}
static Future<MoreLocalizations> loadAsync(Locale locale) {
return Future<MoreLocalizations>.delayed(
const Duration(milliseconds: 100),
() => MoreLocalizations(locale)
);
}
static MoreLocalizations of(BuildContext context) {
return Localizations.of<MoreLocalizations>(context, MoreLocalizations)!;
}
String get message => '$locale';
}
class SyncMoreLocalizationsDelegate extends LocalizationsDelegate<MoreLocalizations> {
@override
Future<MoreLocalizations> load(Locale locale) => MoreLocalizations.loadSync(locale);
@override
bool isSupported(Locale locale) => true;
@override
bool shouldReload(SyncMoreLocalizationsDelegate old) => false;
}
class AsyncMoreLocalizationsDelegate extends LocalizationsDelegate<MoreLocalizations> {
@override
Future<MoreLocalizations> load(Locale locale) => MoreLocalizations.loadAsync(locale);
@override
bool isSupported(Locale locale) => true;
@override
bool shouldReload(AsyncMoreLocalizationsDelegate old) => false;
}
class OnlyRTLDefaultWidgetsLocalizations extends DefaultWidgetsLocalizations {
@override
TextDirection get textDirection => TextDirection.rtl;
}
class OnlyRTLDefaultWidgetsLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocalizations> {
const OnlyRTLDefaultWidgetsLocalizationsDelegate();
@override
bool isSupported(Locale locale) => true;
@override
Future<WidgetsLocalizations> load(Locale locale) {
return SynchronousFuture<WidgetsLocalizations>(OnlyRTLDefaultWidgetsLocalizations());
}
@override
bool shouldReload(OnlyRTLDefaultWidgetsLocalizationsDelegate old) => false;
}
Widget buildFrame({
Locale? locale,
Iterable<LocalizationsDelegate<dynamic>>? delegates,
required WidgetBuilder buildContent,
LocaleResolutionCallback? localeResolutionCallback,
List<Locale> supportedLocales = const <Locale>[
Locale('en', 'US'),
Locale('en', 'GB'),
],
}) {
return WidgetsApp(
color: const Color(0xFFFFFFFF),
locale: locale,
localizationsDelegates: delegates,
localeResolutionCallback: localeResolutionCallback,
supportedLocales: supportedLocales,
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<void>(
pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) {
return buildContent(context);
}
);
},
);
}
class SyncLoadTest extends StatefulWidget {
const SyncLoadTest({super.key});
@override
SyncLoadTestState createState() => SyncLoadTestState();
}
class SyncLoadTestState extends State<SyncLoadTest> {
@override
Widget build(BuildContext context) {
return Text(
TestLocalizations.of(context).message,
textDirection: TextDirection.rtl,
);
}
}
void main() {
testWidgets('Localizations.localeFor in a WidgetsApp with system locale', (WidgetTester tester) async {
late BuildContext pageContext;
await tester.pumpWidget(
buildFrame(
buildContent: (BuildContext context) {
pageContext = context;
return const Text('Hello World', textDirection: TextDirection.ltr);
}
)
);
await tester.binding.setLocale('en', 'GB');
await tester.pump();
expect(Localizations.localeOf(pageContext), const Locale('en', 'GB'));
await tester.binding.setLocale('en', 'US');
await tester.pump();
expect(Localizations.localeOf(pageContext), const Locale('en', 'US'));
});
testWidgets('Localizations.localeFor in a WidgetsApp with an explicit locale', (WidgetTester tester) async {
const Locale locale = Locale('en', 'US');
late BuildContext pageContext;
await tester.pumpWidget(
buildFrame(
locale: locale,
buildContent: (BuildContext context) {
pageContext = context;
return const Text('Hello World');
},
)
);
expect(Localizations.localeOf(pageContext), locale);
await tester.binding.setLocale('en', 'GB');
await tester.pump();
// The WidgetApp's explicit locale overrides the system's locale.
expect(Localizations.localeOf(pageContext), locale);
});
testWidgets('Synchronously loaded localizations in a WidgetsApp', (WidgetTester tester) async {
final List<LocalizationsDelegate<dynamic>> delegates = <LocalizationsDelegate<dynamic>>[
SyncTestLocalizationsDelegate(),
DefaultWidgetsLocalizations.delegate,
];
Future<void> pumpTest(Locale locale) async {
await tester.pumpWidget(Localizations(
locale: locale,
delegates: delegates,
child: const SyncLoadTest(),
));
}
await pumpTest(const Locale('en', 'US'));
expect(find.text('en_US'), findsOneWidget);
await pumpTest(const Locale('en', 'GB'));
await tester.pump();
expect(find.text('en_GB'), findsOneWidget);
await pumpTest(const Locale('en', 'US'));
await tester.pump();
expect(find.text('en_US'), findsOneWidget);
});
testWidgets('Asynchronously loaded localizations in a WidgetsApp', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
delegates: <LocalizationsDelegate<dynamic>>[
AsyncTestLocalizationsDelegate(),
],
buildContent: (BuildContext context) {
return Text(TestLocalizations.of(context).message);
},
)
);
await tester.pump(const Duration(milliseconds: 50)); // TestLocalizations.loadAsync() takes 100ms
expect(find.text('en_US'), findsNothing); // TestLocalizations hasn't been loaded yet
await tester.pump(const Duration(milliseconds: 50)); // TestLocalizations.loadAsync() completes
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget); // default test locale is US english
await tester.binding.setLocale('en', 'GB');
await tester.pump(const Duration(milliseconds: 100));
await tester.pumpAndSettle();
expect(find.text('en_GB'), findsOneWidget);
await tester.binding.setLocale('en', 'US');
await tester.pump(const Duration(milliseconds: 50));
// TestLocalizations.loadAsync() hasn't completed yet so the old text
// localization is still displayed
expect(find.text('en_GB'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 50)); // finish the async load
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget);
});
testWidgets('Localizations with multiple sync delegates', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
delegates: <LocalizationsDelegate<dynamic>>[
SyncTestLocalizationsDelegate(),
SyncMoreLocalizationsDelegate(),
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Column(
children: <Widget>[
Text('A: ${TestLocalizations.of(context).message}'),
Text('B: ${MoreLocalizations.of(context).message}'),
],
);
},
)
);
// All localizations were loaded synchronously
expect(find.text('A: en_US'), findsOneWidget);
expect(find.text('B: en_US'), findsOneWidget);
});
testWidgets('Localizations with multiple delegates', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
delegates: <LocalizationsDelegate<dynamic>>[
SyncTestLocalizationsDelegate(),
AsyncMoreLocalizationsDelegate(), // No resources until this completes
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Column(
children: <Widget>[
Text('A: ${TestLocalizations.of(context).message}'),
Text('B: ${MoreLocalizations.of(context).message}'),
],
);
},
)
);
await tester.pump(const Duration(milliseconds: 50));
expect(find.text('A: en_US'), findsNothing); // MoreLocalizations.load() hasn't completed yet
expect(find.text('B: en_US'), findsNothing);
await tester.pump(const Duration(milliseconds: 50));
await tester.pumpAndSettle();
expect(find.text('A: en_US'), findsOneWidget);
expect(find.text('B: en_US'), findsOneWidget);
});
testWidgets('Multiple Localizations', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
delegates: <LocalizationsDelegate<dynamic>>[
SyncTestLocalizationsDelegate(),
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Column(
children: <Widget>[
Text('A: ${TestLocalizations.of(context).message}'),
Localizations(
locale: const Locale('en', 'GB'),
delegates: <LocalizationsDelegate<dynamic>>[
SyncTestLocalizationsDelegate(),
DefaultWidgetsLocalizations.delegate,
],
// Create a new context within the en_GB Localization
child: Builder(
builder: (BuildContext context) {
return Text('B: ${TestLocalizations.of(context).message}');
},
),
),
],
);
},
)
);
expect(find.text('A: en_US'), findsOneWidget);
expect(find.text('B: en_GB'), findsOneWidget);
});
// If both the locale and the length and type of a Localizations delegate list
// stays the same BUT one of its delegate.shouldReload() methods returns true,
// then the dependent widgets should rebuild.
testWidgets('Localizations sync delegate shouldReload returns true', (WidgetTester tester) async {
final SyncTestLocalizationsDelegate originalDelegate = SyncTestLocalizationsDelegate();
await tester.pumpWidget(
buildFrame(
delegates: <LocalizationsDelegate<dynamic>>[
originalDelegate,
SyncMoreLocalizationsDelegate(),
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Column(
children: <Widget>[
Text('A: ${TestLocalizations.of(context).message}'),
Text('B: ${MoreLocalizations.of(context).message}'),
],
);
},
)
);
await tester.pumpAndSettle();
expect(find.text('A: en_US'), findsOneWidget);
expect(find.text('B: en_US'), findsOneWidget);
expect(originalDelegate.shouldReloadValues, <bool>[]);
final SyncTestLocalizationsDelegate modifiedDelegate = SyncTestLocalizationsDelegate('---');
await tester.pumpWidget(
buildFrame(
delegates: <LocalizationsDelegate<dynamic>>[
modifiedDelegate,
SyncMoreLocalizationsDelegate(),
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Column(
children: <Widget>[
Text('A: ${TestLocalizations.of(context).message}'),
Text('B: ${MoreLocalizations.of(context).message}'),
],
);
},
)
);
await tester.pumpAndSettle();
expect(find.text('A: ---en_US'), findsOneWidget);
expect(find.text('B: en_US'), findsOneWidget);
expect(modifiedDelegate.shouldReloadValues, <bool>[true]);
expect(originalDelegate.shouldReloadValues, <bool>[]);
});
testWidgets('Localizations async delegate shouldReload returns true', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
delegates: <LocalizationsDelegate<dynamic>>[
AsyncTestLocalizationsDelegate(),
AsyncMoreLocalizationsDelegate(),
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Column(
children: <Widget>[
Text('A: ${TestLocalizations.of(context).message}'),
Text('B: ${MoreLocalizations.of(context).message}'),
],
);
},
)
);
await tester.pumpAndSettle();
expect(find.text('A: en_US'), findsOneWidget);
expect(find.text('B: en_US'), findsOneWidget);
final AsyncTestLocalizationsDelegate modifiedDelegate = AsyncTestLocalizationsDelegate('---');
await tester.pumpWidget(
buildFrame(
delegates: <LocalizationsDelegate<dynamic>>[
modifiedDelegate,
AsyncMoreLocalizationsDelegate(),
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Column(
children: <Widget>[
Text('A: ${TestLocalizations.of(context).message}'),
Text('B: ${MoreLocalizations.of(context).message}'),
],
);
},
)
);
await tester.pumpAndSettle();
expect(find.text('A: ---en_US'), findsOneWidget);
expect(find.text('B: en_US'), findsOneWidget);
expect(modifiedDelegate.shouldReloadValues, <bool>[true]);
});
testWidgets('Directionality tracks system locale', (WidgetTester tester) async {
late BuildContext pageContext;
await tester.pumpWidget(
buildFrame(
delegates: const <LocalizationsDelegate<dynamic>>[
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: const <Locale>[
Locale('en', 'GB'),
Locale('ar', 'EG'),
],
buildContent: (BuildContext context) {
pageContext = context;
return const Text('Hello World');
},
)
);
await tester.binding.setLocale('en', 'GB');
await tester.pump();
expect(Directionality.of(pageContext), TextDirection.ltr);
await tester.binding.setLocale('ar', 'EG');
await tester.pump();
expect(Directionality.of(pageContext), TextDirection.rtl);
});
testWidgets('localeResolutionCallback override', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
localeResolutionCallback: (Locale? newLocale, Iterable<Locale> supportedLocales) {
return const Locale('foo', 'BAR');
},
buildContent: (BuildContext context) {
return Text(Localizations.localeOf(context).toString());
},
)
);
await tester.pumpAndSettle();
expect(find.text('foo_BAR'), findsOneWidget);
await tester.binding.setLocale('en', 'GB');
await tester.pumpAndSettle();
expect(find.text('foo_BAR'), findsOneWidget);
});
testWidgets('supportedLocales and defaultLocaleChangeHandler', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('zh', 'CN'),
Locale('en', 'GB'),
Locale('en', 'CA'),
],
buildContent: (BuildContext context) {
return Text(Localizations.localeOf(context).toString());
},
)
);
await tester.pumpAndSettle();
expect(find.text('en_GB'), findsOneWidget);
// defaultLocaleChangedHandler prefers exact supported locale match
await tester.binding.setLocale('en', 'CA');
await tester.pumpAndSettle();
expect(find.text('en_CA'), findsOneWidget);
// defaultLocaleChangedHandler chooses 1st matching supported locale.languageCode
await tester.binding.setLocale('en', 'US');
await tester.pumpAndSettle();
expect(find.text('en_GB'), findsOneWidget);
// defaultLocaleChangedHandler: no matching supported locale, so use the 1st one
await tester.binding.setLocale('da', 'DA');
await tester.pumpAndSettle();
expect(find.text('zh_CN'), findsOneWidget);
});
testWidgets("Localizations.override widget tracks parent's locale and delegates", (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
// Accept whatever locale we're given
localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) => locale,
delegates: const <LocalizationsDelegate<dynamic>>[
GlobalWidgetsLocalizations.delegate,
],
buildContent: (BuildContext context) {
return Localizations.override(
context: context,
child: Builder(
builder: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
final TextDirection direction = WidgetsLocalizations.of(context).textDirection;
return Text('$locale $direction');
},
),
);
},
)
);
// Initial WidgetTester locale is `en_US`.
await tester.pumpAndSettle();
expect(find.text('en_US TextDirection.ltr'), findsOneWidget);
await tester.binding.setLocale('en', 'CA');
await tester.pumpAndSettle();
expect(find.text('en_CA TextDirection.ltr'), findsOneWidget);
await tester.binding.setLocale('ar', 'EG');
await tester.pumpAndSettle();
expect(find.text('ar_EG TextDirection.rtl'), findsOneWidget);
await tester.binding.setLocale('da', 'DA');
await tester.pumpAndSettle();
expect(find.text('da_DA TextDirection.ltr'), findsOneWidget);
});
testWidgets("Localizations.override widget overrides parent's DefaultWidgetLocalizations", (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
// Accept whatever locale we're given
localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) => locale,
buildContent: (BuildContext context) {
return Localizations.override(
context: context,
delegates: const <OnlyRTLDefaultWidgetsLocalizationsDelegate>[
// Override: no matter what the locale, textDirection is always RTL.
OnlyRTLDefaultWidgetsLocalizationsDelegate(),
],
child: Builder(
builder: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
final TextDirection direction = WidgetsLocalizations.of(context).textDirection;
return Text('$locale $direction');
},
),
);
},
)
);
// Initial WidgetTester locale is `en_US`.
await tester.pumpAndSettle();
expect(find.text('en_US TextDirection.rtl'), findsOneWidget);
await tester.binding.setLocale('en', 'CA');
await tester.pumpAndSettle();
expect(find.text('en_CA TextDirection.rtl'), findsOneWidget);
await tester.binding.setLocale('ar', 'EG');
await tester.pumpAndSettle();
expect(find.text('ar_EG TextDirection.rtl'), findsOneWidget);
await tester.binding.setLocale('da', 'DA');
await tester.pumpAndSettle();
expect(find.text('da_DA TextDirection.rtl'), findsOneWidget);
});
testWidgets('WidgetsApp overrides DefaultWidgetLocalizations', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
// Accept whatever locale we're given
localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) => locale,
delegates: <OnlyRTLDefaultWidgetsLocalizationsDelegate>[
const OnlyRTLDefaultWidgetsLocalizationsDelegate(),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
final TextDirection direction = WidgetsLocalizations.of(context).textDirection;
return Text('$locale $direction');
},
)
);
// Initial WidgetTester locale is `en_US`.
await tester.pumpAndSettle();
expect(find.text('en_US TextDirection.rtl'), findsOneWidget);
await tester.binding.setLocale('en', 'CA');
await tester.pumpAndSettle();
expect(find.text('en_CA TextDirection.rtl'), findsOneWidget);
await tester.binding.setLocale('ar', 'EG');
await tester.pumpAndSettle();
expect(find.text('ar_EG TextDirection.rtl'), findsOneWidget);
await tester.binding.setLocale('da', 'DA');
await tester.pumpAndSettle();
expect(find.text('da_DA TextDirection.rtl'), findsOneWidget);
});
// We provide <Locale>[Locale('en', 'US'), Locale('zh', 'CN')] as ui.window.locales
// for flutter tester so that the behavior of tests match that of production
// environments. Here, we test the default locales.
testWidgets('WidgetsApp DefaultWidgetLocalizations', (WidgetTester tester) async {
await tester.pumpAndSettle();
await tester.pumpWidget(
buildFrame(
// Accept whatever locale we're given
localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) => locale,
delegates: <OnlyRTLDefaultWidgetsLocalizationsDelegate>[
const OnlyRTLDefaultWidgetsLocalizationsDelegate(),
],
buildContent: (BuildContext context) {
final Locale locale1 = WidgetsBinding.instance.platformDispatcher.locales.first;
final Locale locale2 = WidgetsBinding.instance.platformDispatcher.locales[1];
return Text('$locale1 $locale2');
},
)
);
// Initial WidgetTester default locales is `en_US` and `zh_CN`.
await tester.pumpAndSettle();
expect(find.text('en_US zh_CN'), findsOneWidget);
});
testWidgets('WidgetsApp.locale is resolved against supportedLocales', (WidgetTester tester) async {
// app locale matches a supportedLocale
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('zh', 'CN'),
Locale('en', 'US'),
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Text(Localizations.localeOf(context).toString());
},
)
);
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget);
// app locale matches a supportedLocale's language
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('zh', 'CN'),
Locale('en', 'GB'),
],
locale: const Locale('en', 'US'),
buildContent: (BuildContext context) {
return Text(Localizations.localeOf(context).toString());
},
)
);
await tester.pumpAndSettle();
expect(find.text('en_GB'), findsOneWidget);
// app locale matches no supportedLocale
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('zh', 'CN'),
Locale('en', 'US'),
],
locale: const Locale('ab', 'CD'),
buildContent: (BuildContext context) {
return Text(Localizations.localeOf(context).toString());
},
)
);
await tester.pumpAndSettle();
expect(find.text('zh_CN'), findsOneWidget);
});
// Example from http://unicode.org/reports/tr35/#LanguageMatching
testWidgets('WidgetsApp Unicode tr35 1', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('de'),
Locale('fr'),
Locale('ja'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'de', countryCode: 'AT'),
Locale.fromSubtags(languageCode: 'fr'),]
);
await tester.pumpAndSettle();
expect(find.text('de'), findsOneWidget);
});
// Examples from http://unicode.org/reports/tr35/#LanguageMatching
testWidgets('WidgetsApp Unicode tr35 2', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('ja', 'JP'),
Locale('de'),
Locale('zh', 'TW'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'de'),
Locale.fromSubtags(languageCode: 'fr'),
Locale.fromSubtags(languageCode: 'de', countryCode: 'SW'),
Locale.fromSubtags(languageCode: 'it'),]
);
await tester.pumpAndSettle();
expect(find.text('de'), findsOneWidget);
});
testWidgets('WidgetsApp EdgeCase Chinese', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale.fromSubtags(languageCode: 'zh'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'de'),
Locale.fromSubtags(languageCode: 'fr'),
Locale.fromSubtags(languageCode: 'de', countryCode: 'SW'),
Locale.fromSubtags(languageCode: 'zh'),]
);
await tester.pumpAndSettle();
expect(find.text('zh'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', countryCode: 'HK'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_HK'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'HK'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('zh'), findsOneWidget);
// This behavior is up to the implementer to decide if a perfect scriptCode match
// is better than a countryCode match.
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'CN'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),
Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
// languageCode only match is not enough to prevent resolving a perfect match
// further down the preferredLocales list.
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'JP'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
// When no language match, we try for country only, since it is likely users are
// at least familiar with their country's language. This is a possible case only
// on iOS, where countryCode can be selected independently from language and script.
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', scriptCode: 'Hans', countryCode: 'TW'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'TW'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'HK'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_HK'), findsOneWidget);
});
// Same as 'WidgetsApp EdgeCase Chinese' test except the supportedLocales order is
// reversed.
testWidgets('WidgetsApp EdgeCase ReverseChinese', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),
Locale.fromSubtags(languageCode: 'zh'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'de'),
Locale.fromSubtags(languageCode: 'fr'),
Locale.fromSubtags(languageCode: 'de', countryCode: 'SW'),
Locale.fromSubtags(languageCode: 'zh'),]
);
await tester.pumpAndSettle();
expect(find.text('zh'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_HK'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_HK'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', countryCode: 'HK'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_HK'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'HK'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_HK'), findsOneWidget);
// This behavior is up to the implementer to decide if a perfect scriptCode match
// is better than a countryCode match.
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'CN'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),
Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_HK'), findsOneWidget);
// languageCode only match is not enough to prevent resolving a perfect match
// further down the preferredLocales list.
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'JP'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'zh', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hans_CN'), findsOneWidget);
// When no language match, we try for country only, since it is likely users are
// at least familiar with their country's language. This is a possible case only
// on iOS, where countryCode can be selected independently from language and script.
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', scriptCode: 'Hans', countryCode: 'TW'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'TW'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_TW'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'HK'),]
);
await tester.pumpAndSettle();
expect(find.text('zh_Hant_HK'), findsOneWidget);
});
// Examples from https://developer.android.com/guide/topics/resources/multilingual-support
testWidgets('WidgetsApp Android', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('en'),
Locale('de', 'DE'),
Locale('es', 'ES'),
Locale('fr', 'FR'),
Locale('it', 'IT'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'fr', countryCode: 'CH'),]
);
await tester.pumpAndSettle();
expect(find.text('fr_FR'), findsOneWidget);
});
// Examples from https://developer.android.com/guide/topics/resources/multilingual-support
testWidgets('WidgetsApp Android', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('en'),
Locale('de', 'DE'),
Locale('es', 'ES'),
Locale('it', 'IT'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'fr', countryCode: 'CH'),
Locale.fromSubtags(languageCode: 'it', countryCode: 'CH'),]
);
await tester.pumpAndSettle();
expect(find.text('it_IT'), findsOneWidget);
});
testWidgets('WidgetsApp Country-only fallback', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('de', 'DE'),
Locale('de', 'AU'),
Locale('de', 'LU'),
Locale('de', 'CH'),
Locale('es', 'ES'),
Locale('es', 'US'),
Locale('it', 'IT'),
Locale('zh', 'CN'),
Locale('zh', 'TW'),
Locale('fr', 'FR'),
Locale('br', 'FR'),
Locale('pt', 'BR'),
Locale('pt', 'PT'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ar', countryCode: 'CH'),]
);
await tester.pumpAndSettle();
expect(find.text('de_CH'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ar', countryCode: 'FR'),]
);
await tester.pumpAndSettle();
expect(find.text('fr_FR'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ar', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'es', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('es_US'), findsOneWidget);
// Strongly prefer matching first locale even if next one is perfect.
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'pt'),
Locale.fromSubtags(languageCode: 'pt', countryCode: 'PT'),]
);
await tester.pumpAndSettle();
expect(find.text('pt_PT'), findsOneWidget);
// Don't country match with any other available match. This behavior is
// up for reconsideration.
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ar', countryCode: 'BR'),
Locale.fromSubtags(languageCode: 'pt'),]
);
await tester.pumpAndSettle();
expect(find.text('pt_BR'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ar', countryCode: 'BR'),
Locale.fromSubtags(languageCode: 'pt', countryCode: 'PT'),]
);
await tester.pumpAndSettle();
expect(find.text('pt_PT'), findsOneWidget);
});
// Simulates a Chinese-default app that supports english in Canada but not
// French. French-Canadian users should get 'en_CA' instead of Chinese.
testWidgets('WidgetsApp Multilingual country', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('zh', 'CN'),
Locale('en', 'CA'),
Locale('en', 'US'),
Locale('en', 'AU'),
Locale('de', 'DE'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'fr', countryCode: 'CA'),
Locale.fromSubtags(languageCode: 'fr'),]
);
await tester.pumpAndSettle();
expect(find.text('en_CA'), findsOneWidget);
});
testWidgets('WidgetsApp Common cases', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
// Decently well localized app.
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('en', 'GB'),
Locale('en', 'AU'),
Locale('en', 'CA'),
Locale('zh', 'CN'),
Locale('zh', 'TW'),
Locale('de', 'DE'),
Locale('de', 'CH'),
Locale('es', 'MX'),
Locale('es', 'ES'),
Locale('es', 'AR'),
Locale('es', 'CO'),
Locale('ru', 'RU'),
Locale('fr', 'FR'),
Locale('fr', 'CA'),
Locale('ar', 'SA'),
Locale('ar', 'EG'),
Locale('ar', 'IQ'),
Locale('ar', 'MA'),
Locale('af'),
Locale('bg'),
Locale('nl', 'NL'),
Locale('pl'),
Locale('cs'),
Locale('fa'),
Locale('el'),
Locale('he'),
Locale('hi'),
Locale('pa'),
Locale('ta'),
Locale('id'),
Locale('it', 'IT'),
Locale('ja'),
Locale('ko'),
Locale('ms'),
Locale('mn'),
Locale('pt', 'BR'),
Locale('pt', 'PT'),
Locale('sv', 'SE'),
Locale('th'),
Locale('tr'),
Locale('vi'),
],
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en'),]
);
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'CA'),]
);
await tester.pumpAndSettle();
expect(find.text('en_CA'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'AU'),]
);
await tester.pumpAndSettle();
expect(find.text('en_AU'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ar', countryCode: 'CH'),]
);
await tester.pumpAndSettle();
expect(find.text('ar_SA'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ar'),]
);
await tester.pumpAndSettle();
expect(find.text('ar_SA'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ar', countryCode: 'IQ'),]
);
await tester.pumpAndSettle();
expect(find.text('ar_IQ'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'es', countryCode: 'ES'),]
);
await tester.pumpAndSettle();
expect(find.text('es_ES'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'es'),]
);
await tester.pumpAndSettle();
expect(find.text('es_MX'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'pa', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('pa'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'hi', countryCode: 'IN'),]
);
await tester.pumpAndSettle();
expect(find.text('hi'), findsOneWidget);
// Multiple preferred locales:
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'NZ'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'AU'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'GB'),
Locale.fromSubtags(languageCode: 'en'),]
);
await tester.pumpAndSettle();
expect(find.text('en_AU'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'ab'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'NZ'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'AU'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'GB'),
Locale.fromSubtags(languageCode: 'en'),]
);
await tester.pumpAndSettle();
expect(find.text('en_AU'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'NZ'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'PH'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'ZA'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'CB'),]
);
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'CA'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'AU'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'GB'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('en_CA'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'da'),
Locale.fromSubtags(languageCode: 'en'),
Locale.fromSubtags(languageCode: 'en', countryCode: 'CA'),]
);
await tester.pumpAndSettle();
expect(find.text('en_CA'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'da'),
Locale.fromSubtags(languageCode: 'fo'),
Locale.fromSubtags(languageCode: 'hr'),]
);
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'da'),
Locale.fromSubtags(languageCode: 'fo'),
Locale.fromSubtags(languageCode: 'hr', countryCode: 'CA'),]
);
await tester.pumpAndSettle();
expect(find.text('en_CA'), findsOneWidget);
});
testWidgets('WidgetsApp invalid preferredLocales', (WidgetTester tester) async {
await tester.pumpWidget(
buildFrame(
supportedLocales: const <Locale>[
Locale('zh', 'CN'),
Locale('en', 'CA'),
Locale('en', 'US'),
Locale('en', 'AU'),
Locale('de', 'DE'),
],
localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) {
if (locale == null) {
return const Locale('und', 'US');
}
return const Locale('en', 'US');
},
buildContent: (BuildContext context) {
final Locale locale = Localizations.localeOf(context);
return Text('$locale');
},
)
);
await tester.binding.setLocales(const <Locale>[
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),]
);
await tester.pumpAndSettle();
expect(find.text('en_US'), findsOneWidget);
await tester.binding.setLocales(const <Locale>[]);
await tester.pumpAndSettle();
expect(find.text('und_US'), findsOneWidget);
});
}
| flutter/packages/flutter_localizations/test/widgets_test.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/test/widgets_test.dart",
"repo_id": "flutter",
"token_count": 20321
} | 759 |
// 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;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:matcher/expect.dart';
import 'package:matcher/src/expect/async_matcher.dart'; // ignore: implementation_imports
import 'package:test_api/hooks.dart' show TestFailure;
import 'binding.dart';
import 'finders.dart';
import 'goldens.dart';
/// Render the closest [RepaintBoundary] of the [element] into an image.
///
/// See also:
///
/// * [OffsetLayer.toImage] which is the actual method being called.
Future<ui.Image> captureImage(Element element) {
assert(element.renderObject != null);
RenderObject renderObject = element.renderObject!;
while (!renderObject.isRepaintBoundary) {
renderObject = renderObject.parent!;
}
assert(!renderObject.debugNeedsPaint);
final OffsetLayer layer = renderObject.debugLayer! as OffsetLayer;
return layer.toImage(renderObject.paintBounds);
}
/// Whether or not [captureImage] is supported.
///
/// This can be used to skip tests on platforms that don't support
/// capturing images.
///
/// Currently this is true except when tests are running in the context of a web
/// browser (`flutter test --platform chrome`).
const bool canCaptureImage = true;
/// The matcher created by [matchesGoldenFile]. This class is enabled when the
/// test is running on a VM using conditional import.
class MatchesGoldenFile extends AsyncMatcher {
/// Creates an instance of [MatchesGoldenFile]. Called by [matchesGoldenFile].
const MatchesGoldenFile(this.key, this.version);
/// Creates an instance of [MatchesGoldenFile]. Called by [matchesGoldenFile].
MatchesGoldenFile.forStringPath(String path, this.version) : key = Uri.parse(path);
/// The [key] to the golden image.
final Uri key;
/// The [version] of the golden image.
final int? version;
@override
Future<String?> matchAsync(dynamic item) async {
final Uri testNameUri = goldenFileComparator.getTestUri(key, version);
Uint8List? buffer;
if (item is Future<List<int>?>) {
final List<int>? bytes = await item;
buffer = bytes == null ? null : Uint8List.fromList(bytes);
} else if (item is List<int>) {
buffer = Uint8List.fromList(item);
}
if (buffer != null) {
if (autoUpdateGoldenFiles) {
await goldenFileComparator.update(testNameUri, buffer);
return null;
}
try {
final bool success = await goldenFileComparator.compare(buffer, testNameUri);
return success ? null : 'does not match';
} on TestFailure catch (ex) {
return ex.message;
}
}
Future<ui.Image?> imageFuture;
final bool disposeImage; // set to true if the matcher created and owns the image and must therefore dispose it.
if (item is Future<ui.Image?>) {
imageFuture = item;
disposeImage = false;
} else if (item is ui.Image) {
imageFuture = Future<ui.Image>.value(item);
disposeImage = false;
} else if (item is Finder) {
final Iterable<Element> elements = item.evaluate();
if (elements.isEmpty) {
return 'could not be rendered because no widget was found';
} else if (elements.length > 1) {
return 'matched too many widgets';
}
imageFuture = captureImage(elements.single);
disposeImage = true;
} else {
throw AssertionError('must provide a Finder, Image, Future<Image>, List<int>, or Future<List<int>>');
}
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance;
return binding.runAsync<String?>(() async {
final ui.Image? image = await imageFuture;
if (image == null) {
throw AssertionError('Future<Image> completed to null');
}
try {
final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png);
if (bytes == null) {
return 'could not encode screenshot.';
}
if (autoUpdateGoldenFiles) {
await goldenFileComparator.update(testNameUri, bytes.buffer.asUint8List());
return null;
}
try {
final bool success = await goldenFileComparator.compare(bytes.buffer.asUint8List(), testNameUri);
return success ? null : 'does not match';
} on TestFailure catch (ex) {
return ex.message;
}
} finally {
if (disposeImage) {
image.dispose();
}
}
});
}
@override
Description describe(Description description) {
final Uri testNameUri = goldenFileComparator.getTestUri(key, version);
return description.add('one widget whose rasterized image matches golden image "$testNameUri"');
}
}
| flutter/packages/flutter_test/lib/src/_matchers_io.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/_matchers_io.dart",
"repo_id": "flutter",
"token_count": 1713
} | 760 |
// 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';
/// Whether the test is running in a web browser compiled to JavaScript.
///
/// See also:
///
/// * [kIsWeb], the equivalent constant in the `foundation` library.
const bool isBrowser = identical(0, 0.0);
/// Whether the test is running on the Windows operating system.
///
/// This does not include tests compiled to JavaScript running in a browser on
/// the Windows operating system.
///
/// See also:
///
/// * [isBrowser], which reports true for tests running in browsers.
bool get isWindows {
if (isBrowser) {
return false;
}
return Platform.isWindows;
}
/// Whether the test is running on the macOS operating system.
///
/// This does not include tests compiled to JavaScript running in a browser on
/// the macOS operating system.
///
/// See also:
///
/// * [isBrowser], which reports true for tests running in browsers.
bool get isMacOS {
if (isBrowser) {
return false;
}
return Platform.isMacOS;
}
/// Whether the test is running on the Linux operating system.
///
/// This does not include tests compiled to JavaScript running in a browser on
/// the Linux operating system.
///
/// See also:
///
/// * [isBrowser], which reports true for tests running in browsers.
bool get isLinux {
if (isBrowser) {
return false;
}
return Platform.isLinux;
}
| flutter/packages/flutter_test/lib/src/platform.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/platform.dart",
"repo_id": "flutter",
"token_count": 404
} | 761 |
// 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('text contrast guideline', () {
testWidgets('black text on white background - Text Widget - direct style',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
const Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.black),
),
),
);
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets('Multiple text with same label', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
const Column(
children: <Widget>[
Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.black),
),
Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.black),
),
],
),
),
);
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets(
'Multiple text with same label but Nodes excluded from '
'semantic tree have failing contrast should pass a11y guideline ',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
const Column(
children: <Widget>[
Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.black),
),
SizedBox(height: 50),
Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.black),
),
SizedBox(height: 50),
ExcludeSemantics(
child: Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.white),
),
),
],
),
),
);
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets('white text on black background - Text Widget - direct style',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
Container(
width: 200.0,
height: 200.0,
color: Colors.black,
child: const Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.white),
),
),
),
);
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets('White text on white background fails contrast test',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
Container(
width: 200.0,
height: 300.0,
color: Colors.white,
child: const Column(
children: <Widget>[
Text(
'this is a white text',
style: TextStyle(fontSize: 14.0, color: Colors.white),
),
SizedBox(height: 50),
Text(
'this is a black text test1',
style: TextStyle(fontSize: 14.0, color: Colors.black),
),
SizedBox(height: 50),
Text(
'this is a black text test2',
style: TextStyle(fontSize: 14.0, color: Colors.black),
),
],
),
),
),
);
await expectLater(tester, doesNotMeetGuideline(textContrastGuideline));
handle.dispose();
});
const Color surface = Color(0xFFF0F0F0);
/// Shades of blue with contrast ratio of 2.9, 4.4, 4.5 from [surface].
const Color blue29 = Color(0xFF7E7EFB);
const Color blue44 = Color(0xFF5757FF);
const Color blue45 = Color(0xFF5252FF);
const List<TextStyle> textStylesMeetingGuideline = <TextStyle>[
TextStyle(color: blue44, backgroundColor: surface, fontSize: 18),
TextStyle(color: blue44, backgroundColor: surface, fontSize: 14, fontWeight: FontWeight.bold),
TextStyle(color: blue45, backgroundColor: surface),
];
const List<TextStyle> textStylesDoesNotMeetingGuideline = <TextStyle>[
TextStyle(color: blue44, backgroundColor: surface),
TextStyle(color: blue29, backgroundColor: surface, fontSize: 18),
];
Widget appWithTextWidget(TextStyle style) => _boilerplate(
Text('this is text', style: style.copyWith(height: 30.0)),
);
for (final TextStyle style in textStylesMeetingGuideline) {
testWidgets('text with style $style', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(appWithTextWidget(style));
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
}
for (final TextStyle style in textStylesDoesNotMeetingGuideline) {
testWidgets('text with $style', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(appWithTextWidget(style));
await expectLater(tester, doesNotMeetGuideline(textContrastGuideline));
handle.dispose();
});
}
testWidgets('black text on white background - Text Widget - direct style',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
const Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.black),
),
),
);
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets('white text on black background - Text Widget - direct style',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
Container(
width: 200.0,
height: 200.0,
color: Colors.black,
child: const Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.white),
),
),
),
);
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets('Material text field - amber on amber',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
Container(
width: 200.0,
height: 200.0,
color: Colors.amberAccent,
child: TextField(
style: const TextStyle(color: Colors.amber),
controller: TextEditingController(text: 'this is a test'),
),
),
),
);
await expectLater(tester, doesNotMeetGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets('Correctly identify failures in complex transforms', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
Padding(
padding: const EdgeInsets.only(left: 100),
child: Semantics(
container: true,
child: Padding(
padding: const EdgeInsets.only(left: 100),
child: Semantics(
container: true,
child: Container(
width: 100.0,
height: 200.0,
color: Colors.amberAccent,
child: const Text(
'this',
style: TextStyle(color: Colors.amber),
),
),
),
),
),
),
),
);
await expectLater(tester, doesNotMeetGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets('Material text field - default style',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
SizedBox(
width: 100,
child: TextField(
controller: TextEditingController(text: 'this is a test'),
),
),
),
);
await tester.idle();
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
testWidgets('Material2: yellow text on yellow background fails with correct message',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
useMaterial3: false,
Container(
width: 200.0,
height: 200.0,
color: Colors.yellow,
child: const Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.yellowAccent),
),
),
),
);
final Evaluation result = await textContrastGuideline.evaluate(tester);
expect(result.passed, false);
expect(
result.reason,
'SemanticsNode#4(Rect.fromLTRB(300.0, 200.0, 500.0, 400.0), '
'label: "this is a test", textDirection: ltr):\n'
'Expected contrast ratio of at least 4.5 but found 1.17 for a font '
'size of 14.0.\n'
'The computed colors was:\n'
'light - Color(0xfffafafa), dark - Color(0xffffeb3b)\n'
'See also: https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html',
);
handle.dispose();
});
testWidgets('Material3: yellow text on yellow background fails with correct message',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
useMaterial3: true,
Container(
width: 200.0,
height: 200.0,
color: Colors.yellow,
child: const Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.yellowAccent),
),
),
),
);
final Evaluation result = await textContrastGuideline.evaluate(tester);
expect(result.passed, false);
expect(
result.reason,
'SemanticsNode#4(Rect.fromLTRB(300.0, 200.0, 500.0, 400.0), '
'label: "this is a test", textDirection: ltr):\n'
'Expected contrast ratio of at least 4.5 but found 1.16 for a font '
'size of 14.0.\n'
'The computed colors was:\n'
'light - Color(0xfffef7ff), dark - Color(0xffffeb3b)\n'
'See also: https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html',
);
handle.dispose();
});
testWidgets('label without corresponding text is skipped',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
Semantics(
label: 'This is not text',
container: true,
child: const SizedBox(
width: 200.0,
height: 200.0,
child: Placeholder(),
),
),
),
);
final Evaluation result = await textContrastGuideline.evaluate(tester);
expect(result.passed, true);
handle.dispose();
});
testWidgets('offscreen text is skipped', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
Stack(
children: <Widget>[
Positioned(
left: -300.0,
child: Container(
width: 200.0,
height: 200.0,
color: Colors.yellow,
child: const Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.yellowAccent),
),
),
),
],
),
),
);
final Evaluation result = await textContrastGuideline.evaluate(tester);
expect(result.passed, true);
handle.dispose();
});
testWidgets('Disabled button is excluded from text contrast guideline',
(WidgetTester tester) async {
// Regression test https://github.com/flutter/flutter/issues/94428
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
_boilerplate(
ElevatedButton(
onPressed: null,
child: Container(
width: 200.0,
height: 200.0,
color: Colors.yellow,
child: const Text(
'this is a test',
style: TextStyle(fontSize: 14.0, color: Colors.yellowAccent),
),
),
),
),
);
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
});
group('custom minimum contrast guideline', () {
Widget iconWidget({
IconData icon = Icons.search,
required Color color,
required Color background,
}) {
return Container(
padding: const EdgeInsets.all(8.0),
color: background,
child: Icon(icon, color: color),
);
}
Widget textWidget({
String text = 'Text',
required Color color,
required Color background,
}) {
return Container(
padding: const EdgeInsets.all(8.0),
color: background,
child: Text(text, style: TextStyle(color: color)),
);
}
Widget rowWidget(List<Widget> widgets) => _boilerplate(Row(children: widgets));
final Finder findIcons = find.byWidgetPredicate((Widget widget) => widget is Icon);
final Finder findTexts = find.byWidgetPredicate((Widget widget) => widget is Text);
final Finder findIconsAndTexts = find.byWidgetPredicate((Widget widget) => widget is Icon || widget is Text);
testWidgets('Black icons on white background', (WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.black, background: Colors.white),
iconWidget(color: Colors.black, background: Colors.white),
]));
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
});
testWidgets('Black icons on black background', (WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.black, background: Colors.black),
iconWidget(color: Colors.black, background: Colors.black),
]));
await expectLater(
tester,
doesNotMeetGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
});
testWidgets('White icons on black background ("dark mode")',
(WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.white, background: Colors.black),
iconWidget(color: Colors.white, background: Colors.black),
]));
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
});
testWidgets('Using different icons', (WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.black, background: Colors.white, icon: Icons.more_horiz),
iconWidget(color: Colors.black, background: Colors.white, icon: Icons.description),
iconWidget(color: Colors.black, background: Colors.white, icon: Icons.image),
iconWidget(color: Colors.black, background: Colors.white, icon: Icons.beach_access),
]));
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
});
testWidgets('One invalid instance fails entire test',
(WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.black, background: Colors.white),
iconWidget(color: Colors.black, background: Colors.black),
]));
await expectLater(
tester,
doesNotMeetGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
});
testWidgets('White on different colors, passing',
(WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.white, background: Colors.red[800]!, icon: Icons.more_horiz),
iconWidget(color: Colors.white, background: Colors.green[800]!, icon: Icons.description),
iconWidget(color: Colors.white, background: Colors.blue[800]!, icon: Icons.image),
iconWidget(color: Colors.white, background: Colors.purple[800]!, icon: Icons.beach_access),
]));
await expectLater(tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findIcons)));
});
testWidgets('White on different colors, failing',
(WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.white, background: Colors.red[200]!, icon: Icons.more_horiz),
iconWidget(color: Colors.white, background: Colors.green[400]!, icon: Icons.description),
iconWidget(color: Colors.white, background: Colors.blue[600]!, icon: Icons.image),
iconWidget(color: Colors.white, background: Colors.purple[800]!, icon: Icons.beach_access),
]));
await expectLater(
tester,
doesNotMeetGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
});
testWidgets('Absence of icons, passing', (WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[]));
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
});
testWidgets('Absence of icons, passing - 2nd test',
(WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
textWidget(color: Colors.black, background: Colors.white),
textWidget(color: Colors.black, background: Colors.black),
]));
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
});
testWidgets('Guideline ignores widgets of other types',
(WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.black, background: Colors.white),
iconWidget(color: Colors.black, background: Colors.white),
textWidget(color: Colors.black, background: Colors.white),
textWidget(color: Colors.black, background: Colors.black),
]));
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
await expectLater(
tester,
doesNotMeetGuideline(CustomMinimumContrastGuideline(finder: findTexts)),
);
await expectLater(
tester,
doesNotMeetGuideline(CustomMinimumContrastGuideline(finder: findIconsAndTexts)),
);
});
testWidgets('Custom minimum ratio - Icons', (WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.blue, background: Colors.white),
iconWidget(color: Colors.black, background: Colors.white),
]));
await expectLater(
tester,
doesNotMeetGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findIcons, minimumRatio: 3.0)),
);
});
testWidgets('Custom minimum ratio - Texts', (WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
textWidget(color: Colors.blue, background: Colors.white),
textWidget(color: Colors.black, background: Colors.white),
]));
await expectLater(
tester,
doesNotMeetGuideline(CustomMinimumContrastGuideline(finder: findTexts)),
);
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findTexts, minimumRatio: 3.0)),
);
});
testWidgets(
'Custom minimum ratio - Different standards for icons and texts',
(WidgetTester tester) async {
await tester.pumpWidget(rowWidget(<Widget>[
iconWidget(color: Colors.blue, background: Colors.white),
iconWidget(color: Colors.black, background: Colors.white),
textWidget(color: Colors.blue, background: Colors.white),
textWidget(color: Colors.black, background: Colors.white),
]));
await expectLater(
tester,
doesNotMeetGuideline(CustomMinimumContrastGuideline(finder: findIcons)),
);
await expectLater(
tester,
meetsGuideline(CustomMinimumContrastGuideline(finder: findTexts, minimumRatio: 3.0)),
);
});
});
group('tap target size guideline', () {
testWidgets('Tappable box at 48 by 48', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(
SizedBox(
width: 48.0,
height: 48.0,
child: GestureDetector(onTap: () {}),
),
));
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
handle.dispose();
});
testWidgets('Tappable box at 47 by 48', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(
SizedBox(
width: 47.0,
height: 48.0,
child: GestureDetector(onTap: () {}),
),
));
await expectLater(
tester,
doesNotMeetGuideline(androidTapTargetGuideline),
);
handle.dispose();
});
testWidgets('Tappable box at 48 by 47', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(
SizedBox(
width: 48.0,
height: 47.0,
child: GestureDetector(onTap: () {}),
),
));
await expectLater(
tester,
doesNotMeetGuideline(androidTapTargetGuideline),
);
handle.dispose();
});
testWidgets('Tappable box at 48 by 48 shrunk by transform',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(
Transform.scale(
scale: 0.5, // should have new height of 24 by 24.
child: SizedBox(
width: 48.0,
height: 48.0,
child: GestureDetector(onTap: () {}),
),
),
));
await expectLater(
tester,
doesNotMeetGuideline(androidTapTargetGuideline),
);
handle.dispose();
});
testWidgets('Too small tap target fails with the correct message',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(
SizedBox(
width: 48.0,
height: 47.0,
child: GestureDetector(onTap: () {}),
),
));
final Evaluation result = await androidTapTargetGuideline.evaluate(tester);
expect(result.passed, false);
expect(
result.reason,
'SemanticsNode#4(Rect.fromLTRB(376.0, 276.5, 424.0, 323.5), '
'actions: [tap]): expected tap '
'target size of at least Size(48.0, 48.0), '
'but found Size(48.0, 47.0)\n'
'See also: https://support.google.com/accessibility/android/answer/7101858?hl=en',
);
handle.dispose();
});
testWidgets('Box that overlaps edge of window is skipped',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
final Widget smallBox = SizedBox(
width: 48.0,
height: 47.0,
child: GestureDetector(onTap: () {}),
);
await tester.pumpWidget(
MaterialApp(
home: Stack(
children: <Widget>[
Positioned(
left: 0.0,
top: -1.0,
child: smallBox,
),
],
),
),
);
final Evaluation overlappingTopResult = await androidTapTargetGuideline.evaluate(tester);
expect(overlappingTopResult.passed, true);
await tester.pumpWidget(
MaterialApp(
home: Stack(
children: <Widget>[
Positioned(
left: -1.0,
top: 0.0,
child: smallBox,
),
],
),
),
);
final Evaluation overlappingLeftResult = await androidTapTargetGuideline.evaluate(tester);
expect(overlappingLeftResult.passed, true);
await tester.pumpWidget(
MaterialApp(
home: Stack(
children: <Widget>[
Positioned(
bottom: -1.0,
child: smallBox,
),
],
),
),
);
final Evaluation overlappingBottomResult = await androidTapTargetGuideline.evaluate(tester);
expect(overlappingBottomResult.passed, true);
await tester.pumpWidget(
MaterialApp(
home: Stack(
children: <Widget>[
Positioned(
right: -1.0,
child: smallBox,
),
],
),
),
);
final Evaluation overlappingRightResult = await androidTapTargetGuideline.evaluate(tester);
expect(overlappingRightResult.passed, true);
handle.dispose();
});
testWidgets('Does not fail on mergedIntoParent child',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(MergeSemantics(
child: Semantics(
container: true,
child: SizedBox(
width: 50.0,
height: 50.0,
child: Semantics(
container: true,
child: GestureDetector(
onTap: () {},
child: const SizedBox(width: 4.0, height: 4.0),
),
),
),
),
)));
final Evaluation overlappingRightResult = await androidTapTargetGuideline.evaluate(tester);
expect(overlappingRightResult.passed, true);
handle.dispose();
});
testWidgets('Does not fail on links', (WidgetTester tester) async {
Widget textWithLink() {
return Builder(
builder: (BuildContext context) {
return RichText(
text: TextSpan(
children: <InlineSpan>[
const TextSpan(text: 'See examples at '),
TextSpan(
text: 'flutter repo',
recognizer: TapGestureRecognizer()..onTap = () {},
),
],
),
);
},
);
}
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(textWithLink()));
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
handle.dispose();
});
testWidgets('Tap size test can handle partially off-screen items', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Foo')),
body: ListView(
controller: controller,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 10, right: 10),
child: SizedBox(
width: 100,
height: 100,
child: Semantics(container: true, onTap: () {}, child: const Text('hello'))),
),
Container(
height: 1000,
color: Colors.red,
),
]
),
),
)
);
controller.jumpTo(90);
await tester.pump();
await expectLater(tester, meetsGuideline(iOSTapTargetGuideline));
});
});
group('Labeled tappable node guideline', () {
testWidgets('Passes when node is labeled', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(Semantics(
container: true,
onTap: () {},
label: 'test',
child: const SizedBox(width: 10.0, height: 10.0),
)));
final Evaluation result = await labeledTapTargetGuideline.evaluate(tester);
expect(result.passed, true);
handle.dispose();
});
testWidgets('Fails if long-press has no label',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(Semantics(
container: true,
onLongPress: () {},
label: '',
child: const SizedBox(width: 10.0, height: 10.0),
)));
final Evaluation result = await labeledTapTargetGuideline.evaluate(tester);
expect(result.passed, false);
handle.dispose();
});
testWidgets('Fails if tap has no label', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(Semantics(
container: true,
onTap: () {},
label: '',
child: const SizedBox(width: 10.0, height: 10.0),
)));
final Evaluation result = await labeledTapTargetGuideline.evaluate(tester);
expect(result.passed, false);
handle.dispose();
});
testWidgets('Passes if tap is merged into labeled node',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(Semantics(
container: true,
onLongPress: () {},
label: '',
child: Semantics(
label: 'test',
child: const SizedBox(width: 10.0, height: 10.0),
),
)));
final Evaluation result = await labeledTapTargetGuideline.evaluate(tester);
expect(result.passed, true);
handle.dispose();
});
testWidgets('Passes if text field does not have label', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(_boilerplate(const TextField()));
final Evaluation result = await labeledTapTargetGuideline.evaluate(tester);
expect(result.passed, true);
handle.dispose();
});
});
testWidgets('regression test for material widget',
(WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(MaterialApp(
theme: ThemeData.light(),
home: Scaffold(
backgroundColor: Colors.white,
body: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFFBBC04),
elevation: 0,
),
onPressed: () {},
child: const Text('Button', style: TextStyle(color: Colors.black)),
),
),
));
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
}
Widget _boilerplate(Widget child, { bool? useMaterial3 }) {
return MaterialApp(
theme: ThemeData(useMaterial3: useMaterial3),
home: Scaffold(
body: Center(child: child),
),
);
}
| flutter/packages/flutter_test/test/accessibility_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/accessibility_test.dart",
"repo_id": "flutter",
"token_count": 14966
} | 762 |
// 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
Future<ui.Image> createTestImage(int width, int height, ui.Color color) async {
final ui.Paint paint = ui.Paint()
..style = ui.PaintingStyle.stroke
..strokeWidth = 1.0
..color = color;
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas pictureCanvas = ui.Canvas(recorder);
pictureCanvas.drawCircle(Offset.zero, 20.0, paint);
final ui.Picture picture = recorder.endRecording();
final ui.Image image = await picture.toImage(width, height);
picture.dispose();
return image;
}
void main() {
const ui.Color red = ui.Color.fromARGB(255, 255, 0, 0);
const ui.Color green = ui.Color.fromARGB(255, 0, 255, 0);
const ui.Color transparentRed = ui.Color.fromARGB(128, 255, 0, 0);
group('succeeds', () {
testWidgets('when images have the same content', (WidgetTester tester) async {
final ui.Image image1 = await createTestImage(100, 100, red);
addTearDown(image1.dispose);
final ui.Image referenceImage1 = await createTestImage(100, 100, red);
addTearDown(referenceImage1.dispose);
await expectLater(image1, matchesReferenceImage(referenceImage1));
final ui.Image image2 = await createTestImage(100, 100, green);
addTearDown(image2.dispose);
final ui.Image referenceImage2 = await createTestImage(100, 100, green);
addTearDown(referenceImage2.dispose);
await expectLater(image2, matchesReferenceImage(referenceImage2));
final ui.Image image3 = await createTestImage(100, 100, transparentRed);
addTearDown(image3.dispose);
final ui.Image referenceImage3 = await createTestImage(100, 100, transparentRed);
addTearDown(referenceImage3.dispose);
await expectLater(image3, matchesReferenceImage(referenceImage3));
});
testWidgets('when images are identical', (WidgetTester tester) async {
final ui.Image image = await createTestImage(100, 100, red);
addTearDown(image.dispose);
await expectLater(image, matchesReferenceImage(image));
});
testWidgets('when widget looks the same', (WidgetTester tester) async {
addTearDown(tester.view.reset);
tester.view
..physicalSize = const Size(10, 10)
..devicePixelRatio = 1;
const ValueKey<String> repaintBoundaryKey = ValueKey<String>('boundary');
await tester.pumpWidget(
const RepaintBoundary(
key: repaintBoundaryKey,
child: ColoredBox(color: red),
),
);
final ui.Image referenceImage = (tester.renderObject(find.byKey(repaintBoundaryKey)) as RenderRepaintBoundary).toImageSync();
addTearDown(referenceImage.dispose);
await expectLater(find.byKey(repaintBoundaryKey), matchesReferenceImage(referenceImage));
});
});
group('fails', () {
testWidgets('when image sizes do not match', (WidgetTester tester) async {
final ui.Image red50 = await createTestImage(50, 50, red);
addTearDown(red50.dispose);
final ui.Image red100 = await createTestImage(100, 100, red);
addTearDown(red100.dispose);
expect(
await matchesReferenceImage(red50).matchAsync(red100),
equals('does not match as width or height do not match. [100×100] != [50×50]'),
);
});
testWidgets('when image pixels do not match', (WidgetTester tester) async {
final ui.Image red100 = await createTestImage(100, 100, red);
addTearDown(red100.dispose);
final ui.Image transparentRed100 = await createTestImage(100, 100, transparentRed);
addTearDown(transparentRed100.dispose);
expect(
await matchesReferenceImage(red100).matchAsync(transparentRed100),
equals('does not match on 57 pixels'),
);
final ui.Image green100 = await createTestImage(100, 100, green);
addTearDown(green100.dispose);
expect(
await matchesReferenceImage(red100).matchAsync(green100),
equals('does not match on 57 pixels'),
);
});
testWidgets('when widget does not look the same', (WidgetTester tester) async {
addTearDown(tester.view.reset);
tester.view
..physicalSize = const Size(10, 10)
..devicePixelRatio = 1;
const ValueKey<String> repaintBoundaryKey = ValueKey<String>('boundary');
await tester.pumpWidget(
const RepaintBoundary(
key: repaintBoundaryKey,
child: ColoredBox(color: red),
),
);
final ui.Image referenceImage = (tester.renderObject(find.byKey(repaintBoundaryKey)) as RenderRepaintBoundary).toImageSync();
addTearDown(referenceImage.dispose);
await tester.pumpWidget(
const RepaintBoundary(
key: repaintBoundaryKey,
child: ColoredBox(color: green),
),
);
expect(
await matchesReferenceImage(referenceImage).matchAsync(
find.byKey(repaintBoundaryKey),
),
equals('does not match on 100 pixels'),
);
});
});
}
| flutter/packages/flutter_test/test/reference_image_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/reference_image_test.dart",
"repo_id": "flutter",
"token_count": 2006
} | 763 |
# 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.
require 'json'
# Minimum CocoaPods Ruby version is 2.0.
# Don't depend on features newer than that.
# Hook for Podfile setup, installation settings.
#
# @example
# flutter_ios_podfile_setup
# target 'Runner' do
# ...
# end
def flutter_ios_podfile_setup; end
# Same as flutter_ios_podfile_setup for macOS.
def flutter_macos_podfile_setup; end
# Determine whether the target depends on Flutter (including transitive dependency)
def depends_on_flutter(target, engine_pod_name)
target.dependencies.any? do |dependency|
if dependency.name == engine_pod_name
return true
end
if depends_on_flutter(dependency.target, engine_pod_name)
return true
end
end
return false
end
# Add iOS build settings to pod targets.
#
# @example
# post_install do |installer|
# installer.pods_project.targets.each do |target|
# flutter_additional_ios_build_settings(target)
# end
# end
# @param [PBXAggregateTarget] target Pod target.
def flutter_additional_ios_build_settings(target)
return unless target.platform_name == :ios
# [target.deployment_target] is a [String] formatted as "8.0".
inherit_deployment_target = target.deployment_target[/\d+/].to_i < 12
# ARC code targeting iOS 8 does not build on Xcode 14.3.
force_to_arc_supported_min = target.deployment_target[/\d+/].to_i < 9
# This podhelper script is at $FLUTTER_ROOT/packages/flutter_tools/bin.
# Add search paths from $FLUTTER_ROOT/bin/cache/artifacts/engine.
artifacts_dir = File.join('..', '..', '..', '..', 'bin', 'cache', 'artifacts', 'engine')
debug_framework_dir = File.expand_path(File.join(artifacts_dir, 'ios', 'Flutter.xcframework'), __FILE__)
unless Dir.exist?(debug_framework_dir)
# iOS artifacts have not been downloaded.
raise "#{debug_framework_dir} must exist. If you're running pod install manually, make sure \"flutter precache --ios\" is executed first"
end
release_framework_dir = File.expand_path(File.join(artifacts_dir, 'ios-release', 'Flutter.xcframework'), __FILE__)
# Bundles are com.apple.product-type.bundle, frameworks are com.apple.product-type.framework.
target_is_resource_bundle = target.respond_to?(:product_type) && target.product_type == 'com.apple.product-type.bundle'
target.build_configurations.each do |build_configuration|
# Build both x86_64 and arm64 simulator archs for all dependencies. If a single plugin does not support arm64 simulators,
# the app and all frameworks will fall back to x86_64. Unfortunately that case is not detectable in this script.
# Therefore all pods must have a x86_64 slice available, or linking a x86_64 app will fail.
build_configuration.build_settings['ONLY_ACTIVE_ARCH'] = 'NO' if build_configuration.type == :debug
# Workaround https://github.com/CocoaPods/CocoaPods/issues/11402, do not sign resource bundles.
if target_is_resource_bundle
build_configuration.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'
build_configuration.build_settings['CODE_SIGNING_REQUIRED'] = 'NO'
build_configuration.build_settings['CODE_SIGNING_IDENTITY'] = '-'
build_configuration.build_settings['EXPANDED_CODE_SIGN_IDENTITY'] = '-'
end
# ARC code targeting iOS 8 does not build on Xcode 14.3. Force to at least iOS 9.
build_configuration.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0' if force_to_arc_supported_min
# Skip other updates if it does not depend on Flutter (including transitive dependency)
next unless depends_on_flutter(target, 'Flutter')
# Bitcode is deprecated, Flutter.framework bitcode blob will have been stripped.
build_configuration.build_settings['ENABLE_BITCODE'] = 'NO'
# Profile can't be derived from the CocoaPods build configuration. Use release framework (for linking only).
# TODO(stuartmorgan): Handle local engines here; see https://github.com/flutter/flutter/issues/132228
configuration_engine_dir = build_configuration.type == :debug ? debug_framework_dir : release_framework_dir
Dir.new(configuration_engine_dir).each_child do |xcframework_file|
next if xcframework_file.start_with?('.') # Hidden file, possibly on external disk.
if xcframework_file.end_with?('-simulator') # ios-arm64_x86_64-simulator
build_configuration.build_settings['FRAMEWORK_SEARCH_PATHS[sdk=iphonesimulator*]'] = "\"#{configuration_engine_dir}/#{xcframework_file}\" $(inherited)"
elsif xcframework_file.start_with?('ios-') # ios-arm64
build_configuration.build_settings['FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]'] = "\"#{configuration_engine_dir}/#{xcframework_file}\" $(inherited)"
# else Info.plist or another platform.
end
end
build_configuration.build_settings['OTHER_LDFLAGS'] = '$(inherited) -framework Flutter'
build_configuration.build_settings['CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER'] = 'NO'
# Suppress warning when pod supports a version lower than the minimum supported by Xcode (Xcode 12 - iOS 9).
# This warning is harmless but confusing--it's not a bad thing for dependencies to support a lower version.
# When deleted, the deployment version will inherit from the higher version derived from the 'Runner' target.
# If the pod only supports a higher version, do not delete to correctly produce an error.
build_configuration.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET' if inherit_deployment_target
# Override legacy Xcode 11 style VALID_ARCHS[sdk=iphonesimulator*]=x86_64 and prefer Xcode 12 EXCLUDED_ARCHS.
build_configuration.build_settings['VALID_ARCHS[sdk=iphonesimulator*]'] = '$(ARCHS_STANDARD)'
build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = '$(inherited) i386'
build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphoneos*]'] = '$(inherited) armv7'
end
end
# Same as flutter_ios_podfile_setup for macOS.
def flutter_additional_macos_build_settings(target)
return unless target.platform_name == :osx
# [target.deployment_target] is a [String] formatted as "10.8".
deployment_target_major, deployment_target_minor = target.deployment_target.match(/(\d+).?(\d*)/).captures
# ARC code targeting macOS 10.10 does not build on Xcode 14.3.
force_to_arc_supported_min = !target.deployment_target.blank? &&
(deployment_target_major.to_i < 10) ||
(deployment_target_major.to_i == 10 && deployment_target_minor.to_i < 11)
# Suppress warning when pod supports a version lower than the minimum supported by the latest stable version of Xcode (currently 10.14).
# This warning is harmless but confusing--it's not a bad thing for dependencies to support a lower version.
inherit_deployment_target = !target.deployment_target.blank? &&
(deployment_target_major.to_i < 10) ||
(deployment_target_major.to_i == 10 && deployment_target_minor.to_i < 14)
# This podhelper script is at $FLUTTER_ROOT/packages/flutter_tools/bin.
# Add search paths from $FLUTTER_ROOT/bin/cache/artifacts/engine.
artifacts_dir = File.join('..', '..', '..', '..', 'bin', 'cache', 'artifacts', 'engine')
debug_framework_dir = File.expand_path(File.join(artifacts_dir, 'darwin-x64', 'FlutterMacOS.xcframework'), __FILE__)
release_framework_dir = File.expand_path(File.join(artifacts_dir, 'darwin-x64-release', 'FlutterMacOS.xcframework'), __FILE__)
application_path = File.dirname(defined_in_file.realpath) if respond_to?(:defined_in_file)
# Find the local engine path, if any.
local_engine = application_path.nil? ?
nil : flutter_get_local_engine_dir(File.join(application_path, 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'))
unless Dir.exist?(debug_framework_dir)
# macOS artifacts have not been downloaded.
raise "#{debug_framework_dir} must exist. If you're running pod install manually, make sure \"flutter precache --macos\" is executed first"
end
target.build_configurations.each do |build_configuration|
# ARC code targeting macOS 10.10 does not build on Xcode 14.3. Force to at least macOS 10.11.
build_configuration.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.11' if force_to_arc_supported_min
# Skip other updates if it does not depend on Flutter (including transitive dependency)
next unless depends_on_flutter(target, 'FlutterMacOS')
if local_engine
configuration_engine_dir = File.expand_path(File.join(local_engine, 'FlutterMacOS.xcframework'), __FILE__)
else
# Profile can't be derived from the CocoaPods build configuration. Use release framework (for linking only).
configuration_engine_dir = (build_configuration.type == :debug ? debug_framework_dir : release_framework_dir)
end
Dir.new(configuration_engine_dir).each_child do |xcframework_file|
if xcframework_file.start_with?('macos-') # Could be macos-arm64_x86_64, macos-arm64, macos-x86_64
build_configuration.build_settings['FRAMEWORK_SEARCH_PATHS'] = "\"#{configuration_engine_dir}/#{xcframework_file}\" $(inherited)"
end
end
# When deleted, the deployment version will inherit from the higher version derived from the 'Runner' target.
# If the pod only supports a higher version, do not delete to correctly produce an error.
build_configuration.build_settings.delete 'MACOSX_DEPLOYMENT_TARGET' if inherit_deployment_target
# Avoid error about Pods-Runner not supporting provisioning profiles.
# Framework signing is handled at the app layer, not per framework, so disallow individual signing.
build_configuration.build_settings.delete 'EXPANDED_CODE_SIGN_IDENTITY'
build_configuration.build_settings['CODE_SIGNING_REQUIRED'] = 'NO'
build_configuration.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'
end
end
# Install pods needed to embed Flutter iOS engine and plugins.
#
# @example
# target 'Runner' do
# flutter_install_all_ios_pods
# end
# @param [String] ios_application_path Path of the iOS directory of the Flutter app.
# Optional, defaults to the Podfile directory.
def flutter_install_all_ios_pods(ios_application_path = nil)
flutter_install_ios_engine_pod(ios_application_path)
flutter_install_plugin_pods(ios_application_path, '.symlinks', 'ios')
end
# Same as flutter_install_all_ios_pods for macOS.
def flutter_install_all_macos_pods(macos_application_path = nil)
flutter_install_macos_engine_pod(macos_application_path)
flutter_install_plugin_pods(macos_application_path, File.join('Flutter', 'ephemeral', '.symlinks'), 'macos')
end
# Install iOS Flutter engine pod.
#
# @example
# target 'Runner' do
# flutter_install_ios_engine_pod
# end
# @param [String] ios_application_path Path of the iOS directory of the Flutter app.
# Optional, defaults to the Podfile directory.
def flutter_install_ios_engine_pod(ios_application_path = nil)
# defined_in_file is set by CocoaPods and is a Pathname to the Podfile.
ios_application_path ||= File.dirname(defined_in_file.realpath) if respond_to?(:defined_in_file)
raise 'Could not find iOS application path' unless ios_application_path
podspec_directory = File.join(ios_application_path, 'Flutter')
copied_podspec_path = File.expand_path('Flutter.podspec', podspec_directory)
# Generate a fake podspec to represent the Flutter framework.
# This is only necessary because plugin podspecs contain `s.dependency 'Flutter'`, and if this Podfile
# does not add a `pod 'Flutter'` CocoaPods will try to download it from the CocoaPods trunk.
File.open(copied_podspec_path, 'w') do |podspec|
podspec.write <<~EOF
#
# This podspec is NOT to be published. It is only used as a local source!
# This is a generated file; do not edit or check into version control.
#
Pod::Spec.new do |s|
s.name = 'Flutter'
s.version = '1.0.0'
s.summary = 'A UI toolkit for beautiful and fast apps.'
s.homepage = 'https://flutter.dev'
s.license = { :type => 'BSD' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :git => 'https://github.com/flutter/engine', :tag => s.version.to_s }
s.ios.deployment_target = '12.0'
# Framework linking is handled by Flutter tooling, not CocoaPods.
# Add a placeholder to satisfy `s.dependency 'Flutter'` plugin podspecs.
s.vendored_frameworks = 'path/to/nothing'
end
EOF
end
# Keep pod path relative so it can be checked into Podfile.lock.
pod 'Flutter', path: flutter_relative_path_from_podfile(podspec_directory)
end
# Same as flutter_install_ios_engine_pod for macOS.
def flutter_install_macos_engine_pod(mac_application_path = nil)
# defined_in_file is set by CocoaPods and is a Pathname to the Podfile.
mac_application_path ||= File.dirname(defined_in_file.realpath) if respond_to?(:defined_in_file)
raise 'Could not find macOS application path' unless mac_application_path
copied_podspec_path = File.expand_path('FlutterMacOS.podspec', File.join(mac_application_path, 'Flutter', 'ephemeral'))
# Generate a fake podspec to represent the FlutterMacOS framework.
# This is only necessary because plugin podspecs contain `s.dependency 'FlutterMacOS'`, and if this Podfile
# does not add a `pod 'FlutterMacOS'` CocoaPods will try to download it from the CocoaPods trunk.
File.open(copied_podspec_path, 'w') do |podspec|
podspec.write <<~EOF
#
# This podspec is NOT to be published. It is only used as a local source!
# This is a generated file; do not edit or check into version control.
#
Pod::Spec.new do |s|
s.name = 'FlutterMacOS'
s.version = '1.0.0'
s.summary = 'A UI toolkit for beautiful and fast apps.'
s.homepage = 'https://flutter.dev'
s.license = { :type => 'BSD' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :git => 'https://github.com/flutter/engine', :tag => s.version.to_s }
s.osx.deployment_target = '10.14'
# Framework linking is handled by Flutter tooling, not CocoaPods.
# Add a placeholder to satisfy `s.dependency 'FlutterMacOS'` plugin podspecs.
s.vendored_frameworks = 'path/to/nothing'
end
EOF
end
# Keep pod path relative so it can be checked into Podfile.lock.
pod 'FlutterMacOS', path: File.join('Flutter', 'ephemeral')
end
# Install Flutter plugin pods.
#
# @param [String] application_path Path of the directory of the Flutter app.
# Optional, defaults to the Podfile directory.
def flutter_install_plugin_pods(application_path = nil, relative_symlink_dir, platform)
# defined_in_file is set by CocoaPods and is a Pathname to the Podfile.
application_path ||= File.dirname(defined_in_file.realpath) if respond_to?(:defined_in_file)
raise 'Could not find application path' unless application_path
# Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
# referring to absolute paths on developers' machines.
symlink_dir = File.expand_path(relative_symlink_dir, application_path)
system('rm', '-rf', symlink_dir) # Avoid the complication of dependencies like FileUtils.
symlink_plugins_dir = File.expand_path('plugins', symlink_dir)
system('mkdir', '-p', symlink_plugins_dir)
plugins_file = File.join(application_path, '..', '.flutter-plugins-dependencies')
plugin_pods = flutter_parse_plugins_file(plugins_file, platform)
plugin_pods.each do |plugin_hash|
plugin_name = plugin_hash['name']
plugin_path = plugin_hash['path']
has_native_build = plugin_hash.fetch('native_build', true)
# iOS and macOS code can be shared in "darwin" directory, otherwise
# respectively in "ios" or "macos" directories.
shared_darwin_source = plugin_hash.fetch('shared_darwin_source', false)
platform_directory = shared_darwin_source ? 'darwin' : platform
next unless plugin_name && plugin_path && has_native_build
symlink = File.join(symlink_plugins_dir, plugin_name)
File.symlink(plugin_path, symlink)
# Keep pod path relative so it can be checked into Podfile.lock.
relative = flutter_relative_path_from_podfile(symlink)
pod plugin_name, path: File.join(relative, platform_directory)
end
end
# .flutter-plugins-dependencies format documented at
# https://flutter.dev/go/plugins-list-migration
def flutter_parse_plugins_file(file, platform)
file_path = File.expand_path(file)
return [] unless File.exist? file_path
dependencies_file = File.read(file)
dependencies_hash = JSON.parse(dependencies_file)
# dependencies_hash.dig('plugins', 'ios') not available until Ruby 2.3
return [] unless dependencies_hash.has_key?('plugins')
return [] unless dependencies_hash['plugins'].has_key?(platform)
dependencies_hash['plugins'][platform] || []
end
def flutter_relative_path_from_podfile(path)
# defined_in_file is set by CocoaPods and is a Pathname to the Podfile.
project_directory_pathname = defined_in_file.dirname
pathname = Pathname.new File.expand_path(path)
relative = pathname.relative_path_from project_directory_pathname
relative.to_s
end
def flutter_parse_xcconfig_file(file)
file_abs_path = File.expand_path(file)
if !File.exist? file_abs_path
return [];
end
entries = Hash.new
skip_line_start_symbols = ["#", "/"]
File.foreach(file_abs_path) { |line|
next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
key_value_pair = line.split(pattern = '=')
if key_value_pair.length == 2
entries[key_value_pair[0].strip()] = key_value_pair[1].strip();
else
puts "Invalid key/value pair: #{line}"
end
}
return entries
end
def flutter_get_local_engine_dir(xcconfig_file)
file_abs_path = File.expand_path(xcconfig_file)
if !File.exist? file_abs_path
return nil
end
config = flutter_parse_xcconfig_file(xcconfig_file)
local_engine = config['LOCAL_ENGINE']
base_dir = config['FLUTTER_ENGINE']
if !local_engine.nil? && !base_dir.nil?
return File.join(base_dir, 'out', local_engine)
end
return nil
end
| flutter/packages/flutter_tools/bin/podhelper.rb/0 | {
"file_path": "flutter/packages/flutter_tools/bin/podhelper.rb",
"repo_id": "flutter",
"token_count": 6601
} | 764 |
To manually update `settings.gradle`, follow these steps:
1. Copy `settings.gradle` as `settings_aar.gradle`
2. Remove the following code from `settings_aar.gradle`:
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/manual_migration_settings.gradle.md/0 | {
"file_path": "flutter/packages/flutter_tools/gradle/manual_migration_settings.gradle.md",
"repo_id": "flutter",
"token_count": 240
} | 765 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="catalog - basic_app_bar" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/examples/catalog/lib/basic_app_bar.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___basic_app_bar.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___basic_app_bar.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 98
} | 766 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="layers - styled_text" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/examples/layers/widgets/styled_text.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___styled_text.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___styled_text.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 96
} | 767 |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/vcs.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/vcs.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 66
} | 768 |
// 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 '../build_info.dart';
import '../project.dart';
/// The builder in the current context.
AndroidBuilder? get androidBuilder {
return context.get<AndroidBuilder>();
}
abstract class AndroidBuilder {
const AndroidBuilder();
/// Builds an AAR artifact.
Future<void> buildAar({
required FlutterProject project,
required Set<AndroidBuildInfo> androidBuildInfo,
required String target,
String? outputDirectoryPath,
required String buildNumber,
});
/// Builds an APK artifact.
Future<void> buildApk({
required FlutterProject project,
required AndroidBuildInfo androidBuildInfo,
required String target,
bool configOnly = false,
});
/// Builds an App Bundle artifact.
Future<void> buildAab({
required FlutterProject project,
required AndroidBuildInfo androidBuildInfo,
required String target,
bool validateDeferredComponents = true,
bool deferredComponentsEnabled = false,
bool configOnly = false,
});
/// Returns a list of available build variant from the Android project.
Future<List<String>> getBuildVariants({required FlutterProject project});
/// Outputs app link related project settings into a json file.
///
/// The return future resolves to the path of the json file.
Future<String> outputsAppLinkSettings(
String buildVariant, {
required FlutterProject project,
});
}
| flutter/packages/flutter_tools/lib/src/android/android_builder.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/android/android_builder.dart",
"repo_id": "flutter",
"token_count": 447
} | 769 |
// 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 'package:unified_analytics/unified_analytics.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/os.dart';
import '../base/platform.dart';
import '../base/utils.dart';
import '../base/version.dart';
import '../base/version_range.dart';
import '../build_info.dart';
import '../cache.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../reporting/reporting.dart';
import 'android_sdk.dart';
// These are the versions used in the project templates.
//
// In general, Flutter aims to default to the latest version.
// However, this currently requires to migrate existing integration tests to the latest supported values.
//
// Please see the README before changing any of these values.
const String templateDefaultGradleVersion = '7.6.3';
const String templateAndroidGradlePluginVersion = '7.3.0';
const String templateAndroidGradlePluginVersionForModule = '7.3.0';
const String templateKotlinGradlePluginVersion = '1.7.10';
// The Flutter Gradle Plugin is only applied to app projects, and modules that
// are built from source using (`include_flutter.groovy`). The remaining
// projects are: plugins, and modules compiled as AARs. In modules, the
// ephemeral directory `.android` is always regenerated after `flutter pub get`,
// so new versions are picked up after a Flutter upgrade.
//
// Please see the README before changing any of these values.
const String compileSdkVersion = '34';
const String minSdkVersion = '21';
const String targetSdkVersion = '34';
const String ndkVersion = '23.1.7779620';
// Update these when new major versions of Java are supported by new Gradle
// versions that we support.
// Source of truth: https://docs.gradle.org/current/userguide/compatibility.html
const String oneMajorVersionHigherJavaVersion = '20';
// Update this when new versions of Gradle come out including minor versions
// and should correspond to the maximum Gradle version we test in CI.
//
// Supported here means supported by the tooling for
// flutter analyze --suggestions and does not imply broader flutter support.
const String maxKnownAndSupportedGradleVersion = '8.0.2';
// Update this when new versions of AGP come out.
//
// Supported here means tooling is aware of this version's Java <-> AGP
// compatibility.
@visibleForTesting
const String maxKnownAndSupportedAgpVersion = '8.1';
// Update this when new versions of AGP come out.
const String maxKnownAgpVersion = '8.3';
// Oldest documented version of AGP that has a listed minimum
// compatible Java version.
const String oldestDocumentedJavaAgpCompatibilityVersion = '4.2';
// Constant used in [_buildAndroidGradlePluginRegExp] and
// [_settingsAndroidGradlePluginRegExp] to identify the version section.
const String _versionGroupName = 'version';
// AGP can be defined in the dependencies block of [build.gradle] or [build.gradle.kts].
// Expected content (covers both classpath and compileOnly cases):
// Groovy DSL with single quotes - 'com.android.tools.build:gradle:{{agpVersion}}'
// Groovy DSL with double quotes - "com.android.tools.build:gradle:{{agpVersion}}"
// Kotlin DSL - ("com.android.tools.build.gradle:{{agpVersion}}")
// ?<version> is used to name the version group which helps with extraction.
final RegExp _androidGradlePluginRegExpFromDependencies = RegExp(
r"""[^\/]*\s*((\bclasspath\b)|(\bcompileOnly\b))\s*\(?['"]com\.android\.tools\.build:gradle:(?<version>\d+(\.\d+){1,2})\)?""",
multiLine: true);
// AGP can be defined in the plugins block of [build.gradle],
// [build.gradle.kts], [settings.gradle], or [settings.gradle.kts].
// Expected content:
// Groovy DSL with single quotes - id 'com.android.application' version '{{agpVersion}}'
// Groovy DSL with double quotes - id "com.android.application" version "{{agpVersion}}"
// Kotlin DSL - id("com.android.application") version "{{agpVersion}}"
// ?<version> is used to name the version group which helps with extraction.
final RegExp _androidGradlePluginRegExpFromId = RegExp(
r"""[^\/]*s*id\s*\(?['"]com\.android\.application['"]\)?\s+version\s+['"](?<version>\d+(\.\d+){1,2})\)?""",
multiLine: true);
// Expected content format (with lines above and below).
// Version can have 2 or 3 numbers.
// 'distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip'
// '^\s*' protects against commented out lines.
final RegExp distributionUrlRegex =
RegExp(r'^\s*distributionUrl\s*=\s*.*\.zip', multiLine: true);
// Modified version of the gradle distribution url match designed to only match
// gradle.org urls so that we can guarantee any modifications to the url
// still points to a hosted zip.
final RegExp gradleOrgVersionMatch =
RegExp(
r'^\s*distributionUrl\s*=\s*https\\://services\.gradle\.org/distributions/gradle-((?:\d|\.)+)-(.*)\.zip',
multiLine: true
);
// This matches uncommented minSdkVersion lines in the module-level build.gradle
// file which have minSdkVersion 16,17, 18, 19, or 20.
final RegExp tooOldMinSdkVersionMatch = RegExp(
r'(?<=^\s*)minSdkVersion (1[6789]|20)(?=\s*(?://|$))',
multiLine: true,
);
// From https://docs.gradle.org/current/userguide/command_line_interface.html#command_line_interface
const String gradleVersionFlag = r'--version';
// Directory under android/ that gradle uses to store gradle information.
// Regularly used with [gradleWrapperDirectory] and
// [gradleWrapperPropertiesFilename].
// Different from the directory of gradle files stored in
// `_cache.getArtifactDirectory('gradle_wrapper')`
const String gradleDirectoryName = 'gradle';
const String gradleWrapperDirectoryName = 'wrapper';
const String gradleWrapperPropertiesFilename = 'gradle-wrapper.properties';
/// Provides utilities to run a Gradle task, such as finding the Gradle executable
/// or constructing a Gradle project.
class GradleUtils {
GradleUtils({
required Platform platform,
required Logger logger,
required Cache cache,
required OperatingSystemUtils operatingSystemUtils,
}) : _platform = platform,
_logger = logger,
_cache = cache,
_operatingSystemUtils = operatingSystemUtils;
final Cache _cache;
final Platform _platform;
final Logger _logger;
final OperatingSystemUtils _operatingSystemUtils;
/// Gets the Gradle executable path and prepares the Gradle project.
/// This is the `gradlew` or `gradlew.bat` script in the `android/` directory.
String getExecutable(FlutterProject project) {
final Directory androidDir = project.android.hostAppGradleRoot;
injectGradleWrapperIfNeeded(androidDir);
final File gradle = androidDir.childFile(getGradlewFileName(_platform));
if (gradle.existsSync()) {
_logger.printTrace('Using gradle from ${gradle.absolute.path}.');
// If the Gradle executable doesn't have execute permission,
// then attempt to set it.
_operatingSystemUtils.makeExecutable(gradle);
return gradle.absolute.path;
}
throwToolExit(
'Unable to locate gradlew script. Please check that ${gradle.path} '
'exists or that ${gradle.dirname} can be read.');
}
/// Injects the Gradle wrapper files if any of these files don't exist in [directory].
void injectGradleWrapperIfNeeded(Directory directory) {
copyDirectory(
_cache.getArtifactDirectory('gradle_wrapper'),
directory,
shouldCopyFile: (File sourceFile, File destinationFile) {
// Don't override the existing files in the project.
return !destinationFile.existsSync();
},
onFileCopied: (File source, File dest) {
_operatingSystemUtils.makeExecutable(dest);
}
);
// Add the `gradle-wrapper.properties` file if it doesn't exist.
final Directory propertiesDirectory = directory
.childDirectory(gradleDirectoryName)
.childDirectory(gradleWrapperDirectoryName);
final File propertiesFile =
propertiesDirectory.childFile(gradleWrapperPropertiesFilename);
if (propertiesFile.existsSync()) {
return;
}
propertiesDirectory.createSync(recursive: true);
final String gradleVersion =
getGradleVersionForAndroidPlugin(directory, _logger);
final String propertyContents = '''
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\\://services.gradle.org/distributions/gradle-$gradleVersion-all.zip
''';
propertiesFile.writeAsStringSync(propertyContents);
}
}
/// Returns the Gradle version that the current Android plugin depends on when found,
/// otherwise it returns a default version.
///
/// The Android plugin version is specified in the [build.gradle],
/// [build.gradle.kts], [settings.gradle], or [settings.gradle.kts] file within
/// the project's Android directory.
String getGradleVersionForAndroidPlugin(Directory directory, Logger logger) {
final String? androidPluginVersion = getAgpVersion(directory, logger);
if (androidPluginVersion == null) {
logger.printTrace(
'AGP version cannot be determined, assuming Gradle version: $templateDefaultGradleVersion');
return templateDefaultGradleVersion;
}
return getGradleVersionFor(androidPluginVersion);
}
/// Returns the gradle file from the top level directory.
/// The returned file is not guaranteed to be present.
File getGradleWrapperFile(Directory directory) {
return directory.childDirectory(gradleDirectoryName)
.childDirectory(gradleWrapperDirectoryName)
.childFile(gradleWrapperPropertiesFilename);
}
/// Parses the gradle wrapper distribution url to return a string containing
/// the version number.
///
/// Expected input is of the form '...gradle-7.4.2-all.zip', and the output
/// would be of the form '7.4.2'.
String? parseGradleVersionFromDistributionUrl(String? distributionUrl) {
if (distributionUrl == null) {
return null;
}
final List<String> zipParts = distributionUrl.split('-');
if (zipParts.length < 2) {
return null;
}
return zipParts[1];
}
/// Returns either the gradle-wrapper.properties value from the passed in
/// [directory] or if not present the version available in local path.
///
/// If gradle version is not found null is returned.
/// [directory] should be an android directory with a build.gradle file.
Future<String?> getGradleVersion(
Directory directory, Logger logger, ProcessManager processManager) async {
final File propertiesFile = getGradleWrapperFile(directory);
if (propertiesFile.existsSync()) {
final String wrapperFileContent = propertiesFile.readAsStringSync();
final RegExpMatch? distributionUrl =
distributionUrlRegex.firstMatch(wrapperFileContent);
if (distributionUrl != null) {
final String? gradleVersion =
parseGradleVersionFromDistributionUrl(distributionUrl.group(0));
if (gradleVersion != null) {
return gradleVersion;
} else {
// Did not find gradle zip url. Likely this is a bug in our parsing.
logger.printWarning(_formatParseWarning(wrapperFileContent));
}
} else {
// If no distributionUrl log then treat as if there was no propertiesFile.
logger.printTrace(
'$propertiesFile does not provide a Gradle version falling back to system gradle.');
}
} else {
// Could not find properties file.
logger.printTrace(
'$propertiesFile does not exist falling back to system gradle');
}
// System installed Gradle version.
if (processManager.canRun('gradle')) {
final String gradleVersionVerbose =
(await processManager.run(<String>['gradle', gradleVersionFlag])).stdout
as String;
// Expected format:
/*
------------------------------------------------------------
Gradle 7.6
------------------------------------------------------------
Build time: 2022-11-25 13:35:10 UTC
Revision: daece9dbc5b79370cc8e4fd6fe4b2cd400e150a8
Kotlin: 1.7.10
Groovy: 3.0.13
Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM: 17.0.6 (Homebrew 17.0.6+0)
OS: Mac OS X 13.2.1 aarch64
*/
// Observation shows that the version can have 2 or 3 numbers.
// Inner parentheticals `(\.\d+)?` denote the optional third value.
// Outer parentheticals `Gradle (...)` denote a grouping used to extract
// the version number.
final RegExp gradleVersionRegex = RegExp(r'Gradle\s+(\d+\.\d+(?:\.\d+)?)');
final RegExpMatch? version =
gradleVersionRegex.firstMatch(gradleVersionVerbose);
if (version == null) {
// Most likely a bug in our parse implementation/regex.
logger.printWarning(_formatParseWarning(gradleVersionVerbose));
return null;
}
return version.group(1);
} else {
logger.printTrace('Could not run system gradle');
return null;
}
}
/// Returns the Android Gradle Plugin (AGP) version that the current project
/// depends on when found, null otherwise.
///
/// The Android plugin version is specified in the [build.gradle],
/// [build.gradle.kts], [settings.gradle] or [settings.gradle.kts]
/// file within the project's Android directory ([androidDirectory]).
String? getAgpVersion(Directory androidDirectory, Logger logger) {
File buildFile = androidDirectory.childFile('build.gradle');
if (!buildFile.existsSync()) {
buildFile = androidDirectory.childFile('build.gradle.kts');
}
if (!buildFile.existsSync()) {
logger.printTrace(
'Cannot find build.gradle/build.gradle.kts in $androidDirectory');
return null;
}
final String buildFileContent = buildFile.readAsStringSync();
final RegExpMatch? buildMatchClasspath =
_androidGradlePluginRegExpFromDependencies.firstMatch(buildFileContent);
if (buildMatchClasspath != null) {
final String? androidPluginVersion =
buildMatchClasspath.namedGroup(_versionGroupName);
logger.printTrace('$buildFile provides AGP version from classpath: $androidPluginVersion');
return androidPluginVersion;
}
final RegExpMatch? buildMatchId =
_androidGradlePluginRegExpFromId.firstMatch(buildFileContent);
if (buildMatchId != null) {
final String? androidPluginVersion =
buildMatchId.namedGroup(_versionGroupName);
logger.printTrace('$buildFile provides AGP version from plugin id: $androidPluginVersion');
return androidPluginVersion;
}
logger.printTrace(
"$buildFile doesn't provide an AGP version. Checking settings.");
File settingsFile = androidDirectory.childFile('settings.gradle');
if (!settingsFile.existsSync()) {
settingsFile = androidDirectory.childFile('settings.gradle.kts');
}
if (!settingsFile.existsSync()) {
logger.printTrace(
'Cannot find settings.gradle/settings.gradle.kts in $androidDirectory');
return null;
}
final String settingsFileContent = settingsFile.readAsStringSync();
final RegExpMatch? settingsMatch =
_androidGradlePluginRegExpFromId.firstMatch(settingsFileContent);
if (settingsMatch != null) {
final String? androidPluginVersion =
settingsMatch.namedGroup(_versionGroupName);
logger.printTrace(
'$settingsFile provides AGP version: $androidPluginVersion');
return androidPluginVersion;
}
logger.printTrace("$settingsFile doesn't provide an AGP version.");
return null;
}
String _formatParseWarning(String content) {
return 'Could not parse gradle version from: \n'
'$content \n'
'If there is a version please look for an existing bug '
'https://github.com/flutter/flutter/issues/'
' and if one does not exist file a new issue.';
}
// Validate that Gradle version and AGP are compatible with each other.
//
// Returns true if versions are compatible.
// Null Gradle version or AGP version returns false.
// If compatibility cannot be evaluated returns false.
// If versions are newer than the max known version a warning is logged and true
// returned.
//
// Source of truth found here:
// https://developer.android.com/studio/releases/gradle-plugin#updating-gradle
// AGP has a minimum version of gradle required but no max starting at
// AGP version 2.3.0+.
bool validateGradleAndAgp(Logger logger,
{required String? gradleV, required String? agpV}) {
const String oldestSupportedAgpVersion = '3.3.0';
const String oldestSupportedGradleVersion = '4.10.1';
if (gradleV == null || agpV == null) {
logger
.printTrace('Gradle version or AGP version unknown ($gradleV, $agpV).');
return false;
}
// First check if versions are too old.
if (isWithinVersionRange(agpV,
min: '0.0', max: oldestSupportedAgpVersion, inclusiveMax: false)) {
logger.printTrace('AGP Version: $agpV is too old.');
return false;
}
if (isWithinVersionRange(gradleV,
min: '0.0', max: oldestSupportedGradleVersion, inclusiveMax: false)) {
logger.printTrace('Gradle Version: $gradleV is too old.');
return false;
}
// Check highest supported version before checking unknown versions.
if (isWithinVersionRange(agpV, min: '8.0', max: maxKnownAndSupportedAgpVersion)) {
return isWithinVersionRange(gradleV,
min: '8.0', max: maxKnownAndSupportedGradleVersion);
}
// Check if versions are newer than the max known versions.
if (isWithinVersionRange(agpV,
min: maxKnownAndSupportedAgpVersion, max: '100.100')) {
// Assume versions we do not know about are valid but log.
final bool validGradle =
isWithinVersionRange(gradleV, min: '8.0', max: '100.00');
logger.printTrace('Newer than known AGP version ($agpV), gradle ($gradleV).'
'\n Treating as valid configuration.');
return validGradle;
}
// Begin Known Gradle <-> AGP validation.
// Max agp here is a made up version to contain all 7.4 changes.
if (isWithinVersionRange(agpV, min: '7.4', max: '7.5')) {
return isWithinVersionRange(gradleV,
min: '7.5', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(agpV,
min: '7.3', max: '7.4', inclusiveMax: false)) {
return isWithinVersionRange(gradleV,
min: '7.4', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(agpV,
min: '7.2', max: '7.3', inclusiveMax: false)) {
return isWithinVersionRange(gradleV,
min: '7.3.3', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(agpV,
min: '7.1', max: '7.2', inclusiveMax: false)) {
return isWithinVersionRange(gradleV,
min: '7.2', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(agpV,
min: '7.0', max: '7.1', inclusiveMax: false)) {
return isWithinVersionRange(gradleV,
min: '7.0', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(agpV,
min: '4.2.0', max: '7.0', inclusiveMax: false)) {
return isWithinVersionRange(gradleV,
min: '6.7.1', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(agpV,
min: '4.1.0', max: '4.2.0', inclusiveMax: false)) {
return isWithinVersionRange(gradleV,
min: '6.5', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(agpV,
min: '4.0.0', max: '4.1.0', inclusiveMax: false)) {
return isWithinVersionRange(gradleV,
min: '6.1.1', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(
agpV,
min: '3.6.0',
max: '3.6.4',
)) {
return isWithinVersionRange(gradleV,
min: '5.6.4', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(
agpV,
min: '3.5.0',
max: '3.5.4',
)) {
return isWithinVersionRange(gradleV,
min: '5.4.1', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(
agpV,
min: '3.4.0',
max: '3.4.3',
)) {
return isWithinVersionRange(gradleV,
min: '5.1.1', max: maxKnownAndSupportedGradleVersion);
}
if (isWithinVersionRange(
agpV,
min: '3.3.0',
max: '3.3.3',
)) {
return isWithinVersionRange(gradleV,
min: '4.10.1', max: maxKnownAndSupportedGradleVersion);
}
logger.printTrace('Unknown Gradle-Agp compatibility, $gradleV, $agpV');
return false;
}
/// Validate that the [javaVersion] and Gradle version are compatible with
/// each other.
///
/// Source of truth:
/// https://docs.gradle.org/current/userguide/compatibility.html#java
bool validateJavaAndGradle(Logger logger,
{required String? javaV, required String? gradleV}) {
// https://docs.gradle.org/current/userguide/compatibility.html#java
const String oldestSupportedJavaVersion = '1.8';
const String oldestDocumentedJavaGradleCompatibility = '2.0';
// Begin Java <-> Gradle validation.
if (javaV == null || gradleV == null) {
logger.printTrace(
'Java version or Gradle version unknown ($javaV, $gradleV).');
return false;
}
// First check if versions are too old.
if (isWithinVersionRange(javaV,
min: '1.1', max: oldestSupportedJavaVersion, inclusiveMax: false)) {
logger.printTrace('Java Version: $javaV is too old.');
return false;
}
if (isWithinVersionRange(gradleV,
min: '0.0', max: oldestDocumentedJavaGradleCompatibility, inclusiveMax: false)) {
logger.printTrace('Gradle Version: $gradleV is too old.');
return false;
}
// Check if versions are newer than the max supported versions.
if (isWithinVersionRange(
javaV,
min: oneMajorVersionHigherJavaVersion,
max: '100.100',
)) {
// Assume versions Java versions newer than [maxSupportedJavaVersion]
// required a higher gradle version.
final bool validGradle = isWithinVersionRange(gradleV,
min: maxKnownAndSupportedGradleVersion, max: '100.00');
logger.printWarning(
'Newer than known valid Java version ($javaV), gradle ($gradleV).'
'\n Treating as valid configuration.');
return validGradle;
}
// Begin known Java <-> Gradle evaluation.
for (final JavaGradleCompat data in _javaGradleCompatList) {
if (isWithinVersionRange(javaV, min: data.javaMin, max: data.javaMax, inclusiveMax: false)) {
return isWithinVersionRange(gradleV, min: data.gradleMin, max: data.gradleMax);
}
}
logger.printTrace('Unknown Java-Gradle compatibility $javaV, $gradleV');
return false;
}
/// Returns compatibility information for the valid range of Gradle versions for
/// the specified Java version.
///
/// Returns null when the tooling has not documented the compatible Gradle
/// versions for the Java version (either the version is too old or too new). If
/// this seems like a mistake, the caller may need to update the
/// [_javaGradleCompatList] detailing Java/Gradle compatibility.
JavaGradleCompat? getValidGradleVersionRangeForJavaVersion(
Logger logger, {
required String javaV,
}) {
for (final JavaGradleCompat data in _javaGradleCompatList) {
if (isWithinVersionRange(javaV, min: data.javaMin, max: data.javaMax, inclusiveMax: false)) {
return data;
}
}
logger.printTrace('Unable to determine valid Gradle version range for Java version $javaV.');
return null;
}
/// Validate that the specified Java and Android Gradle Plugin (AGP) versions are
/// compatible with each other.
///
/// Returns true when the specified Java and AGP versions are
/// definitely compatible; otherwise, false is assumed by default. In addition,
/// this will return false when either a null Java or AGP version is provided.
///
/// Source of truth are the AGP release notes:
/// https://developer.android.com/build/releases/gradle-plugin
bool validateJavaAndAgp(Logger logger,
{required String? javaV, required String? agpV}) {
if (javaV == null || agpV == null) {
logger.printTrace(
'Java version or AGP version unknown ($javaV, $agpV).');
return false;
}
// Check if AGP version is too old to perform validation.
if (isWithinVersionRange(agpV,
min: '1.0', max: oldestDocumentedJavaAgpCompatibilityVersion, inclusiveMax: false)) {
logger.printTrace('AGP Version: $agpV is too old to determine Java compatibility.');
return false;
}
if (isWithinVersionRange(agpV,
min: maxKnownAndSupportedAgpVersion, max: '100.100', inclusiveMin: false)) {
logger.printTrace('AGP Version: $agpV is too new to determine Java compatibility.');
return false;
}
// Begin known Java <-> AGP evaluation.
for (final JavaAgpCompat data in _javaAgpCompatList) {
if (isWithinVersionRange(agpV, min: data.agpMin, max: data.agpMax)) {
return isWithinVersionRange(javaV, min: data.javaMin, max: '100.100');
}
}
logger.printTrace('Unknown Java-AGP compatibility $javaV, $agpV');
return false;
}
/// Returns compatibility information concerning the minimum AGP
/// version for the specified Java version.
JavaAgpCompat? getMinimumAgpVersionForJavaVersion(Logger logger,
{required String javaV}) {
for (final JavaAgpCompat data in _javaAgpCompatList) {
if (isWithinVersionRange(javaV, min: data.javaMin, max: '100.100')) {
return data;
}
}
logger.printTrace('Unable to determine minimum AGP version for specified Java version.');
return null;
}
/// Returns valid Java range for specified Gradle and AGP versions.
///
/// Assumes that gradleV and agpV are compatible versions.
VersionRange getJavaVersionFor({required String gradleV, required String agpV}) {
// Find minimum Java version based on AGP compatibility.
String? minJavaVersion;
for (final JavaAgpCompat data in _javaAgpCompatList) {
if (isWithinVersionRange(agpV, min: data.agpMin, max: data.agpMax)) {
minJavaVersion = data.javaMin;
}
}
// Find maximum Java version based on Gradle compatibility.
String? maxJavaVersion;
for (final JavaGradleCompat data in _javaGradleCompatList.reversed) {
if (isWithinVersionRange(gradleV, min: data.gradleMin, max: maxKnownAndSupportedGradleVersion)) {
maxJavaVersion = data.javaMax;
}
}
return VersionRange(minJavaVersion, maxJavaVersion);
}
/// Returns the Gradle version that is required by the given Android Gradle plugin version
/// by picking the largest compatible version from
/// https://developer.android.com/studio/releases/gradle-plugin#updating-gradle
String getGradleVersionFor(String androidPluginVersion) {
final List<GradleForAgp> compatList = <GradleForAgp> [
GradleForAgp(agpMin: '1.0.0', agpMax: '1.1.3', minRequiredGradle: '2.3'),
GradleForAgp(agpMin: '1.2.0', agpMax: '1.3.1', minRequiredGradle: '2.9'),
GradleForAgp(agpMin: '1.5.0', agpMax: '1.5.0', minRequiredGradle: '2.2.1'),
GradleForAgp(agpMin: '2.0.0', agpMax: '2.1.2', minRequiredGradle: '2.13'),
GradleForAgp(agpMin: '2.1.3', agpMax: '2.2.3', minRequiredGradle: '2.14.1'),
GradleForAgp(agpMin: '2.3.0', agpMax: '2.9.9', minRequiredGradle: '3.3'),
GradleForAgp(agpMin: '3.0.0', agpMax: '3.0.9', minRequiredGradle: '4.1'),
GradleForAgp(agpMin: '3.1.0', agpMax: '3.1.9', minRequiredGradle: '4.4'),
GradleForAgp(agpMin: '3.2.0', agpMax: '3.2.1', minRequiredGradle: '4.6'),
GradleForAgp(agpMin: '3.3.0', agpMax: '3.3.2', minRequiredGradle: '4.10.2'),
GradleForAgp(agpMin: '3.4.0', agpMax: '3.5.0', minRequiredGradle: '5.6.2'),
GradleForAgp(agpMin: '4.0.0', agpMax: '4.1.0', minRequiredGradle: '6.7'),
// 7.5 is a made up value to include everything through 7.4.*
GradleForAgp(agpMin: '7.0.0', agpMax: '7.5', minRequiredGradle: '7.5'),
GradleForAgp(agpMin: '7.5.0', agpMax: '100.100', minRequiredGradle: '8.0'),
// Assume if AGP is newer than this code know about return the highest gradle
// version we know about.
GradleForAgp(agpMin: maxKnownAgpVersion, agpMax: maxKnownAgpVersion, minRequiredGradle: maxKnownAndSupportedGradleVersion),
];
for (final GradleForAgp data in compatList) {
if (isWithinVersionRange(androidPluginVersion, min: data.agpMin, max: data.agpMax)) {
return data.minRequiredGradle;
}
}
if (isWithinVersionRange(androidPluginVersion, min: maxKnownAgpVersion, max: '100.100')) {
return maxKnownAndSupportedGradleVersion;
}
throwToolExit('Unsupported Android Plugin version: $androidPluginVersion.');
}
/// Overwrite local.properties in the specified Flutter project's Android
/// sub-project, if needed.
///
/// If [requireAndroidSdk] is true (the default) and no Android SDK is found,
/// this will fail with a [ToolExit].
void updateLocalProperties({
required FlutterProject project,
BuildInfo? buildInfo,
bool requireAndroidSdk = true,
}) {
if (requireAndroidSdk && globals.androidSdk == null) {
exitWithNoSdkMessage();
}
final File localProperties = project.android.localPropertiesFile;
bool changed = false;
SettingsFile settings;
if (localProperties.existsSync()) {
settings = SettingsFile.parseFromFile(localProperties);
} else {
settings = SettingsFile();
changed = true;
}
void changeIfNecessary(String key, String? value) {
if (settings.values[key] == value) {
return;
}
if (value == null) {
settings.values.remove(key);
} else {
settings.values[key] = value;
}
changed = true;
}
final AndroidSdk? androidSdk = globals.androidSdk;
if (androidSdk != null) {
changeIfNecessary('sdk.dir', globals.fsUtils.escapePath(androidSdk.directory.path));
}
changeIfNecessary('flutter.sdk', globals.fsUtils.escapePath(Cache.flutterRoot!));
if (buildInfo != null) {
changeIfNecessary('flutter.buildMode', buildInfo.modeName);
final String? buildName = validatedBuildNameForPlatform(
TargetPlatform.android_arm,
buildInfo.buildName ?? project.manifest.buildName,
globals.logger,
);
changeIfNecessary('flutter.versionName', buildName);
final String? buildNumber = validatedBuildNumberForPlatform(
TargetPlatform.android_arm,
buildInfo.buildNumber ?? project.manifest.buildNumber,
globals.logger,
);
changeIfNecessary('flutter.versionCode', buildNumber);
}
if (changed) {
settings.writeContents(localProperties);
}
}
/// Writes standard Android local properties to the specified [properties] file.
///
/// Writes the path to the Android SDK, if known.
void writeLocalProperties(File properties) {
final SettingsFile settings = SettingsFile();
final AndroidSdk? androidSdk = globals.androidSdk;
if (androidSdk != null) {
settings.values['sdk.dir'] = globals.fsUtils.escapePath(androidSdk.directory.path);
}
settings.writeContents(properties);
}
void exitWithNoSdkMessage() {
BuildEvent('unsupported-project',
type: 'gradle',
eventError: 'android-sdk-not-found',
flutterUsage: globals.flutterUsage)
.send();
globals.analytics.send(Event.flutterBuildInfo(
label: 'unsupported-project',
buildType: 'gradle',
error: 'android-sdk-not-found',
));
throwToolExit('${globals.logger.terminal.warningMark} No Android SDK found. '
'Try setting the ANDROID_HOME environment variable.');
}
// Data class to hold normal/defined Java <-> Gradle compatibility criteria.
//
// The [javaMax] is exclusive in terms of supporting the noted [gradleMin],
// whereas [javaMin] is inclusive.
@immutable
class JavaGradleCompat {
const JavaGradleCompat({
required this.javaMin,
required this.javaMax,
required this.gradleMin,
required this.gradleMax,
});
final String javaMin;
final String javaMax;
final String gradleMin;
final String gradleMax;
@override
bool operator ==(Object other) =>
other is JavaGradleCompat &&
other.javaMin == javaMin &&
other.javaMax == javaMax &&
other.gradleMin == gradleMin &&
other.gradleMax == gradleMax;
@override
int get hashCode => Object.hash(javaMin, javaMax, gradleMin, gradleMax);
}
// Data class to hold defined Java <-> AGP compatibility criteria.
//
// The [agpMin] and [agpMax] are inclusive in terms of having the
// noted [javaMin] and [javaDefault] versions.
@immutable
class JavaAgpCompat {
const JavaAgpCompat({
required this.javaMin,
required this.javaDefault,
required this.agpMin,
required this.agpMax,
});
final String javaMin;
final String javaDefault;
final String agpMin;
final String agpMax;
@override
bool operator ==(Object other) =>
other is JavaAgpCompat &&
other.javaMin == javaMin &&
other.javaDefault == javaDefault &&
other.agpMin == agpMin &&
other.agpMax == agpMax;
@override
int get hashCode => Object.hash(javaMin, javaDefault, agpMin, agpMax);
}
class GradleForAgp {
GradleForAgp({
required this.agpMin,
required this.agpMax,
required this.minRequiredGradle,
});
final String agpMin;
final String agpMax;
final String minRequiredGradle;
}
// Returns gradlew file name based on the platform.
String getGradlewFileName(Platform platform) {
if (platform.isWindows) {
return 'gradlew.bat';
} else {
return 'gradlew';
}
}
/// List of compatible Java/Gradle versions.
///
/// Should be updated when a new version of Java is supported by a new version
/// of Gradle, as https://docs.gradle.org/current/userguide/compatibility.html
/// details.
List<JavaGradleCompat> _javaGradleCompatList = const <JavaGradleCompat>[
JavaGradleCompat(
javaMin: '19',
javaMax: '20',
gradleMin: '7.6',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '18',
javaMax: '19',
gradleMin: '7.5',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '17',
javaMax: '18',
gradleMin: '7.3',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '16',
javaMax: '17',
gradleMin: '7.0',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '15',
javaMax: '16',
gradleMin: '6.7',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '14',
javaMax: '15',
gradleMin: '6.3',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '13',
javaMax: '14',
gradleMin: '6.0',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '12',
javaMax: '13',
gradleMin: '5.4',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '11',
javaMax: '12',
gradleMin: '5.0',
gradleMax: maxKnownAndSupportedGradleVersion,
),
// 1.11 is a made up java version to cover everything in 1.10.*
JavaGradleCompat(
javaMin: '1.10',
javaMax: '1.11',
gradleMin: '4.7',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '1.9',
javaMax: '1.10',
gradleMin: '4.3',
gradleMax: maxKnownAndSupportedGradleVersion,
),
JavaGradleCompat(
javaMin: '1.8',
javaMax: '1.9',
gradleMin: '2.0',
gradleMax: maxKnownAndSupportedGradleVersion,
),
];
// List of compatible Java/AGP versions, where agpMax versions are inclusive.
//
// Should be updated whenever a new version of AGP is released as
// https://developer.android.com/build/releases/gradle-plugin details.
List<JavaAgpCompat> _javaAgpCompatList = const <JavaAgpCompat>[
JavaAgpCompat(
javaMin: '17',
javaDefault: '17',
agpMin: '8.0',
agpMax: maxKnownAndSupportedAgpVersion,
),
JavaAgpCompat(
javaMin: '11',
javaDefault: '11',
agpMin: '7.0',
agpMax: '7.4',
),
JavaAgpCompat(
// You may use JDK 1.7 with AGP 4.2, but we treat 1.8 as the default since
// it is used by default for this AGP version and lower versions of Java
// are deprecated for executing Gradle.
javaMin: '1.8',
javaDefault: '1.8',
agpMin: '4.2',
agpMax: '4.2',
),
];
| flutter/packages/flutter_tools/lib/src/android/gradle_utils.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/android/gradle_utils.dart",
"repo_id": "flutter",
"token_count": 12559
} | 770 |
// 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:dds/dds.dart' as dds;
import 'package:meta/meta.dart';
import 'common.dart';
import 'context.dart';
import 'io.dart' as io;
import 'logger.dart';
// TODO(fujino): This should be direct injected, rather than mutable global state.
@visibleForTesting
Future<dds.DartDevelopmentService> Function(
Uri remoteVmServiceUri, {
bool enableAuthCodes,
bool ipv6,
Uri? serviceUri,
List<String> cachedUserTags,
dds.UriConverter? uriConverter,
}) ddsLauncherCallback = dds.DartDevelopmentService.startDartDevelopmentService;
/// Helper class to launch a [dds.DartDevelopmentService]. Allows for us to
/// mock out this functionality for testing purposes.
class DartDevelopmentService {
dds.DartDevelopmentService? _ddsInstance;
Uri? get uri => _ddsInstance?.uri ?? _existingDdsUri;
Uri? _existingDdsUri;
Future<void> get done => _completer.future;
final Completer<void> _completer = Completer<void>();
Future<void> startDartDevelopmentService(
Uri vmServiceUri, {
required Logger logger,
int? hostPort,
bool? ipv6,
bool? disableServiceAuthCodes,
bool cacheStartupProfile = false,
}) async {
final Uri ddsUri = Uri(
scheme: 'http',
host: ((ipv6 ?? false) ? io.InternetAddress.loopbackIPv6 : io.InternetAddress.loopbackIPv4).host,
port: hostPort ?? 0,
);
logger.printTrace(
'Launching a Dart Developer Service (DDS) instance at $ddsUri, '
'connecting to VM service at $vmServiceUri.',
);
try {
_ddsInstance = await ddsLauncherCallback(
vmServiceUri,
serviceUri: ddsUri,
enableAuthCodes: disableServiceAuthCodes != true,
ipv6: ipv6 ?? false,
// Enables caching of CPU samples collected during application startup.
cachedUserTags: cacheStartupProfile ? const <String>['AppStartUp'] : const <String>[],
uriConverter: context.get<dds.UriConverter>(),
);
unawaited(_ddsInstance?.done.whenComplete(() {
if (!_completer.isCompleted) {
_completer.complete();
}
}));
logger.printTrace('DDS is listening at ${_ddsInstance?.uri}.');
} on dds.DartDevelopmentServiceException catch (e) {
logger.printTrace('Warning: Failed to start DDS: ${e.message}');
if (e.errorCode == dds.DartDevelopmentServiceException.existingDdsInstanceError) {
try {
// First try to use the new field to avoid parsing from the message.
_existingDdsUri = e is dds.ExistingDartDevelopmentServiceException ? e.ddsUri : null;
// Otherwise, fall back to parsing from the exception (old DDS).
// This is not completely reliable which is why the new field above
// was added.
if (_existingDdsUri == null) {
String parsedUrl = e.message.split(' ').firstWhere((String e) => e.startsWith('http'));
// Trim trailing full stops from the message.
// https://github.com/flutter/flutter/issues/118609.
if (parsedUrl.endsWith('.')) {
parsedUrl = parsedUrl.substring(0, parsedUrl.length - 1);
}
_existingDdsUri ??= Uri.parse(parsedUrl);
}
} on StateError {
if (e.message.contains('Existing VM service clients prevent DDS from taking control.')) {
throwToolExit('${e.message}. Please rebuild your application with a newer version of Flutter.');
}
logger.printError(
'DDS has failed to start and there is not an existing DDS instance '
'available to connect to. Please file an issue at https://github.com/flutter/flutter/issues '
'with the following error message:\n\n ${e.message}.'
);
// DDS was unable to start for an unknown reason. Raise a StateError
// so it can be reported by the crash reporter.
throw StateError(e.message);
}
}
if (!_completer.isCompleted) {
_completer.complete();
}
rethrow;
}
}
Future<void> shutdown() async => _ddsInstance?.shutdown();
void setExternalDevToolsUri(Uri uri) {
_ddsInstance?.setExternalDevToolsUri(uri);
}
}
| flutter/packages/flutter_tools/lib/src/base/dds.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/dds.dart",
"repo_id": "flutter",
"token_count": 1738
} | 771 |
// 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 '../convert.dart';
import '../features.dart';
import 'io.dart' as io;
import 'logger.dart';
import 'platform.dart';
enum TerminalColor {
red,
green,
blue,
cyan,
yellow,
magenta,
grey,
}
/// A class that contains the context settings for command text output to the
/// console.
class OutputPreferences {
OutputPreferences({
bool? wrapText,
int? wrapColumn,
bool? showColor,
io.Stdio? stdio,
}) : _stdio = stdio,
wrapText = wrapText ?? stdio?.hasTerminal ?? false,
_overrideWrapColumn = wrapColumn,
showColor = showColor ?? false;
/// A version of this class for use in tests.
OutputPreferences.test({this.wrapText = false, int wrapColumn = kDefaultTerminalColumns, this.showColor = false})
: _overrideWrapColumn = wrapColumn, _stdio = null;
final io.Stdio? _stdio;
/// If [wrapText] is true, then any text sent to the context's [Logger]
/// instance (e.g. from the [printError] or [printStatus] functions) will be
/// wrapped (newlines added between words) to be no longer than the
/// [wrapColumn] specifies. Defaults to true if there is a terminal. To
/// determine if there's a terminal, [OutputPreferences] asks the context's
/// stdio.
final bool wrapText;
/// The terminal width used by the [wrapText] function if there is no terminal
/// attached to [io.Stdio], --wrap is on, and --wrap-columns was not specified.
static const int kDefaultTerminalColumns = 100;
/// The column at which output sent to the context's [Logger] instance
/// (e.g. from the [printError] or [printStatus] functions) will be wrapped.
/// Ignored if [wrapText] is false. Defaults to the width of the output
/// terminal, or to [kDefaultTerminalColumns] if not writing to a terminal.
final int? _overrideWrapColumn;
int get wrapColumn {
return _overrideWrapColumn ?? _stdio?.terminalColumns ?? kDefaultTerminalColumns;
}
/// Whether or not to output ANSI color codes when writing to the output
/// terminal. Defaults to whatever [platform.stdoutSupportsAnsi] says if
/// writing to a terminal, and false otherwise.
final bool showColor;
@override
String toString() {
return '$runtimeType[wrapText: $wrapText, wrapColumn: $wrapColumn, showColor: $showColor]';
}
}
/// The command line terminal, if available.
// TODO(ianh): merge this with AnsiTerminal, the abstraction isn't giving us anything.
abstract class Terminal {
/// Create a new test [Terminal].
///
/// If not specified, [supportsColor] defaults to `false`.
factory Terminal.test({bool supportsColor, bool supportsEmoji}) = _TestTerminal;
/// Whether the current terminal supports color escape codes.
///
/// Check [isCliAnimationEnabled] as well before using `\r` or ANSI sequences
/// to perform animations.
bool get supportsColor;
/// Whether animations should be used in the output.
bool get isCliAnimationEnabled;
/// Configures isCliAnimationEnabled based on a [FeatureFlags] object.
void applyFeatureFlags(FeatureFlags flags);
/// Whether the current terminal can display emoji.
bool get supportsEmoji;
/// When we have a choice of styles (e.g. animated spinners), this selects the
/// style to use.
int get preferredStyle;
/// Whether we are interacting with the flutter tool via the terminal.
///
/// If not set, defaults to false.
bool get usesTerminalUi;
set usesTerminalUi(bool value);
/// Whether there is a terminal attached to stdin.
///
/// If true, this usually indicates that a user is using the CLI as
/// opposed to using an IDE. This can be used to determine
/// whether it is appropriate to show a terminal prompt,
/// or whether an automatic selection should be made instead.
bool get stdinHasTerminal;
/// Warning mark to use in stdout or stderr.
String get warningMark;
/// Success mark to use in stdout.
String get successMark;
String bolden(String message);
String color(String message, TerminalColor color);
String clearScreen();
bool get singleCharMode;
set singleCharMode(bool value);
/// Return keystrokes from the console.
///
/// This is a single-subscription stream. This stream may be closed before
/// the application exits.
///
/// Useful when the console is in [singleCharMode].
Stream<String> get keystrokes;
/// Prompts the user to input a character within a given list. Re-prompts if
/// entered character is not in the list.
///
/// The `prompt`, if non-null, is the text displayed prior to waiting for user
/// input each time. If `prompt` is non-null and `displayAcceptedCharacters`
/// is true, the accepted keys are printed next to the `prompt`.
///
/// The returned value is the user's input; if `defaultChoiceIndex` is not
/// null, and the user presses enter without any other input, the return value
/// will be the character in `acceptedCharacters` at the index given by
/// `defaultChoiceIndex`.
///
/// The accepted characters must be a String with a length of 1, excluding any
/// whitespace characters such as `\t`, `\n`, or ` `.
///
/// If [usesTerminalUi] is false, throws a [StateError].
Future<String> promptForCharInput(
List<String> acceptedCharacters, {
required Logger logger,
String? prompt,
int? defaultChoiceIndex,
bool displayAcceptedCharacters = true,
});
}
class AnsiTerminal implements Terminal {
AnsiTerminal({
required io.Stdio stdio,
required Platform platform,
DateTime? now, // Time used to determine preferredStyle. Defaults to 0001-01-01 00:00.
bool defaultCliAnimationEnabled = true,
})
: _stdio = stdio,
_platform = platform,
_now = now ?? DateTime(1),
_isCliAnimationEnabled = defaultCliAnimationEnabled;
final io.Stdio _stdio;
final Platform _platform;
final DateTime _now;
static const String bold = '\u001B[1m';
static const String resetAll = '\u001B[0m';
static const String resetColor = '\u001B[39m';
static const String resetBold = '\u001B[22m';
static const String clear = '\u001B[2J\u001B[H';
static const String red = '\u001b[31m';
static const String green = '\u001b[32m';
static const String blue = '\u001b[34m';
static const String cyan = '\u001b[36m';
static const String magenta = '\u001b[35m';
static const String yellow = '\u001b[33m';
static const String grey = '\u001b[90m';
// Moves cursor up 1 line.
static const String cursorUpLineCode = '\u001b[1A';
// Moves cursor to the beginning of the line.
static const String cursorBeginningOfLineCode = '\u001b[1G';
// Clear the entire line, cursor position does not change.
static const String clearEntireLineCode = '\u001b[2K';
static const Map<TerminalColor, String> _colorMap = <TerminalColor, String>{
TerminalColor.red: red,
TerminalColor.green: green,
TerminalColor.blue: blue,
TerminalColor.cyan: cyan,
TerminalColor.magenta: magenta,
TerminalColor.yellow: yellow,
TerminalColor.grey: grey,
};
static String colorCode(TerminalColor color) => _colorMap[color]!;
@override
bool get supportsColor => _platform.stdoutSupportsAnsi;
@override
bool get isCliAnimationEnabled => _isCliAnimationEnabled;
bool _isCliAnimationEnabled;
@override
void applyFeatureFlags(FeatureFlags flags) {
_isCliAnimationEnabled = flags.isCliAnimationEnabled;
}
// Assume unicode emojis are supported when not on Windows.
// If we are on Windows, unicode emojis are supported in Windows Terminal,
// which sets the WT_SESSION environment variable. See:
// https://github.com/microsoft/terminal/blob/master/doc/user-docs/index.md#tips-and-tricks
@override
bool get supportsEmoji => !_platform.isWindows
|| _platform.environment.containsKey('WT_SESSION');
@override
int get preferredStyle {
const int workdays = DateTime.friday;
if (_now.weekday <= workdays) {
return _now.weekday - 1;
}
return _now.hour + workdays;
}
final RegExp _boldControls = RegExp(
'(${RegExp.escape(resetBold)}|${RegExp.escape(bold)})',
);
@override
bool usesTerminalUi = false;
@override
String get warningMark {
return bolden(color('[!]', TerminalColor.red));
}
@override
String get successMark {
return bolden(color('✓', TerminalColor.green));
}
@override
String bolden(String message) {
if (!supportsColor || message.isEmpty) {
return message;
}
final StringBuffer buffer = StringBuffer();
for (String line in message.split('\n')) {
// If there were bolds or resetBolds in the string before, then nuke them:
// they're redundant. This prevents previously embedded resets from
// stopping the boldness.
line = line.replaceAll(_boldControls, '');
buffer.writeln('$bold$line$resetBold');
}
final String result = buffer.toString();
// avoid introducing a new newline to the emboldened text
return (!message.endsWith('\n') && result.endsWith('\n'))
? result.substring(0, result.length - 1)
: result;
}
@override
String color(String message, TerminalColor color) {
if (!supportsColor || message.isEmpty) {
return message;
}
final StringBuffer buffer = StringBuffer();
final String colorCodes = _colorMap[color]!;
for (String line in message.split('\n')) {
// If there were resets in the string before, then keep them, but
// restart the color right after. This prevents embedded resets from
// stopping the colors, and allows nesting of colors.
line = line.replaceAll(resetColor, '$resetColor$colorCodes');
buffer.writeln('$colorCodes$line$resetColor');
}
final String result = buffer.toString();
// avoid introducing a new newline to the colored text
return (!message.endsWith('\n') && result.endsWith('\n'))
? result.substring(0, result.length - 1)
: result;
}
@override
String clearScreen() => supportsColor && isCliAnimationEnabled ? clear : '\n\n';
/// Returns ANSI codes to clear [numberOfLines] lines starting with the line
/// the cursor is on.
///
/// If the terminal does not support ANSI codes, returns an empty string.
String clearLines(int numberOfLines) {
if (!supportsColor || !isCliAnimationEnabled) {
return '';
}
return cursorBeginningOfLineCode +
clearEntireLineCode +
(cursorUpLineCode + clearEntireLineCode) * (numberOfLines - 1);
}
@override
bool get singleCharMode {
if (!_stdio.stdinHasTerminal) {
return false;
}
final io.Stdin stdin = _stdio.stdin as io.Stdin;
return stdin.lineMode && stdin.echoMode;
}
@override
set singleCharMode(bool value) {
if (!_stdio.stdinHasTerminal) {
return;
}
final io.Stdin stdin = _stdio.stdin as io.Stdin;
try {
// The order of setting lineMode and echoMode is important on Windows.
if (value) {
stdin.echoMode = false;
stdin.lineMode = false;
} else {
stdin.lineMode = true;
stdin.echoMode = true;
}
} on io.StdinException {
// If the pipe to STDIN has been closed it's probably because the
// terminal has been closed, and there is nothing actionable to do here.
}
}
@override
bool get stdinHasTerminal => _stdio.stdinHasTerminal;
Stream<String>? _broadcastStdInString;
@override
Stream<String> get keystrokes {
return _broadcastStdInString ??= _stdio.stdin.transform<String>(const AsciiDecoder(allowInvalid: true)).asBroadcastStream();
}
@override
Future<String> promptForCharInput(
List<String> acceptedCharacters, {
required Logger logger,
String? prompt,
int? defaultChoiceIndex,
bool displayAcceptedCharacters = true,
}) async {
assert(acceptedCharacters.isNotEmpty);
assert(prompt == null || prompt.isNotEmpty);
if (!usesTerminalUi) {
throw StateError('cannot prompt without a terminal ui');
}
List<String> charactersToDisplay = acceptedCharacters;
if (defaultChoiceIndex != null) {
assert(defaultChoiceIndex >= 0 && defaultChoiceIndex < acceptedCharacters.length);
charactersToDisplay = List<String>.of(charactersToDisplay);
charactersToDisplay[defaultChoiceIndex] = bolden(charactersToDisplay[defaultChoiceIndex]);
acceptedCharacters.add('');
}
String? choice;
singleCharMode = true;
while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) {
if (prompt != null) {
logger.printStatus(prompt, emphasis: true, newline: false);
if (displayAcceptedCharacters) {
logger.printStatus(' [${charactersToDisplay.join("|")}]', newline: false);
}
// prompt ends with ': '
logger.printStatus(': ', emphasis: true, newline: false);
}
choice = (await keystrokes.first).trim();
logger.printStatus(choice);
}
singleCharMode = false;
if (defaultChoiceIndex != null && choice == '') {
choice = acceptedCharacters[defaultChoiceIndex];
}
return choice;
}
}
class _TestTerminal implements Terminal {
_TestTerminal({this.supportsColor = false, this.supportsEmoji = false});
@override
bool usesTerminalUi = false;
@override
String bolden(String message) => message;
@override
String clearScreen() => '\n\n';
@override
String color(String message, TerminalColor color) => message;
@override
Stream<String> get keystrokes => const Stream<String>.empty();
@override
Future<String> promptForCharInput(List<String> acceptedCharacters, {
required Logger logger,
String? prompt,
int? defaultChoiceIndex,
bool displayAcceptedCharacters = true,
}) {
throw UnsupportedError('promptForCharInput not supported in the test terminal.');
}
@override
bool get singleCharMode => false;
@override
set singleCharMode(bool value) { }
@override
final bool supportsColor;
@override
bool get isCliAnimationEnabled => supportsColor && _isCliAnimationEnabled;
bool _isCliAnimationEnabled = true;
@override
void applyFeatureFlags(FeatureFlags flags) {
_isCliAnimationEnabled = flags.isCliAnimationEnabled;
}
@override
final bool supportsEmoji;
@override
int get preferredStyle => 0;
@override
bool get stdinHasTerminal => false;
@override
String get successMark => '✓';
@override
String get warningMark => '[!]';
}
| flutter/packages/flutter_tools/lib/src/base/terminal.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/terminal.dart",
"repo_id": "flutter",
"token_count": 4760
} | 772 |
// 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:package_config/package_config.dart';
import '../../artifacts.dart';
import '../../base/build.dart';
import '../../base/common.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../build_info.dart';
import '../../compile.dart';
import '../../dart/package_map.dart';
import '../../globals.dart' as globals show xcode;
import '../build_system.dart';
import '../depfile.dart';
import '../exceptions.dart';
import '../tools/shader_compiler.dart';
import 'assets.dart';
import 'dart_plugin_registrant.dart';
import 'icon_tree_shaker.dart';
import 'localizations.dart';
import 'native_assets.dart';
/// Copies the pre-built flutter bundle.
// This is a one-off rule for implementing build bundle in terms of assemble.
class CopyFlutterBundle extends Target {
const CopyFlutterBundle();
@override
String get name => 'copy_flutter_bundle';
@override
List<Source> get inputs => const <Source>[
Source.artifact(Artifact.vmSnapshotData, mode: BuildMode.debug),
Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug),
Source.pattern('{BUILD_DIR}/app.dill'),
...IconTreeShaker.inputs,
...ShaderCompiler.inputs,
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{OUTPUT_DIR}/vm_snapshot_data'),
Source.pattern('{OUTPUT_DIR}/isolate_snapshot_data'),
Source.pattern('{OUTPUT_DIR}/kernel_blob.bin'),
];
@override
List<String> get depfiles => <String>[
'flutter_assets.d',
];
@override
Future<void> build(Environment environment) async {
final String? buildModeEnvironment = environment.defines[kBuildMode];
if (buildModeEnvironment == null) {
throw MissingDefineException(kBuildMode, 'copy_flutter_bundle');
}
final String? flavor = environment.defines[kFlavor];
final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
environment.outputDir.createSync(recursive: true);
// Only copy the prebuilt runtimes and kernel blob in debug mode.
if (buildMode == BuildMode.debug) {
final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
environment.buildDir.childFile('app.dill')
.copySync(environment.outputDir.childFile('kernel_blob.bin').path);
environment.fileSystem.file(vmSnapshotData)
.copySync(environment.outputDir.childFile('vm_snapshot_data').path);
environment.fileSystem.file(isolateSnapshotData)
.copySync(environment.outputDir.childFile('isolate_snapshot_data').path);
}
final Depfile assetDepfile = await copyAssets(
environment,
environment.outputDir,
targetPlatform: TargetPlatform.android,
buildMode: buildMode,
flavor: flavor,
);
environment.depFileService.writeToFile(
assetDepfile,
environment.buildDir.childFile('flutter_assets.d'),
);
}
@override
List<Target> get dependencies => const <Target>[
KernelSnapshot(),
];
}
/// Copies the pre-built flutter bundle for release mode.
class ReleaseCopyFlutterBundle extends CopyFlutterBundle {
const ReleaseCopyFlutterBundle();
@override
String get name => 'release_flutter_bundle';
@override
List<Source> get inputs => const <Source>[];
@override
List<Source> get outputs => const <Source>[];
@override
List<String> get depfiles => const <String>[
'flutter_assets.d',
];
@override
List<Target> get dependencies => const <Target>[];
}
/// Generate a snapshot of the dart code used in the program.
///
/// This target depends on the `.dart_tool/package_config.json` file
/// even though it is not listed as an input. Pub inserts a timestamp into
/// the file which causes unnecessary rebuilds, so instead a subset of the contents
/// are used an input instead.
class KernelSnapshot extends Target {
const KernelSnapshot();
@override
String get name => 'kernel_snapshot';
@override
List<Source> get inputs => const <Source>[
Source.pattern('{BUILD_DIR}/native_assets.yaml'),
Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'),
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
Source.artifact(Artifact.platformKernelDill),
Source.artifact(Artifact.engineDartBinary),
Source.artifact(Artifact.engineDartAotRuntime),
Source.artifact(Artifact.frontendServerSnapshotForEngineDartSdk),
];
@override
List<Source> get outputs => const <Source>[];
@override
List<String> get depfiles => <String>[
'kernel_snapshot.d',
];
@override
List<Target> get dependencies => const <Target>[
NativeAssets(),
GenerateLocalizationsTarget(),
DartPluginRegistrantTarget(),
];
@override
Future<void> build(Environment environment) async {
final KernelCompiler compiler = KernelCompiler(
fileSystem: environment.fileSystem,
logger: environment.logger,
processManager: environment.processManager,
artifacts: environment.artifacts,
fileSystemRoots: <String>[],
);
final String? buildModeEnvironment = environment.defines[kBuildMode];
if (buildModeEnvironment == null) {
throw MissingDefineException(kBuildMode, 'kernel_snapshot');
}
final String? targetPlatformEnvironment = environment.defines[kTargetPlatform];
if (targetPlatformEnvironment == null) {
throw MissingDefineException(kTargetPlatform, 'kernel_snapshot');
}
final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
final String targetFile = environment.defines[kTargetFile] ?? environment.fileSystem.path.join('lib', 'main.dart');
final File packagesFile = environment.projectDir
.childDirectory('.dart_tool')
.childFile('package_config.json');
final String targetFileAbsolute = environment.fileSystem.file(targetFile).absolute.path;
// everything besides 'false' is considered to be enabled.
final bool trackWidgetCreation = environment.defines[kTrackWidgetCreation] != 'false';
final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment);
// This configuration is all optional.
final String? frontendServerStarterPath = environment.defines[kFrontendServerStarterPath];
final List<String> extraFrontEndOptions = decodeCommaSeparated(environment.defines, kExtraFrontEndOptions);
final List<String>? fileSystemRoots = environment.defines[kFileSystemRoots]?.split(',');
final String? fileSystemScheme = environment.defines[kFileSystemScheme];
final File nativeAssetsFile = environment.buildDir.childFile('native_assets.yaml');
final String nativeAssets = nativeAssetsFile.path;
if (!await nativeAssetsFile.exists()) {
throwToolExit("$nativeAssets doesn't exist.");
}
environment.logger.printTrace('Embedding native assets mapping $nativeAssets in kernel.');
TargetModel targetModel = TargetModel.flutter;
if (targetPlatform == TargetPlatform.fuchsia_x64 ||
targetPlatform == TargetPlatform.fuchsia_arm64) {
targetModel = TargetModel.flutterRunner;
}
// Force linking of the platform for desktop embedder targets since these
// do not correctly load the core snapshots in debug mode.
// See https://github.com/flutter/flutter/issues/44724
final bool forceLinkPlatform;
switch (targetPlatform) {
case TargetPlatform.darwin:
case TargetPlatform.windows_x64:
case TargetPlatform.windows_arm64:
case TargetPlatform.linux_x64:
forceLinkPlatform = true;
case TargetPlatform.android:
case TargetPlatform.android_arm:
case TargetPlatform.android_arm64:
case TargetPlatform.android_x64:
case TargetPlatform.android_x86:
case TargetPlatform.fuchsia_arm64:
case TargetPlatform.fuchsia_x64:
case TargetPlatform.ios:
case TargetPlatform.linux_arm64:
case TargetPlatform.tester:
case TargetPlatform.web_javascript:
forceLinkPlatform = false;
}
final String? targetOS = switch (targetPlatform) {
TargetPlatform.fuchsia_arm64 || TargetPlatform.fuchsia_x64 => 'fuchsia',
TargetPlatform.android ||
TargetPlatform.android_arm ||
TargetPlatform.android_arm64 ||
TargetPlatform.android_x64 ||
TargetPlatform.android_x86 =>
'android',
TargetPlatform.darwin => 'macos',
TargetPlatform.ios => 'ios',
TargetPlatform.linux_arm64 || TargetPlatform.linux_x64 => 'linux',
TargetPlatform.windows_arm64 || TargetPlatform.windows_x64 => 'windows',
TargetPlatform.tester || TargetPlatform.web_javascript => null,
};
final PackageConfig packageConfig = await loadPackageConfigWithLogging(
packagesFile,
logger: environment.logger,
);
final CompilerOutput? output = await compiler.compile(
sdkRoot: environment.artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: targetPlatform,
mode: buildMode,
),
aot: buildMode.isPrecompiled,
buildMode: buildMode,
trackWidgetCreation: trackWidgetCreation && buildMode != BuildMode.release,
targetModel: targetModel,
outputFilePath: environment.buildDir.childFile('app.dill').path,
initializeFromDill: buildMode.isPrecompiled ? null :
environment.buildDir.childFile('app.dill').path,
packagesPath: packagesFile.path,
linkPlatformKernelIn: forceLinkPlatform || buildMode.isPrecompiled,
mainPath: targetFileAbsolute,
depFilePath: environment.buildDir.childFile('kernel_snapshot.d').path,
frontendServerStarterPath: frontendServerStarterPath,
extraFrontEndOptions: extraFrontEndOptions,
fileSystemRoots: fileSystemRoots,
fileSystemScheme: fileSystemScheme,
dartDefines: decodeDartDefines(environment.defines, kDartDefines),
packageConfig: packageConfig,
buildDir: environment.buildDir,
targetOS: targetOS,
checkDartPluginRegistry: environment.generateDartPluginRegistry,
nativeAssets: nativeAssets,
);
if (output == null || output.errorCount != 0) {
throw Exception();
}
}
}
/// Supports compiling a dart kernel file to an ELF binary.
abstract class AotElfBase extends Target {
const AotElfBase();
@override
String get analyticsName => 'android_aot';
@override
Future<void> build(Environment environment) async {
final AOTSnapshotter snapshotter = AOTSnapshotter(
fileSystem: environment.fileSystem,
logger: environment.logger,
xcode: globals.xcode!,
processManager: environment.processManager,
artifacts: environment.artifacts,
);
final String outputPath = environment.buildDir.path;
final String? buildModeEnvironment = environment.defines[kBuildMode];
if (buildModeEnvironment == null) {
throw MissingDefineException(kBuildMode, 'aot_elf');
}
final String? targetPlatformEnvironment = environment.defines[kTargetPlatform];
if (targetPlatformEnvironment == null) {
throw MissingDefineException(kTargetPlatform, 'aot_elf');
}
final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions);
final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment);
final String? splitDebugInfo = environment.defines[kSplitDebugInfo];
final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
final String? codeSizeDirectory = environment.defines[kCodeSizeDirectory];
if (codeSizeDirectory != null) {
final File codeSizeFile = environment.fileSystem
.directory(codeSizeDirectory)
.childFile('snapshot.${environment.defines[kTargetPlatform]}.json');
final File precompilerTraceFile = environment.fileSystem
.directory(codeSizeDirectory)
.childFile('trace.${environment.defines[kTargetPlatform]}.json');
extraGenSnapshotOptions.add('--write-v8-snapshot-profile-to=${codeSizeFile.path}');
extraGenSnapshotOptions.add('--trace-precompiler-to=${precompilerTraceFile.path}');
}
final int snapshotExitCode = await snapshotter.build(
platform: targetPlatform,
buildMode: buildMode,
mainPath: environment.buildDir.childFile('app.dill').path,
outputPath: outputPath,
extraGenSnapshotOptions: extraGenSnapshotOptions,
splitDebugInfo: splitDebugInfo,
dartObfuscation: dartObfuscation,
);
if (snapshotExitCode != 0) {
throw Exception('AOT snapshotter exited with code $snapshotExitCode');
}
}
}
/// Generate an ELF binary from a dart kernel file in profile mode.
class AotElfProfile extends AotElfBase {
const AotElfProfile(this.targetPlatform);
@override
String get name => 'aot_elf_profile';
@override
List<Source> get inputs => <Source>[
const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
const Source.pattern('{BUILD_DIR}/app.dill'),
const Source.artifact(Artifact.engineDartBinary),
const Source.artifact(Artifact.skyEnginePath),
Source.artifact(Artifact.genSnapshot,
platform: targetPlatform,
mode: BuildMode.profile,
),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{BUILD_DIR}/app.so'),
];
@override
List<Target> get dependencies => const <Target>[
KernelSnapshot(),
];
final TargetPlatform targetPlatform;
}
/// Generate an ELF binary from a dart kernel file in release mode.
class AotElfRelease extends AotElfBase {
const AotElfRelease(this.targetPlatform);
@override
String get name => 'aot_elf_release';
@override
List<Source> get inputs => <Source>[
const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
const Source.pattern('{BUILD_DIR}/app.dill'),
const Source.artifact(Artifact.engineDartBinary),
const Source.artifact(Artifact.skyEnginePath),
Source.artifact(Artifact.genSnapshot,
platform: targetPlatform,
mode: BuildMode.release,
),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{BUILD_DIR}/app.so'),
];
@override
List<Target> get dependencies => const <Target>[
KernelSnapshot(),
];
final TargetPlatform targetPlatform;
}
/// Copies the pre-built flutter aot bundle.
// This is a one-off rule for implementing build aot in terms of assemble.
abstract class CopyFlutterAotBundle extends Target {
const CopyFlutterAotBundle();
@override
List<Source> get inputs => const <Source>[
Source.pattern('{BUILD_DIR}/app.so'),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{OUTPUT_DIR}/app.so'),
];
@override
Future<void> build(Environment environment) async {
final File outputFile = environment.outputDir.childFile('app.so');
if (!outputFile.parent.existsSync()) {
outputFile.parent.createSync(recursive: true);
}
environment.buildDir.childFile('app.so').copySync(outputFile.path);
}
}
/// Lipo CLI tool wrapper shared by iOS and macOS builds.
abstract final class Lipo {
/// Create a "fat" binary by combining multiple architecture-specific ones.
/// `skipMissingInputs` can be changed to `true` to first check whether
/// the expected input paths exist and ignore the command if they don't.
/// Otherwise, `lipo` would fail if the given paths didn't exist.
static Future<void> create(
Environment environment,
List<DarwinArch> darwinArchs, {
required String relativePath,
required String inputDir,
bool skipMissingInputs = false,
}) async {
final String resultPath = environment.fileSystem.path.join(environment.buildDir.path, relativePath);
environment.fileSystem.directory(resultPath).parent.createSync(recursive: true);
Iterable<String> inputPaths = darwinArchs.map(
(DarwinArch iosArch) => environment.fileSystem.path.join(inputDir, iosArch.name, relativePath)
);
if (skipMissingInputs) {
inputPaths = inputPaths.where(environment.fileSystem.isFileSync);
if (inputPaths.isEmpty) {
return;
}
}
final List<String> lipoArgs = <String>[
'lipo',
...inputPaths,
'-create',
'-output',
resultPath,
];
final ProcessResult result = await environment.processManager.run(lipoArgs);
if (result.exitCode != 0) {
throw Exception('lipo exited with code ${result.exitCode}.\n${result.stderr}');
}
}
}
| flutter/packages/flutter_tools/lib/src/build_system/targets/common.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/common.dart",
"repo_id": "flutter",
"token_count": 5731
} | 773 |
// 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:pool/pool.dart';
import 'package:process/process.dart';
import 'artifacts.dart';
import 'asset.dart' hide defaultManifestPath;
import 'base/common.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'build_info.dart';
import 'build_system/build_system.dart';
import 'build_system/depfile.dart';
import 'build_system/tools/asset_transformer.dart';
import 'build_system/tools/scene_importer.dart';
import 'build_system/tools/shader_compiler.dart';
import 'bundle.dart';
import 'cache.dart';
import 'devfs.dart';
import 'device.dart';
import 'globals.dart' as globals;
import 'project.dart';
/// Provides a `build` method that builds the bundle.
class BundleBuilder {
/// Builds the bundle for the given target platform.
///
/// The default `mainPath` is `lib/main.dart`.
/// The default `manifestPath` is `pubspec.yaml`.
///
/// If [buildNativeAssets], native assets are built and the mapping for native
/// assets lookup at runtime is embedded in the kernel file, otherwise an
/// empty native assets mapping is embedded in the kernel file.
Future<void> build({
required TargetPlatform platform,
required BuildInfo buildInfo,
FlutterProject? project,
String? mainPath,
String manifestPath = defaultManifestPath,
String? applicationKernelFilePath,
String? depfilePath,
String? assetDirPath,
bool buildNativeAssets = true,
@visibleForTesting BuildSystem? buildSystem,
}) async {
project ??= FlutterProject.current();
mainPath ??= defaultMainPath;
depfilePath ??= defaultDepfilePath;
assetDirPath ??= getAssetBuildDirectory();
buildSystem ??= globals.buildSystem;
// If the precompiled flag was not passed, force us into debug mode.
final Environment environment = Environment(
projectDir: project.directory,
outputDir: globals.fs.directory(assetDirPath),
buildDir: project.dartTool.childDirectory('flutter_build'),
cacheDir: globals.cache.getRoot(),
flutterRootDir: globals.fs.directory(Cache.flutterRoot),
engineVersion: globals.artifacts!.isLocalEngine
? null
: globals.flutterVersion.engineRevision,
defines: <String, String>{
// used by the KernelSnapshot target
kTargetPlatform: getNameForTargetPlatform(platform),
kTargetFile: mainPath,
kDeferredComponents: 'false',
...buildInfo.toBuildSystemEnvironment(),
if (!buildNativeAssets) kNativeAssets: 'false'
},
artifacts: globals.artifacts!,
fileSystem: globals.fs,
logger: globals.logger,
processManager: globals.processManager,
usage: globals.flutterUsage,
analytics: globals.analytics,
platform: globals.platform,
generateDartPluginRegistry: true,
);
final Target target = buildInfo.mode == BuildMode.debug
? globals.buildTargets.copyFlutterBundle
: globals.buildTargets.releaseCopyFlutterBundle;
final BuildResult result = await buildSystem.build(target, environment);
if (!result.success) {
for (final ExceptionMeasurement measurement in result.exceptions.values) {
globals.printError('Target ${measurement.target} failed: ${measurement.exception}',
stackTrace: measurement.fatal
? measurement.stackTrace
: null,
);
}
throwToolExit('Failed to build bundle.');
}
final Depfile depfile = Depfile(result.inputFiles, result.outputFiles);
final File outputDepfile = globals.fs.file(depfilePath);
if (!outputDepfile.parent.existsSync()) {
outputDepfile.parent.createSync(recursive: true);
}
environment.depFileService.writeToFile(depfile, outputDepfile);
// Work around for flutter_tester placing kernel artifacts in odd places.
if (applicationKernelFilePath != null) {
final File outputDill = globals.fs.directory(assetDirPath).childFile('kernel_blob.bin');
if (outputDill.existsSync()) {
outputDill.copySync(applicationKernelFilePath);
}
}
return;
}
}
Future<AssetBundle?> buildAssets({
required String manifestPath,
String? assetDirPath,
String? packagesPath,
TargetPlatform? targetPlatform,
String? flavor,
}) async {
assetDirPath ??= getAssetBuildDirectory();
packagesPath ??= globals.fs.path.absolute('.packages');
// Build the asset bundle.
final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle();
final int result = await assetBundle.build(
manifestPath: manifestPath,
packagesPath: packagesPath,
targetPlatform: targetPlatform,
flavor: flavor,
);
if (result != 0) {
return null;
}
return assetBundle;
}
Future<void> writeBundle(
Directory bundleDir,
Map<String, AssetBundleEntry> assetEntries, {
required TargetPlatform targetPlatform,
required ImpellerStatus impellerStatus,
required ProcessManager processManager,
required FileSystem fileSystem,
required Artifacts artifacts,
required Logger logger,
required Directory projectDir,
}) async {
if (bundleDir.existsSync()) {
try {
bundleDir.deleteSync(recursive: true);
} on FileSystemException catch (err) {
logger.printWarning(
'Failed to clean up asset directory ${bundleDir.path}: $err\n'
'To clean build artifacts, use the command "flutter clean".'
);
}
}
bundleDir.createSync(recursive: true);
final ShaderCompiler shaderCompiler = ShaderCompiler(
processManager: processManager,
logger: logger,
fileSystem: fileSystem,
artifacts: artifacts,
);
final SceneImporter sceneImporter = SceneImporter(
processManager: processManager,
logger: logger,
fileSystem: fileSystem,
artifacts: artifacts,
);
final AssetTransformer assetTransformer = AssetTransformer(
processManager: processManager,
fileSystem: fileSystem,
dartBinaryPath: artifacts.getArtifactPath(Artifact.engineDartBinary),
);
// Limit number of open files to avoid running out of file descriptors.
final Pool pool = Pool(64);
await Future.wait<void>(
assetEntries.entries.map<Future<void>>((MapEntry<String, AssetBundleEntry> entry) async {
final PoolResource resource = await pool.request();
try {
// This will result in strange looking files, for example files with `/`
// on Windows or files that end up getting URI encoded such as `#.ext`
// to `%23.ext`. However, we have to keep it this way since the
// platform channels in the framework will URI encode these values,
// and the native APIs will look for files this way.
final File file = fileSystem.file(fileSystem.path.join(bundleDir.path, entry.key));
file.parent.createSync(recursive: true);
final DevFSContent devFSContent = entry.value.content;
if (devFSContent is DevFSFileContent) {
final File input = devFSContent.file as File;
bool doCopy = true;
switch (entry.value.kind) {
case AssetKind.regular:
if (entry.value.transformers.isEmpty) {
break;
}
final AssetTransformationFailure? failure = await assetTransformer.transformAsset(
asset: input,
outputPath: file.path,
workingDirectory: projectDir.path,
transformerEntries: entry.value.transformers,
);
doCopy = false;
if (failure != null) {
throwToolExit(failure.message);
}
case AssetKind.font:
break;
case AssetKind.shader:
doCopy = !await shaderCompiler.compileShader(
input: input,
outputPath: file.path,
targetPlatform: targetPlatform,
);
case AssetKind.model:
doCopy = !await sceneImporter.importScene(
input: input,
outputPath: file.path,
);
}
if (doCopy) {
input.copySync(file.path);
}
} else {
await file.writeAsBytes(await entry.value.contentsAsBytes());
}
} finally {
resource.release();
}
}));
}
| flutter/packages/flutter_tools/lib/src/bundle_builder.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/bundle_builder.dart",
"repo_id": "flutter",
"token_count": 3134
} | 774 |
// 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 'package:crypto/crypto.dart';
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../base/analyze_size.dart';
import '../base/common.dart';
import '../base/error_handling_io.dart';
import '../base/logger.dart';
import '../base/process.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../convert.dart';
import '../doctor_validator.dart';
import '../globals.dart' as globals;
import '../ios/application_package.dart';
import '../ios/mac.dart';
import '../ios/plist_parser.dart';
import '../reporting/reporting.dart';
import '../runner/flutter_command.dart';
import 'build.dart';
/// Builds an .app for an iOS app to be used for local testing on an iOS device
/// or simulator. Can only be run on a macOS host.
class BuildIOSCommand extends _BuildIOSSubCommand {
BuildIOSCommand({
required super.logger,
required bool verboseHelp,
}) : super(verboseHelp: verboseHelp) {
addPublishPort(verboseHelp: verboseHelp);
argParser
..addFlag('config-only',
help: 'Update the project configuration without performing a build. '
'This can be used in CI/CD process that create an archive to avoid '
'performing duplicate work.'
)
..addFlag('simulator',
help: 'Build for the iOS simulator instead of the device. This changes '
'the default build mode to debug if otherwise unspecified.',
);
}
@override
final String name = 'ios';
@override
final String description = 'Build an iOS application bundle (macOS host only).';
@override
final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.build;
@override
EnvironmentType get environmentType => boolArg('simulator') ? EnvironmentType.simulator : EnvironmentType.physical;
@override
bool get configOnly => boolArg('config-only');
@override
Directory _outputAppDirectory(String xcodeResultOutput) => globals.fs.directory(xcodeResultOutput).parent;
}
/// The key that uniquely identifies an image file in an image asset.
/// It consists of (idiom, scale, size?), where size is present for app icon
/// asset, and null for launch image asset.
@immutable
class _ImageAssetFileKey {
const _ImageAssetFileKey(this.idiom, this.scale, this.size);
/// The idiom (iphone or ipad).
final String idiom;
/// The scale factor (e.g. 2).
final int scale;
/// The logical size in point (e.g. 83.5).
/// Size is present for app icon, and null for launch image.
final double? size;
@override
int get hashCode => Object.hash(idiom, scale, size);
@override
bool operator ==(Object other) => other is _ImageAssetFileKey
&& other.idiom == idiom
&& other.scale == scale
&& other.size == size;
/// The pixel size based on logical size and scale.
int? get pixelSize => size == null ? null : (size! * scale).toInt(); // pixel size must be an int.
}
/// Builds an .xcarchive and optionally .ipa for an iOS app to be generated for
/// App Store submission.
///
/// Can only be run on a macOS host.
class BuildIOSArchiveCommand extends _BuildIOSSubCommand {
BuildIOSArchiveCommand({required super.logger, required super.verboseHelp}) {
argParser.addOption(
'export-method',
defaultsTo: 'app-store',
allowed: <String>['app-store', 'ad-hoc', 'development', 'enterprise'],
help: 'Specify how the IPA will be distributed.',
allowedHelp: <String, String>{
'app-store': 'Upload to the App Store.',
'ad-hoc': 'Test on designated devices that do not need to be registered with the Apple developer account. '
'Requires a distribution certificate.',
'development': 'Test only on development devices registered with the Apple developer account.',
'enterprise': 'Distribute an app registered with the Apple Developer Enterprise Program.',
},
);
argParser.addOption(
'export-options-plist',
valueHelp: 'ExportOptions.plist',
help:
'Export an IPA with these options. See "xcodebuild -h" for available exportOptionsPlist keys.',
);
}
@override
final String name = 'ipa';
@override
final List<String> aliases = <String>['xcarchive'];
@override
final String description = 'Build an iOS archive bundle and IPA for distribution (macOS host only).';
@override
final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.archive;
@override
final EnvironmentType environmentType = EnvironmentType.physical;
@override
final bool configOnly = false;
String? get exportOptionsPlist => stringArg('export-options-plist');
@override
Directory _outputAppDirectory(String xcodeResultOutput) => globals.fs
.directory(xcodeResultOutput)
.childDirectory('Products')
.childDirectory('Applications');
@override
Future<void> validateCommand() async {
final String? exportOptions = exportOptionsPlist;
if (exportOptions != null) {
if (argResults?.wasParsed('export-method') ?? false) {
throwToolExit(
'"--export-options-plist" is not compatible with "--export-method". Either use "--export-options-plist" and '
'a plist describing how the IPA should be exported by Xcode, or use "--export-method" to create a new plist.\n'
'See "xcodebuild -h" for available exportOptionsPlist keys.'
);
}
final FileSystemEntityType type = globals.fs.typeSync(exportOptions);
if (type == FileSystemEntityType.notFound) {
throwToolExit(
'"$exportOptions" property list does not exist.');
} else if (type != FileSystemEntityType.file) {
throwToolExit(
'"$exportOptions" is not a file. See "xcodebuild -h" for available keys.');
}
}
return super.validateCommand();
}
// A helper function to parse Contents.json of an image asset into a map,
// with the key to be _ImageAssetFileKey, and value to be the image file name.
// Some assets have size (e.g. app icon) and others do not (e.g. launch image).
Map<_ImageAssetFileKey, String> _parseImageAssetContentsJson(
String contentsJsonDirName,
{ required bool requiresSize })
{
final Directory contentsJsonDirectory = globals.fs.directory(contentsJsonDirName);
if (!contentsJsonDirectory.existsSync()) {
return <_ImageAssetFileKey, String>{};
}
final File contentsJsonFile = contentsJsonDirectory.childFile('Contents.json');
final Map<String, dynamic> contents = json.decode(contentsJsonFile.readAsStringSync()) as Map<String, dynamic>? ?? <String, dynamic>{};
final List<dynamic> images = contents['images'] as List<dynamic>? ?? <dynamic>[];
final Map<String, dynamic> info = contents['info'] as Map<String, dynamic>? ?? <String, dynamic>{};
if ((info['version'] as int?) != 1) {
// Skips validation for unknown format.
return <_ImageAssetFileKey, String>{};
}
final Map<_ImageAssetFileKey, String> iconInfo = <_ImageAssetFileKey, String>{};
for (final dynamic image in images) {
final Map<String, dynamic> imageMap = image as Map<String, dynamic>;
final String? idiom = imageMap['idiom'] as String?;
final String? size = imageMap['size'] as String?;
final String? scale = imageMap['scale'] as String?;
final String? fileName = imageMap['filename'] as String?;
// requiresSize must match the actual presence of size in json.
if (requiresSize != (size != null)
|| idiom == null || scale == null || fileName == null)
{
continue;
}
final double? parsedSize;
if (size != null) {
// for example, "64x64". Parse the width since it is a square.
final Iterable<double> parsedSizes = size.split('x')
.map((String element) => double.tryParse(element))
.whereType<double>();
if (parsedSizes.isEmpty) {
continue;
}
parsedSize = parsedSizes.first;
} else {
parsedSize = null;
}
// for example, "3x".
final Iterable<int> parsedScales = scale.split('x')
.map((String element) => int.tryParse(element))
.whereType<int>();
if (parsedScales.isEmpty) {
continue;
}
final int parsedScale = parsedScales.first;
iconInfo[_ImageAssetFileKey(idiom, parsedScale, parsedSize)] = fileName;
}
return iconInfo;
}
// A helper function to check if an image asset is still using template files.
bool _isAssetStillUsingTemplateFiles({
required Map<_ImageAssetFileKey, String> templateImageInfoMap,
required Map<_ImageAssetFileKey, String> projectImageInfoMap,
required String templateImageDirName,
required String projectImageDirName,
}) {
return projectImageInfoMap.entries.any((MapEntry<_ImageAssetFileKey, String> entry) {
final String projectFileName = entry.value;
final String? templateFileName = templateImageInfoMap[entry.key];
if (templateFileName == null) {
return false;
}
final File projectFile = globals.fs.file(
globals.fs.path.join(projectImageDirName, projectFileName));
final File templateFile = globals.fs.file(
globals.fs.path.join(templateImageDirName, templateFileName));
return projectFile.existsSync()
&& templateFile.existsSync()
&& md5.convert(projectFile.readAsBytesSync()) ==
md5.convert(templateFile.readAsBytesSync());
});
}
// A helper function to return a list of image files in an image asset with
// wrong sizes (as specified in its Contents.json file).
List<String> _imageFilesWithWrongSize({
required Map<_ImageAssetFileKey, String> imageInfoMap,
required String imageDirName,
}) {
return imageInfoMap.entries.where((MapEntry<_ImageAssetFileKey, String> entry) {
final String fileName = entry.value;
final File imageFile = globals.fs.file(globals.fs.path.join(imageDirName, fileName));
if (!imageFile.existsSync()) {
return false;
}
// validate image size is correct.
// PNG file's width is at byte [16, 20), and height is at byte [20, 24), in big endian format.
// Based on https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_format
final ByteData imageData = imageFile.readAsBytesSync().buffer.asByteData();
if (imageData.lengthInBytes < 24) {
return false;
}
final int width = imageData.getInt32(16);
final int height = imageData.getInt32(20);
// The size must not be null.
final int expectedSize = entry.key.pixelSize!;
return width != expectedSize || height != expectedSize;
})
.map((MapEntry<_ImageAssetFileKey, String> entry) => entry.value)
.toList();
}
ValidationResult? _createValidationResult(String title, List<ValidationMessage> messages) {
if (messages.isEmpty) {
return null;
}
final bool anyInvalid = messages.any((ValidationMessage message) => message.type != ValidationMessageType.information);
return ValidationResult(
anyInvalid ? ValidationType.partial : ValidationType.success,
messages,
statusInfo: title,
);
}
ValidationMessage _createValidationMessage({
required bool isValid,
required String message,
}) {
// Use "information" type for valid message, and "hint" type for invalid message.
return isValid ? ValidationMessage(message) : ValidationMessage.hint(message);
}
Future<List<ValidationMessage>> _validateIconAssetsAfterArchive() async {
final BuildableIOSApp app = await buildableIOSApp;
final Map<_ImageAssetFileKey, String> templateInfoMap = _parseImageAssetContentsJson(
app.templateAppIconDirNameForContentsJson,
requiresSize: true);
final Map<_ImageAssetFileKey, String> projectInfoMap = _parseImageAssetContentsJson(
app.projectAppIconDirName,
requiresSize: true);
final List<ValidationMessage> validationMessages = <ValidationMessage>[];
final bool usesTemplate = _isAssetStillUsingTemplateFiles(
templateImageInfoMap: templateInfoMap,
projectImageInfoMap: projectInfoMap,
templateImageDirName: await app.templateAppIconDirNameForImages,
projectImageDirName: app.projectAppIconDirName);
if (usesTemplate) {
validationMessages.add(_createValidationMessage(
isValid: false,
message: 'App icon is set to the default placeholder icon. Replace with unique icons.',
));
}
final List<String> filesWithWrongSize = _imageFilesWithWrongSize(
imageInfoMap: projectInfoMap,
imageDirName: app.projectAppIconDirName);
if (filesWithWrongSize.isNotEmpty) {
validationMessages.add(_createValidationMessage(
isValid: false,
message: 'App icon is using the incorrect size (e.g. ${filesWithWrongSize.first}).',
));
}
return validationMessages;
}
Future<List<ValidationMessage>> _validateLaunchImageAssetsAfterArchive() async {
final BuildableIOSApp app = await buildableIOSApp;
final Map<_ImageAssetFileKey, String> templateInfoMap = _parseImageAssetContentsJson(
app.templateLaunchImageDirNameForContentsJson,
requiresSize: false);
final Map<_ImageAssetFileKey, String> projectInfoMap = _parseImageAssetContentsJson(
app.projectLaunchImageDirName,
requiresSize: false);
final List<ValidationMessage> validationMessages = <ValidationMessage>[];
final bool usesTemplate = _isAssetStillUsingTemplateFiles(
templateImageInfoMap: templateInfoMap,
projectImageInfoMap: projectInfoMap,
templateImageDirName: await app.templateLaunchImageDirNameForImages,
projectImageDirName: app.projectLaunchImageDirName);
if (usesTemplate) {
validationMessages.add(_createValidationMessage(
isValid: false,
message: 'Launch image is set to the default placeholder icon. Replace with unique launch image.',
));
}
return validationMessages;
}
Future<List<ValidationMessage>> _validateXcodeBuildSettingsAfterArchive() async {
final BuildableIOSApp app = await buildableIOSApp;
final String plistPath = app.builtInfoPlistPathAfterArchive;
if (!globals.fs.file(plistPath).existsSync()) {
globals.printError('Invalid iOS archive. Does not contain Info.plist.');
return <ValidationMessage>[];
}
final Map<String, String?> xcodeProjectSettingsMap = <String, String?>{};
xcodeProjectSettingsMap['Version Number'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleShortVersionStringKey);
xcodeProjectSettingsMap['Build Number'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleVersionKey);
xcodeProjectSettingsMap['Display Name'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleDisplayNameKey)
?? globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleNameKey);
xcodeProjectSettingsMap['Deployment Target'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kMinimumOSVersionKey);
xcodeProjectSettingsMap['Bundle Identifier'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleIdentifierKey);
final List<ValidationMessage> validationMessages = xcodeProjectSettingsMap.entries.map((MapEntry<String, String?> entry) {
final String title = entry.key;
final String? info = entry.value;
return _createValidationMessage(
isValid: info != null,
message: '$title: ${info ?? "Missing"}',
);
}).toList();
final bool hasMissingSettings = xcodeProjectSettingsMap.values.any((String? element) => element == null);
if (hasMissingSettings) {
validationMessages.add(_createValidationMessage(
isValid: false,
message: 'You must set up the missing app settings.'),
);
}
final bool usesDefaultBundleIdentifier = xcodeProjectSettingsMap['Bundle Identifier']?.startsWith('com.example') ?? false;
if (usesDefaultBundleIdentifier) {
validationMessages.add(_createValidationMessage(
isValid: false,
message: 'Your application still contains the default "com.example" bundle identifier.'),
);
}
return validationMessages;
}
@override
Future<FlutterCommandResult> runCommand() async {
final BuildInfo buildInfo = await cachedBuildInfo;
displayNullSafetyMode(buildInfo);
final FlutterCommandResult xcarchiveResult = await super.runCommand();
final List<ValidationResult?> validationResults = <ValidationResult?>[];
validationResults.add(_createValidationResult(
'App Settings Validation',
await _validateXcodeBuildSettingsAfterArchive(),
));
validationResults.add(_createValidationResult(
'App Icon and Launch Image Assets Validation',
await _validateIconAssetsAfterArchive() + await _validateLaunchImageAssetsAfterArchive(),
));
for (final ValidationResult result in validationResults.whereType<ValidationResult>()) {
globals.printStatus('\n${result.coloredLeadingBox} ${result.statusInfo}');
for (final ValidationMessage message in result.messages) {
globals.printStatus(
'${message.coloredIndicator} ${message.message}',
indent: result.leadingBox.length + 1,
);
}
}
globals.printStatus('\nTo update the settings, please refer to https://docs.flutter.dev/deployment/ios\n');
// xcarchive failed or not at expected location.
if (xcarchiveResult.exitStatus != ExitStatus.success) {
globals.printStatus('Skipping IPA.');
return xcarchiveResult;
}
if (!shouldCodesign) {
globals.printStatus('Codesigning disabled with --no-codesign, skipping IPA.');
return xcarchiveResult;
}
// Build IPA from generated xcarchive.
final BuildableIOSApp app = await buildableIOSApp;
Status? status;
RunResult? result;
final String relativeOutputPath = app.ipaOutputPath;
final String absoluteOutputPath = globals.fs.path.absolute(relativeOutputPath);
final String absoluteArchivePath = globals.fs.path.absolute(app.archiveBundleOutputPath);
String? exportOptions = exportOptionsPlist;
String? exportMethod = exportOptions != null ?
globals.plistParser.getValueFromFile<String?>(exportOptions, 'method') : null;
exportMethod ??= stringArg('export-method')!;
final bool isAppStoreUpload = exportMethod == 'app-store';
File? generatedExportPlist;
try {
final String exportMethodDisplayName = isAppStoreUpload ? 'App Store' : exportMethod;
status = globals.logger.startProgress('Building $exportMethodDisplayName IPA...');
if (exportOptions == null) {
generatedExportPlist = _createExportPlist();
exportOptions = generatedExportPlist.path;
}
result = await globals.processUtils.run(
<String>[
...globals.xcode!.xcrunCommand(),
'xcodebuild',
'-exportArchive',
if (shouldCodesign) ...<String>[
'-allowProvisioningDeviceRegistration',
'-allowProvisioningUpdates',
],
'-archivePath',
absoluteArchivePath,
'-exportPath',
absoluteOutputPath,
'-exportOptionsPlist',
globals.fs.path.absolute(exportOptions),
],
);
} finally {
if (generatedExportPlist != null) {
ErrorHandlingFileSystem.deleteIfExists(generatedExportPlist);
}
status?.stop();
}
if (result.exitCode != 0) {
final StringBuffer errorMessage = StringBuffer();
// "error:" prefixed lines are the nicely formatted error message, the
// rest is the same message but printed as a IDEFoundationErrorDomain.
// Example:
// error: exportArchive: exportOptionsPlist error for key 'method': expected one of {app-store, ad-hoc, enterprise, development, validation}, but found developmentasdasd
// Error Domain=IDEFoundationErrorDomain Code=1 "exportOptionsPlist error for key 'method': expected one of {app-store, ad-hoc, enterprise, development, validation}, but found developmentasdasd" ...
LineSplitter.split(result.stderr)
.where((String line) => line.contains('error: '))
.forEach(errorMessage.writeln);
globals.printError('Encountered error while creating the IPA:');
globals.printError(errorMessage.toString());
globals.printError('Try distributing the app in Xcode: "open $absoluteArchivePath"');
// Even though the IPA step didn't succeed, the xcarchive did.
// Still count this as success since the user has been instructed about how to
// recover in Xcode.
return FlutterCommandResult.success();
}
globals.printStatus('Built IPA to $absoluteOutputPath.');
if (isAppStoreUpload) {
globals.printStatus('To upload to the App Store either:');
globals.printStatus(
'1. Drag and drop the "$relativeOutputPath/*.ipa" bundle into the Apple Transporter macOS app https://apps.apple.com/us/app/transporter/id1450874784',
indent: 4,
);
globals.printStatus(
'2. Run "xcrun altool --upload-app --type ios -f $relativeOutputPath/*.ipa --apiKey your_api_key --apiIssuer your_issuer_id".',
indent: 4,
);
globals.printStatus(
'See "man altool" for details about how to authenticate with the App Store Connect API key.',
indent: 7,
);
}
return FlutterCommandResult.success();
}
File _createExportPlist() {
// Create the plist to be passed into xcodebuild -exportOptionsPlist.
final StringBuffer plistContents = StringBuffer('''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>method</key>
<string>${stringArg('export-method')}</string>
<key>uploadBitcode</key>
<false/>
</dict>
</plist>
''');
final File tempPlist = globals.fs.systemTempDirectory
.createTempSync('flutter_build_ios.').childFile('ExportOptions.plist');
tempPlist.writeAsStringSync(plistContents.toString());
return tempPlist;
}
}
abstract class _BuildIOSSubCommand extends BuildSubCommand {
_BuildIOSSubCommand({
required super.logger,
required bool verboseHelp
}) : super(verboseHelp: verboseHelp) {
addTreeShakeIconsFlag();
addSplitDebugInfoOption();
addBuildModeFlags(verboseHelp: verboseHelp);
usesTargetOption();
usesFlavorOption();
usesPubOption();
usesBuildNumberOption();
usesBuildNameOption();
addDartObfuscationOption();
usesDartDefineOption();
usesExtraDartFlagOptions(verboseHelp: verboseHelp);
addEnableExperimentation(hide: !verboseHelp);
addBuildPerformanceFile(hide: !verboseHelp);
addBundleSkSLPathOption(hide: !verboseHelp);
addNullSafetyModeOptions(hide: !verboseHelp);
usesAnalyzeSizeFlag();
argParser.addFlag('codesign',
defaultsTo: true,
help: 'Codesign the application bundle (only available on device builds).',
);
}
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{
DevelopmentArtifact.iOS,
};
XcodeBuildAction get xcodeBuildAction;
/// The result of the Xcode build command. Null until it finishes.
@protected
XcodeBuildResult? xcodeBuildResult;
EnvironmentType get environmentType;
bool get configOnly;
bool get shouldCodesign => boolArg('codesign');
late final Future<BuildInfo> cachedBuildInfo = getBuildInfo();
late final Future<BuildableIOSApp> buildableIOSApp = () async {
final BuildableIOSApp? app = await applicationPackages?.getPackageForPlatform(
TargetPlatform.ios,
buildInfo: await cachedBuildInfo,
) as BuildableIOSApp?;
if (app == null) {
throwToolExit('Application not configured for iOS');
}
return app;
}();
Directory _outputAppDirectory(String xcodeResultOutput);
@override
bool get supported => globals.platform.isMacOS;
@override
Future<FlutterCommandResult> runCommand() async {
defaultBuildMode = environmentType == EnvironmentType.simulator ? BuildMode.debug : BuildMode.release;
final BuildInfo buildInfo = await cachedBuildInfo;
if (!supported) {
throwToolExit('Building for iOS is only supported on macOS.');
}
if (environmentType == EnvironmentType.simulator && !buildInfo.supportsSimulator) {
throwToolExit('${sentenceCase(buildInfo.friendlyModeName)} mode is not supported for simulators.');
}
if (configOnly && buildInfo.codeSizeDirectory != null) {
throwToolExit('Cannot analyze code size without performing a full build.');
}
if (environmentType == EnvironmentType.physical && !shouldCodesign) {
globals.printStatus(
'Warning: Building for device with codesigning disabled. You will '
'have to manually codesign before deploying to device.',
);
}
final BuildableIOSApp app = await buildableIOSApp;
final String logTarget = environmentType == EnvironmentType.simulator ? 'simulator' : 'device';
final String typeName = globals.artifacts!.getEngineType(TargetPlatform.ios, buildInfo.mode);
if (xcodeBuildAction == XcodeBuildAction.build) {
globals.printStatus('Building $app for $logTarget ($typeName)...');
} else {
globals.printStatus('Archiving $app...');
}
final XcodeBuildResult result = await buildXcodeProject(
app: app,
buildInfo: buildInfo,
targetOverride: targetFile,
environmentType: environmentType,
codesign: shouldCodesign,
configOnly: configOnly,
buildAction: xcodeBuildAction,
deviceID: globals.deviceManager?.specifiedDeviceId,
disablePortPublication: usingCISystem &&
xcodeBuildAction == XcodeBuildAction.build &&
await disablePortPublication,
);
xcodeBuildResult = result;
if (!result.success) {
await diagnoseXcodeBuildFailure(result, globals.flutterUsage, globals.logger, globals.analytics);
final String presentParticiple = xcodeBuildAction == XcodeBuildAction.build ? 'building' : 'archiving';
throwToolExit('Encountered error while $presentParticiple for $logTarget.');
}
if (buildInfo.codeSizeDirectory != null) {
final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
fileSystem: globals.fs,
logger: globals.logger,
flutterUsage: globals.flutterUsage,
analytics: analytics,
appFilenamePattern: 'App'
);
// Only support 64bit iOS code size analysis.
final String arch = DarwinArch.arm64.name;
final File aotSnapshot = globals.fs.directory(buildInfo.codeSizeDirectory)
.childFile('snapshot.$arch.json');
final File precompilerTrace = globals.fs.directory(buildInfo.codeSizeDirectory)
.childFile('trace.$arch.json');
final String? resultOutput = result.output;
if (resultOutput == null) {
throwToolExit('Could not find app to analyze code size');
}
final Directory outputAppDirectoryCandidate = _outputAppDirectory(resultOutput);
Directory? appDirectory;
if (outputAppDirectoryCandidate.existsSync()) {
appDirectory = outputAppDirectoryCandidate.listSync()
.whereType<Directory>()
.where((Directory directory) {
return globals.fs.path.extension(directory.path) == '.app';
}).first;
}
if (appDirectory == null) {
throwToolExit('Could not find app to analyze code size in ${outputAppDirectoryCandidate.path}');
}
final Map<String, Object?> output = await sizeAnalyzer.analyzeAotSnapshot(
aotSnapshot: aotSnapshot,
precompilerTrace: precompilerTrace,
outputDirectory: appDirectory,
type: 'ios',
);
final File outputFile = globals.fsUtils.getUniqueFile(
globals.fs
.directory(globals.fsUtils.homeDirPath)
.childDirectory('.flutter-devtools'), 'ios-code-size-analysis', 'json',
)..writeAsStringSync(jsonEncode(output));
// This message is used as a sentinel in analyze_apk_size_test.dart
globals.printStatus(
'A summary of your iOS bundle analysis can be found at: ${outputFile.path}',
);
// DevTools expects a file path relative to the .flutter-devtools/ dir.
final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim();
globals.printStatus(
'\nTo analyze your app size in Dart DevTools, run the following command:\n'
'dart devtools --appSizeBase=$relativeAppSizePath'
);
}
if (result.output != null) {
globals.printStatus('Built ${result.output}.');
// When an app is successfully built, record to analytics whether Impeller
// is enabled or disabled.
final BuildableIOSApp app = await buildableIOSApp;
final String plistPath = app.project.infoPlist.path;
final bool? impellerEnabled = globals.plistParser.getValueFromFile<bool>(
plistPath, PlistParser.kFLTEnableImpellerKey,
);
final String buildLabel = impellerEnabled == false
? 'plist-impeller-disabled'
: 'plist-impeller-enabled';
BuildEvent(
buildLabel,
type: 'ios',
flutterUsage: globals.flutterUsage,
).send();
globals.analytics.send(Event.flutterBuildInfo(
label: buildLabel,
buildType: 'ios',
));
return FlutterCommandResult.success();
}
return FlutterCommandResult.fail();
}
}
| flutter/packages/flutter_tools/lib/src/commands/build_ios.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/build_ios.dart",
"repo_id": "flutter",
"token_count": 10509
} | 775 |
// 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/common.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/terminal.dart';
import '../base/utils.dart';
import '../convert.dart';
import '../device.dart';
import '../globals.dart' as globals;
import '../runner/flutter_command.dart';
class DevicesCommand extends FlutterCommand {
DevicesCommand({ bool verboseHelp = false }) {
argParser.addFlag('machine',
negatable: false,
help: 'Output device information in machine readable structured JSON format.',
);
argParser.addOption(
'timeout',
abbr: 't',
help: '(deprecated) This option has been replaced by "--${FlutterOptions.kDeviceTimeout}".',
hide: !verboseHelp,
);
usesDeviceTimeoutOption();
usesDeviceConnectionOption();
}
@override
final String name = 'devices';
@override
final String description = 'List all connected devices.';
@override
final String category = FlutterCommandCategory.tools;
@override
Duration? get deviceDiscoveryTimeout {
if (argResults?['timeout'] != null) {
final int? timeoutSeconds = int.tryParse(stringArg('timeout')!);
if (timeoutSeconds == null) {
throwToolExit('Could not parse -t/--timeout argument. It must be an integer.');
}
return Duration(seconds: timeoutSeconds);
}
return super.deviceDiscoveryTimeout;
}
@override
Future<void> validateCommand() {
if (argResults?['timeout'] != null) {
globals.printWarning('${globals.logger.terminal.warningMark} The "--timeout" argument is deprecated; use "--${FlutterOptions.kDeviceTimeout}" instead.');
}
return super.validateCommand();
}
@override
Future<FlutterCommandResult> runCommand() async {
if (globals.doctor?.canListAnything != true) {
throwToolExit(
"Unable to locate a development device; please run 'flutter doctor' for "
'information about installing additional components.',
exitCode: 1);
}
final DevicesCommandOutput output = DevicesCommandOutput(
platform: globals.platform,
logger: globals.logger,
deviceManager: globals.deviceManager,
deviceDiscoveryTimeout: deviceDiscoveryTimeout,
deviceConnectionInterface: deviceConnectionInterface,
);
await output.findAndOutputAllTargetDevices(
machine: boolArg('machine'),
);
return FlutterCommandResult.success();
}
}
class DevicesCommandOutput {
factory DevicesCommandOutput({
required Platform platform,
required Logger logger,
DeviceManager? deviceManager,
Duration? deviceDiscoveryTimeout,
DeviceConnectionInterface? deviceConnectionInterface,
}) {
if (platform.isMacOS) {
return DevicesCommandOutputWithExtendedWirelessDeviceDiscovery(
logger: logger,
deviceManager: deviceManager,
deviceDiscoveryTimeout: deviceDiscoveryTimeout,
deviceConnectionInterface: deviceConnectionInterface,
);
}
return DevicesCommandOutput._private(
logger: logger,
deviceManager: deviceManager,
deviceDiscoveryTimeout: deviceDiscoveryTimeout,
deviceConnectionInterface: deviceConnectionInterface,
);
}
DevicesCommandOutput._private({
required Logger logger,
required DeviceManager? deviceManager,
required this.deviceDiscoveryTimeout,
required this.deviceConnectionInterface,
}) : _deviceManager = deviceManager,
_logger = logger;
final DeviceManager? _deviceManager;
final Logger _logger;
final Duration? deviceDiscoveryTimeout;
final DeviceConnectionInterface? deviceConnectionInterface;
bool get _includeAttachedDevices =>
deviceConnectionInterface == null ||
deviceConnectionInterface == DeviceConnectionInterface.attached;
bool get _includeWirelessDevices =>
deviceConnectionInterface == null ||
deviceConnectionInterface == DeviceConnectionInterface.wireless;
Future<List<Device>> _getAttachedDevices(DeviceManager deviceManager) async {
if (!_includeAttachedDevices) {
return <Device>[];
}
return deviceManager.getAllDevices(
filter: DeviceDiscoveryFilter(
deviceConnectionInterface: DeviceConnectionInterface.attached,
),
);
}
Future<List<Device>> _getWirelessDevices(DeviceManager deviceManager) async {
if (!_includeWirelessDevices) {
return <Device>[];
}
return deviceManager.getAllDevices(
filter: DeviceDiscoveryFilter(
deviceConnectionInterface: DeviceConnectionInterface.wireless,
),
);
}
Future<void> findAndOutputAllTargetDevices({required bool machine}) async {
List<Device> attachedDevices = <Device>[];
List<Device> wirelessDevices = <Device>[];
final DeviceManager? deviceManager = _deviceManager;
if (deviceManager != null) {
// Refresh the cache and then get the attached and wireless devices from
// the cache.
await deviceManager.refreshAllDevices(timeout: deviceDiscoveryTimeout);
attachedDevices = await _getAttachedDevices(deviceManager);
wirelessDevices = await _getWirelessDevices(deviceManager);
}
final List<Device> allDevices = attachedDevices + wirelessDevices;
if (machine) {
await printDevicesAsJson(allDevices);
return;
}
if (allDevices.isEmpty) {
_logger.printStatus('No authorized devices detected.');
} else {
if (attachedDevices.isNotEmpty) {
_logger.printStatus('Found ${attachedDevices.length} connected ${pluralize('device', attachedDevices.length)}:');
await Device.printDevices(attachedDevices, _logger, prefix: ' ');
}
if (wirelessDevices.isNotEmpty) {
if (attachedDevices.isNotEmpty) {
_logger.printStatus('');
}
_logger.printStatus('Found ${wirelessDevices.length} wirelessly connected ${pluralize('device', wirelessDevices.length)}:');
await Device.printDevices(wirelessDevices, _logger, prefix: ' ');
}
}
await _printDiagnostics(foundAny: allDevices.isNotEmpty);
}
Future<void> _printDiagnostics({ required bool foundAny }) async {
final StringBuffer status = StringBuffer();
status.writeln();
final List<String> diagnostics = await _deviceManager?.getDeviceDiagnostics() ?? <String>[];
if (diagnostics.isNotEmpty) {
for (final String diagnostic in diagnostics) {
status.writeln(diagnostic);
status.writeln();
}
}
status.writeln('Run "flutter emulators" to list and start any available device emulators.');
status.writeln();
status.write('If you expected ${ foundAny ? 'another' : 'a' } device to be detected, please run "flutter doctor" to diagnose potential issues. ');
if (deviceDiscoveryTimeout == null) {
status.write('You may also try increasing the time to wait for connected devices with the "--${FlutterOptions.kDeviceTimeout}" flag. ');
}
status.write('Visit https://flutter.dev/setup/ for troubleshooting tips.');
_logger.printStatus(status.toString());
}
Future<void> printDevicesAsJson(List<Device> devices) async {
_logger.printStatus(
const JsonEncoder.withIndent(' ').convert(
await Future.wait(devices.map((Device d) => d.toJson()))
)
);
}
}
const String _checkingForWirelessDevicesMessage = 'Checking for wireless devices...';
const String _noAttachedCheckForWireless = 'No devices found yet. Checking for wireless devices...';
const String _noWirelessDevicesFoundMessage = 'No wireless devices were found.';
class DevicesCommandOutputWithExtendedWirelessDeviceDiscovery extends DevicesCommandOutput {
DevicesCommandOutputWithExtendedWirelessDeviceDiscovery({
required super.logger,
super.deviceManager,
super.deviceDiscoveryTimeout,
super.deviceConnectionInterface,
}) : super._private();
@override
Future<void> findAndOutputAllTargetDevices({required bool machine}) async {
// When a user defines the timeout or filters to only attached devices,
// use the super function that does not do longer wireless device discovery.
if (deviceDiscoveryTimeout != null || deviceConnectionInterface == DeviceConnectionInterface.attached) {
return super.findAndOutputAllTargetDevices(machine: machine);
}
if (machine) {
final List<Device> devices = await _deviceManager?.refreshAllDevices(
filter: DeviceDiscoveryFilter(
deviceConnectionInterface: deviceConnectionInterface,
),
timeout: DeviceManager.minimumWirelessDeviceDiscoveryTimeout,
) ?? <Device>[];
await printDevicesAsJson(devices);
return;
}
final Future<void>? extendedWirelessDiscovery = _deviceManager?.refreshExtendedWirelessDeviceDiscoverers(
timeout: DeviceManager.minimumWirelessDeviceDiscoveryTimeout,
);
List<Device> attachedDevices = <Device>[];
final DeviceManager? deviceManager = _deviceManager;
if (deviceManager != null) {
attachedDevices = await _getAttachedDevices(deviceManager);
}
// Number of lines to clear starts at 1 because it's inclusive of the line
// the cursor is on, which will be blank for this use case.
int numLinesToClear = 1;
// Display list of attached devices.
if (attachedDevices.isNotEmpty) {
_logger.printStatus('Found ${attachedDevices.length} connected ${pluralize('device', attachedDevices.length)}:');
await Device.printDevices(attachedDevices, _logger, prefix: ' ');
_logger.printStatus('');
numLinesToClear += 1;
}
// Display waiting message.
if (attachedDevices.isEmpty && _includeAttachedDevices) {
_logger.printStatus(_noAttachedCheckForWireless);
} else {
_logger.printStatus(_checkingForWirelessDevicesMessage);
}
numLinesToClear += 1;
final Status waitingStatus = _logger.startSpinner();
await extendedWirelessDiscovery;
List<Device> wirelessDevices = <Device>[];
if (deviceManager != null) {
wirelessDevices = await _getWirelessDevices(deviceManager);
}
waitingStatus.stop();
final Terminal terminal = _logger.terminal;
if (_logger.isVerbose && _includeAttachedDevices) {
// Reprint the attach devices.
if (attachedDevices.isNotEmpty) {
_logger.printStatus('\nFound ${attachedDevices.length} connected ${pluralize('device', attachedDevices.length)}:');
await Device.printDevices(attachedDevices, _logger, prefix: ' ');
}
} else if (terminal.supportsColor && terminal is AnsiTerminal) {
_logger.printStatus(
terminal.clearLines(numLinesToClear),
newline: false,
);
}
if (attachedDevices.isNotEmpty || !_logger.terminal.supportsColor) {
_logger.printStatus('');
}
if (wirelessDevices.isEmpty) {
if (attachedDevices.isEmpty) {
// No wireless or attached devices were found.
_logger.printStatus('No authorized devices detected.');
} else {
// Attached devices found, wireless devices not found.
_logger.printStatus(_noWirelessDevicesFoundMessage);
}
} else {
// Display list of wireless devices.
_logger.printStatus('Found ${wirelessDevices.length} wirelessly connected ${pluralize('device', wirelessDevices.length)}:');
await Device.printDevices(wirelessDevices, _logger, prefix: ' ');
}
await _printDiagnostics(foundAny: wirelessDevices.isNotEmpty || attachedDevices.isNotEmpty);
}
}
| flutter/packages/flutter_tools/lib/src/commands/devices.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/devices.dart",
"repo_id": "flutter",
"token_count": 3913
} | 776 |
// 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:completion/completion.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../globals.dart' as globals;
import '../runner/flutter_command.dart';
class ShellCompletionCommand extends FlutterCommand {
ShellCompletionCommand() {
argParser.addFlag(
'overwrite',
help: 'Causes the given shell completion setup script to be overwritten if it already exists.',
);
}
@override
final String name = 'bash-completion';
@override
final String description = 'Output command line shell completion setup scripts.\n\n'
'This command prints the flutter command line completion setup script for Bash and Zsh. To '
'use it, specify an output file and follow the instructions in the generated output file to '
'install it in your shell environment. Once it is sourced, your shell will be able to '
'complete flutter commands and options.';
@override
final String category = FlutterCommandCategory.sdk;
@override
final List<String> aliases = <String>['zsh-completion'];
@override
bool get shouldUpdateCache => false;
/// Return null to disable analytics recording of the `bash-completion` command.
@override
Future<String?> get usagePath async => null;
@override
Future<FlutterCommandResult> runCommand() async {
final List<String> rest = argResults?.rest ?? <String>[];
if (rest.length > 1) {
throwToolExit('Too many arguments given to bash-completion command.', exitCode: 1);
}
if (rest.isEmpty || rest.first == '-') {
final String script = generateCompletionScript(<String>['flutter']);
globals.stdio.stdoutWrite(script);
return FlutterCommandResult.warning();
}
final File outputFile = globals.fs.file(rest.first);
if (outputFile.existsSync() && !boolArg('overwrite')) {
throwToolExit(
'Output file ${outputFile.path} already exists, will not overwrite. '
'Use --overwrite to force overwriting existing output file.',
exitCode: 1,
);
}
try {
outputFile.writeAsStringSync(generateCompletionScript(<String>['flutter']));
} on FileSystemException catch (error) {
throwToolExit('Unable to write shell completion setup script.\n$error', exitCode: 1);
}
return FlutterCommandResult.success();
}
}
| flutter/packages/flutter_tools/lib/src/commands/shell_completion.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/shell_completion.dart",
"repo_id": "flutter",
"token_count": 810
} | 777 |
// 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:file/file.dart';
import 'package:package_config/package_config.dart';
import '../base/version.dart';
final RegExp _languageVersion = RegExp(r'\/\/\s*@dart\s*=\s*([0-9])\.([0-9]+)');
final RegExp _declarationEnd = RegExp('(import)|(library)|(part)');
const String _blockCommentStart = '/*';
const String _blockCommentEnd = '*/';
/// The first language version where null safety was available by default.
final LanguageVersion nullSafeVersion = LanguageVersion(2, 12);
LanguageVersion? _currentLanguageVersion;
/// Lookup the current Dart language version.
LanguageVersion currentLanguageVersion(FileSystem fileSystem, String flutterRoot) {
if (_currentLanguageVersion != null) {
return _currentLanguageVersion!;
}
// Either reading the file or parsing the version could fail on a corrupt Dart SDK.
// let it crash so it shows up in crash logging.
final File versionFile = fileSystem.file(fileSystem.path.join(flutterRoot, 'bin', 'cache', 'dart-sdk', 'version'));
if (!versionFile.existsSync() && _inUnitTest()) {
return LanguageVersion(2, 12);
}
final Version version = Version.parse(versionFile.readAsStringSync())!;
return _currentLanguageVersion = LanguageVersion(version.major, version.minor);
}
// Whether the tool is executing in a unit test.
bool _inUnitTest() {
return Zone.current[#test.declarer] != null;
}
/// Attempts to read the language version of a dart [file].
///
/// If this is not present, falls back to the language version defined in
/// [package]. If [package] is not provided and there is no
/// language version header, returns 2.12. This does not specifically check
/// for language declarations other than library, part, or import.
///
/// The specification for the language version tag is defined at:
/// https://github.com/dart-lang/language/blob/master/accepted/future-releases/language-versioning/feature-specification.md#individual-library-language-version-override
LanguageVersion determineLanguageVersion(File file, Package? package, String flutterRoot) {
int blockCommentDepth = 0;
// If reading the file fails, default to a null-safe version. The
// command will likely fail later in the process with a better error
// message.
List<String> lines;
try {
lines = file.readAsLinesSync();
} on FileSystemException {
return currentLanguageVersion(file.fileSystem, flutterRoot);
}
for (final String line in lines) {
final String trimmedLine = line.trim();
if (trimmedLine.isEmpty) {
continue;
}
// Check for the start or end of a block comment. Within a block
// comment, all language version declarations are ignored. Block
// comments can be nested, and the start or end may occur on
// the same line. This does not handle the case of invalid
// block comment combinations like `*/ /*` since that will cause
// a compilation error anyway.
bool sawBlockComment = false;
final int startMatches = _blockCommentStart.allMatches(trimmedLine).length;
final int endMatches = _blockCommentEnd.allMatches(trimmedLine).length;
if (startMatches > 0) {
blockCommentDepth += startMatches;
sawBlockComment = true;
}
if (endMatches > 0) {
blockCommentDepth -= endMatches;
sawBlockComment = true;
}
if (blockCommentDepth != 0 || sawBlockComment) {
continue;
}
// Check for a match with the language version.
final Match? match = _languageVersion.matchAsPrefix(trimmedLine);
if (match != null) {
final String rawMajor = match.group(1) ?? '';
final String rawMinor = match.group(2) ?? '';
try {
final int major = int.parse(rawMajor);
final int minor = int.parse(rawMinor);
return LanguageVersion(major, minor);
} on FormatException {
// Language comment was invalid in a way that the regexp did not
// anticipate.
break;
}
}
// Check for a declaration which ends the search for a language
// version.
if (_declarationEnd.matchAsPrefix(trimmedLine) != null) {
break;
}
}
// If the language version cannot be found, use the package version.
if (package != null) {
return package.languageVersion ?? currentLanguageVersion(file.fileSystem, flutterRoot);
}
// Default to current version.
return currentLanguageVersion(file.fileSystem, flutterRoot);
}
| flutter/packages/flutter_tools/lib/src/dart/language_version.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/dart/language_version.dart",
"repo_id": "flutter",
"token_count": 1412
} | 778 |
// 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/bot_detector.dart';
import 'base/common.dart';
import 'base/io.dart' as io;
import 'base/logger.dart';
import 'convert.dart';
import 'resident_runner.dart';
/// An implementation of the devtools launcher that uses `pub global activate` to
/// start a server instance.
class DevtoolsServerLauncher extends DevtoolsLauncher {
DevtoolsServerLauncher({
required ProcessManager processManager,
required String dartExecutable,
required Logger logger,
required BotDetector botDetector,
}) : _processManager = processManager,
_dartExecutable = dartExecutable,
_logger = logger,
_botDetector = botDetector;
final ProcessManager _processManager;
final String _dartExecutable;
final Logger _logger;
final BotDetector _botDetector;
final Completer<void> _processStartCompleter = Completer<void>();
io.Process? _devToolsProcess;
bool _devToolsProcessKilled = false;
@visibleForTesting
Future<void>? devToolsProcessExit;
static final RegExp _serveDevToolsPattern =
RegExp(r'Serving DevTools at ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+?)\.?$');
@override
Future<void> get processStart => _processStartCompleter.future;
@override
Future<void> launch(Uri? vmServiceUri, {List<String>? additionalArguments}) async {
// Place this entire method in a try/catch that swallows exceptions because
// this method is guaranteed not to return a Future that throws.
try {
_devToolsProcess = await _processManager.start(<String>[
_dartExecutable,
'devtools',
'--no-launch-browser',
if (vmServiceUri != null) '--vm-uri=$vmServiceUri',
...?additionalArguments,
]);
_processStartCompleter.complete();
final Completer<Uri> completer = Completer<Uri>();
_devToolsProcess!.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((String line) {
final Match? match = _serveDevToolsPattern.firstMatch(line);
if (match != null) {
final String url = match[1]!;
completer.complete(Uri.parse(url));
}
});
_devToolsProcess!.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(_logger.printError);
final bool runningOnBot = await _botDetector.isRunningOnBot;
devToolsProcessExit = _devToolsProcess!.exitCode.then(
(int exitCode) {
if (!_devToolsProcessKilled && runningOnBot) {
throwToolExit('DevTools process failed: exitCode=$exitCode');
}
}
);
devToolsUrl = await completer.future;
} on Exception catch (e, st) {
_logger.printError('Failed to launch DevTools: $e', stackTrace: st);
}
}
@override
Future<DevToolsServerAddress?> serve() async {
if (activeDevToolsServer == null) {
await launch(null);
}
return activeDevToolsServer;
}
@override
Future<void> close() async {
if (devToolsUrl != null) {
devToolsUrl = null;
}
if (_devToolsProcess != null) {
_devToolsProcessKilled = true;
_devToolsProcess!.kill();
}
}
}
| flutter/packages/flutter_tools/lib/src/devtools_launcher.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/devtools_launcher.dart",
"repo_id": "flutter",
"token_count": 1327
} | 779 |
// 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:file/file.dart';
import 'package:process/process.dart';
import '../base/common.dart';
import '../base/logger.dart';
import '../base/process.dart';
import '../globals.dart' as globals;
import 'fuchsia_sdk.dart';
// Usage: ffx [-c <config>] [-e <env>] [-t <target>] [-T <timeout>] [-v] [<command>] [<args>]
// Fuchsia's developer tool
// Options:
// -c, --config override default configuration
// -e, --env override default environment settings
// -t, --target apply operations across single or multiple targets
// -T, --timeout override default proxy timeout
// -v, --verbose use verbose output
// --help display usage information
// Commands:
// config View and switch default and user configurations
// daemon Interact with/control the ffx daemon
// target Interact with a target device or emulator
// session Control the current session. See
// https://fuchsia.dev/fuchsia-src/concepts/session/introduction
// for details.
/// A simple wrapper for the Fuchsia SDK's 'ffx' tool.
class FuchsiaFfx {
FuchsiaFfx({
FuchsiaArtifacts? fuchsiaArtifacts,
Logger? logger,
ProcessManager? processManager,
}) : _fuchsiaArtifacts = fuchsiaArtifacts ?? globals.fuchsiaArtifacts,
_logger = logger ?? globals.logger,
_processUtils = ProcessUtils(
logger: logger ?? globals.logger,
processManager: processManager ?? globals.processManager);
final FuchsiaArtifacts? _fuchsiaArtifacts;
final Logger _logger;
final ProcessUtils _processUtils;
/// Returns a list of attached devices as a list of strings with entries
/// formatted as follows:
///
/// abcd::abcd:abc:abcd:abcd%qemu scare-cable-skip-joy
Future<List<String>?> list({Duration? timeout}) async {
final File? ffx = _fuchsiaArtifacts?.ffx;
if (ffx == null || !ffx.existsSync()) {
throwToolExit('Fuchsia ffx tool not found.');
}
final List<String> command = <String>[
ffx.path,
if (timeout != null) ...<String>['-T', '${timeout.inSeconds}'],
'target',
'list',
// TODO(akbiggs): Revert -f back to --format once we've verified that
// analytics spam is coming from here.
'-f',
's',
];
final RunResult result = await _processUtils.run(command);
if (result.exitCode != 0) {
_logger.printError('ffx failed: ${result.stderr}');
return null;
}
if (result.stderr.contains('No devices found')) {
return null;
}
return result.stdout.split('\n');
}
/// Returns the address of the named device.
///
/// The string [deviceName] should be the name of the device from the
/// 'list' command, e.g. 'scare-cable-skip-joy'.
Future<String?> resolve(String deviceName) async {
final File? ffx = _fuchsiaArtifacts?.ffx;
if (ffx == null || !ffx.existsSync()) {
throwToolExit('Fuchsia ffx tool not found.');
}
final List<String> command = <String>[
ffx.path,
'target',
'list',
'-f',
'a',
deviceName,
];
final RunResult result = await _processUtils.run(command);
if (result.exitCode != 0) {
_logger.printError('ffx failed: ${result.stderr}');
return null;
}
return result.stdout.trim();
}
/// Show information about the current session
///
/// Returns `null` if the command failed, which can be interpreted as there is
/// no usable session.
Future<String?> sessionShow() async {
final File? ffx = _fuchsiaArtifacts?.ffx;
if (ffx == null || !ffx.existsSync()) {
throwToolExit('Fuchsia ffx tool not found.');
}
final List<String> command = <String>[
ffx.path,
'session',
'show',
];
final RunResult result = await _processUtils.run(command);
if (result.exitCode != 0) {
_logger.printError('ffx failed: ${result.stderr}');
return null;
}
return result.stdout;
}
/// Add an element to the current session
///
/// [url] should be formatted as a Fuchsia-style package URL, e.g.:
/// fuchsia-pkg://fuchsia.com/flutter_gallery#meta/flutter_gallery.cmx
/// Returns true on success and false on failure.
Future<bool> sessionAdd(String url) async {
final File? ffx = _fuchsiaArtifacts?.ffx;
if (ffx == null || !ffx.existsSync()) {
throwToolExit('Fuchsia ffx tool not found.');
}
final List<String> command = <String>[
ffx.path,
'session',
'add',
url,
];
final RunResult result = await _processUtils.run(command);
if (result.exitCode != 0) {
_logger.printError('ffx failed: ${result.stderr}');
return false;
}
return true;
}
}
| flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_ffx.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_ffx.dart",
"repo_id": "flutter",
"token_count": 1928
} | 780 |
// 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/platform.dart';
import '../doctor_validator.dart';
import '../features.dart';
import '../macos/xcode.dart';
class IOSWorkflow implements Workflow {
const IOSWorkflow({
required Platform platform,
required FeatureFlags featureFlags,
required Xcode xcode,
}) : _platform = platform,
_featureFlags = featureFlags,
_xcode = xcode;
final Platform _platform;
final FeatureFlags _featureFlags;
final Xcode _xcode;
@override
bool get appliesToHostPlatform => _featureFlags.isIOSEnabled && _platform.isMacOS;
// We need xcode (+simctl) to list simulator devices, and libimobiledevice to list real devices.
@override
bool get canListDevices => appliesToHostPlatform && _xcode.isSimctlInstalled;
// We need xcode to launch simulator devices, and ios-deploy
// for real devices.
@override
bool get canLaunchDevices => appliesToHostPlatform && _xcode.isInstalledAndMeetsVersionCheck;
@override
bool get canListEmulators => false;
}
| flutter/packages/flutter_tools/lib/src/ios/ios_workflow.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/ios/ios_workflow.dart",
"repo_id": "flutter",
"token_count": 358
} | 781 |
// 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 '../build_system/build_system.dart';
import '../build_system/build_targets.dart';
import '../build_system/targets/common.dart';
import '../build_system/targets/dart_plugin_registrant.dart';
import '../build_system/targets/localizations.dart';
import '../build_system/targets/web.dart';
import '../web/compiler_config.dart';
class BuildTargetsImpl extends BuildTargets {
const BuildTargetsImpl();
@override
Target get copyFlutterBundle => const CopyFlutterBundle();
@override
Target get releaseCopyFlutterBundle => const ReleaseCopyFlutterBundle();
@override
Target get generateLocalizationsTarget => const GenerateLocalizationsTarget();
@override
Target get dartPluginRegistrantTarget => const DartPluginRegistrantTarget();
@override
Target webServiceWorker(FileSystem fileSystem, List<WebCompilerConfig> compileConfigs) =>
WebServiceWorker(fileSystem, compileConfigs);
}
| flutter/packages/flutter_tools/lib/src/isolated/build_targets.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/isolated/build_targets.dart",
"repo_id": "flutter",
"token_count": 341
} | 782 |
// 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:process/process.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/os.dart';
import '../base/platform.dart';
import '../build_info.dart';
import '../desktop_device.dart';
import '../device.dart';
import '../features.dart';
import '../project.dart';
import 'application_package.dart';
import 'build_linux.dart';
import 'linux_workflow.dart';
/// A device that represents a desktop Linux target.
class LinuxDevice extends DesktopDevice {
LinuxDevice({
required ProcessManager processManager,
required Logger logger,
required FileSystem fileSystem,
required OperatingSystemUtils operatingSystemUtils,
}) : _operatingSystemUtils = operatingSystemUtils,
_logger = logger,
super(
'linux',
platformType: PlatformType.linux,
ephemeral: false,
logger: logger,
processManager: processManager,
fileSystem: fileSystem,
operatingSystemUtils: operatingSystemUtils,
);
final OperatingSystemUtils _operatingSystemUtils;
final Logger _logger;
@override
bool isSupported() => true;
@override
String get name => 'Linux';
@override
late final Future<TargetPlatform> targetPlatform = () async {
if (_operatingSystemUtils.hostPlatform == HostPlatform.linux_x64) {
return TargetPlatform.linux_x64;
}
return TargetPlatform.linux_arm64;
}();
@override
bool isSupportedForProject(FlutterProject flutterProject) {
return flutterProject.linux.existsSync();
}
@override
Future<void> buildForDevice({
String? mainPath,
required BuildInfo buildInfo,
}) async {
await buildLinux(
FlutterProject.current().linux,
buildInfo,
target: mainPath,
targetPlatform: await targetPlatform,
logger: _logger,
);
}
@override
String executablePathForDevice(covariant LinuxApp package, BuildInfo buildInfo) {
return package.executable(buildInfo.mode);
}
}
class LinuxDevices extends PollingDeviceDiscovery {
LinuxDevices({
required Platform platform,
required FeatureFlags featureFlags,
required OperatingSystemUtils operatingSystemUtils,
required FileSystem fileSystem,
required ProcessManager processManager,
required Logger logger,
}) : _platform = platform,
_linuxWorkflow = LinuxWorkflow(
platform: platform,
featureFlags: featureFlags,
),
_fileSystem = fileSystem,
_logger = logger,
_processManager = processManager,
_operatingSystemUtils = operatingSystemUtils,
super('linux devices');
final Platform _platform;
final LinuxWorkflow _linuxWorkflow;
final ProcessManager _processManager;
final Logger _logger;
final FileSystem _fileSystem;
final OperatingSystemUtils _operatingSystemUtils;
@override
bool get supportsPlatform => _platform.isLinux;
@override
bool get canListAnything => _linuxWorkflow.canListDevices;
@override
Future<List<Device>> pollingGetDevices({ Duration? timeout }) async {
if (!canListAnything) {
return const <Device>[];
}
return <Device>[
LinuxDevice(
logger: _logger,
processManager: _processManager,
fileSystem: _fileSystem,
operatingSystemUtils: _operatingSystemUtils,
),
];
}
@override
Future<List<String>> getDiagnostics() async => const <String>[];
@override
List<String> get wellKnownIds => const <String>['linux'];
}
| flutter/packages/flutter_tools/lib/src/linux/linux_device.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/linux/linux_device.dart",
"repo_id": "flutter",
"token_count": 1260
} | 783 |
// 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/platform.dart';
import '../doctor_validator.dart';
import '../features.dart';
/// The macOS-specific implementation of a [Workflow].
class MacOSWorkflow implements Workflow {
const MacOSWorkflow({
required Platform platform,
required FeatureFlags featureFlags,
}) : _platform = platform,
_featureFlags = featureFlags;
final Platform _platform;
final FeatureFlags _featureFlags;
@override
bool get appliesToHostPlatform => _platform.isMacOS && _featureFlags.isMacOSEnabled;
@override
bool get canLaunchDevices => _platform.isMacOS && _featureFlags.isMacOSEnabled;
@override
bool get canListDevices => _platform.isMacOS && _featureFlags.isMacOSEnabled;
@override
bool get canListEmulators => false;
}
| flutter/packages/flutter_tools/lib/src/macos/macos_workflow.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/macos/macos_workflow.dart",
"repo_id": "flutter",
"token_count": 271
} | 784 |
// 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/config.dart';
import 'base/context.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/platform.dart';
import 'version.dart';
/// A class that represents global (non-project-specific) internal state that
/// must persist across tool invocations.
abstract class PersistentToolState {
factory PersistentToolState({
required FileSystem fileSystem,
required Logger logger,
required Platform platform,
}) = _DefaultPersistentToolState;
factory PersistentToolState.test({
required Directory directory,
required Logger logger,
}) = _DefaultPersistentToolState.test;
static PersistentToolState? get instance => context.get<PersistentToolState>();
/// Whether the welcome message should be redisplayed.
///
/// May give null if the value has not been set.
bool? get shouldRedisplayWelcomeMessage;
void setShouldRedisplayWelcomeMessage(bool value); // Enforced nonnull setter.
/// Returns the last active version for a given [channel].
///
/// If there was no active prior version, returns `null` instead.
String? lastActiveVersion(Channel channel);
/// Update the last active version for a given [channel].
void updateLastActiveVersion(String fullGitHash, Channel channel);
/// Return the hash of the last active license terms.
String? get lastActiveLicenseTermsHash;
void setLastActiveLicenseTermsHash(String value); // Enforced nonnull setter.
/// Whether this client was already determined to be or not be a bot.
bool? get isRunningOnBot;
void setIsRunningOnBot(bool value); // Enforced nonnull setter.
}
class _DefaultPersistentToolState implements PersistentToolState {
_DefaultPersistentToolState({
required FileSystem fileSystem,
required Logger logger,
required Platform platform,
}) : _config = Config(
_kFileName,
fileSystem: fileSystem,
logger: logger,
platform: platform,
);
@visibleForTesting
_DefaultPersistentToolState.test({
required Directory directory,
required Logger logger,
}) : _config = Config.test(
name: _kFileName,
directory: directory,
logger: logger,
);
static const String _kFileName = 'tool_state';
static const String _kRedisplayWelcomeMessage = 'redisplay-welcome-message';
static const Map<Channel, String> _lastActiveVersionKeys = <Channel,String>{
Channel.master: 'last-active-master-version',
Channel.main: 'last-active-main-version',
Channel.beta: 'last-active-beta-version',
Channel.stable: 'last-active-stable-version',
};
static const String _kBotKey = 'is-bot';
static const String _kLicenseHash = 'license-hash';
final Config _config;
@override
bool? get shouldRedisplayWelcomeMessage {
return _config.getValue(_kRedisplayWelcomeMessage) as bool?;
}
@override
void setShouldRedisplayWelcomeMessage(bool value) {
_config.setValue(_kRedisplayWelcomeMessage, value);
}
@override
String? lastActiveVersion(Channel channel) {
final String? versionKey = _versionKeyFor(channel);
assert(versionKey != null);
return _config.getValue(versionKey!) as String?;
}
@override
void updateLastActiveVersion(String fullGitHash, Channel channel) {
final String? versionKey = _versionKeyFor(channel);
assert(versionKey != null);
_config.setValue(versionKey!, fullGitHash);
}
@override
String? get lastActiveLicenseTermsHash => _config.getValue(_kLicenseHash) as String?;
@override
void setLastActiveLicenseTermsHash(String value) {
_config.setValue(_kLicenseHash, value);
}
String? _versionKeyFor(Channel channel) {
return _lastActiveVersionKeys[channel];
}
@override
bool? get isRunningOnBot => _config.getValue(_kBotKey) as bool?;
@override
void setIsRunningOnBot(bool value) {
_config.setValue(_kBotKey, value);
}
}
| flutter/packages/flutter_tools/lib/src/persistent_tool_state.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/persistent_tool_state.dart",
"repo_id": "flutter",
"token_count": 1243
} | 785 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.