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';
import 'gesture_tester.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testGesture('GestureArenaTeam rejection test', (GestureTester tester) {
final GestureArenaTeam team = GestureArenaTeam();
final HorizontalDragGestureRecognizer horizontalDrag = HorizontalDragGestureRecognizer()..team = team;
final VerticalDragGestureRecognizer verticalDrag = VerticalDragGestureRecognizer()..team = team;
final TapGestureRecognizer tap = TapGestureRecognizer();
expect(horizontalDrag.team, equals(team));
expect(verticalDrag.team, equals(team));
expect(tap.team, isNull);
final List<String> log = <String>[];
horizontalDrag.onStart = (DragStartDetails details) { log.add('horizontal-drag-start'); };
verticalDrag.onStart = (DragStartDetails details) { log.add('vertical-drag-start'); };
tap.onTap = () { log.add('tap'); };
void test(Offset delta) {
const Offset origin = Offset(10.0, 10.0);
final TestPointer pointer = TestPointer(5);
final PointerDownEvent down = pointer.down(origin);
horizontalDrag.addPointer(down);
verticalDrag.addPointer(down);
tap.addPointer(down);
expect(log, isEmpty);
tester.closeArena(5);
expect(log, isEmpty);
tester.route(down);
expect(log, isEmpty);
tester.route(pointer.move(origin + delta));
tester.route(pointer.up());
}
test(Offset.zero);
expect(log, <String>['tap']);
log.clear();
test(const Offset(0.0, 30.0));
expect(log, <String>['vertical-drag-start']);
log.clear();
horizontalDrag.dispose();
verticalDrag.dispose();
tap.dispose();
});
testGesture('GestureArenaTeam captain', (GestureTester tester) {
final GestureArenaTeam team = GestureArenaTeam();
final PassiveGestureRecognizer captain = PassiveGestureRecognizer()..team = team;
final HorizontalDragGestureRecognizer horizontalDrag = HorizontalDragGestureRecognizer()..team = team;
final VerticalDragGestureRecognizer verticalDrag = VerticalDragGestureRecognizer()..team = team;
final TapGestureRecognizer tap = TapGestureRecognizer();
team.captain = captain;
final List<String> log = <String>[];
captain.onGestureAccepted = () { log.add('captain accepted gesture'); };
horizontalDrag.onStart = (DragStartDetails details) { log.add('horizontal-drag-start'); };
verticalDrag.onStart = (DragStartDetails details) { log.add('vertical-drag-start'); };
tap.onTap = () { log.add('tap'); };
void test(Offset delta) {
const Offset origin = Offset(10.0, 10.0);
final TestPointer pointer = TestPointer(5);
final PointerDownEvent down = pointer.down(origin);
captain.addPointer(down);
horizontalDrag.addPointer(down);
verticalDrag.addPointer(down);
tap.addPointer(down);
expect(log, isEmpty);
tester.closeArena(5);
expect(log, isEmpty);
tester.route(down);
expect(log, isEmpty);
tester.route(pointer.move(origin + delta));
tester.route(pointer.up());
}
test(Offset.zero);
expect(log, <String>['tap']);
log.clear();
test(const Offset(0.0, 30.0));
expect(log, <String>['captain accepted gesture']);
log.clear();
horizontalDrag.dispose();
verticalDrag.dispose();
tap.dispose();
captain.dispose();
});
}
typedef GestureAcceptedCallback = void Function();
class PassiveGestureRecognizer extends OneSequenceGestureRecognizer {
GestureAcceptedCallback? onGestureAccepted;
@override
void addPointer(PointerDownEvent event) {
startTrackingPointer(event.pointer);
}
@override
String get debugDescription => 'passive';
@override
void didStopTrackingLastPointer(int pointer) {
resolve(GestureDisposition.rejected);
}
@override
void handleEvent(PointerEvent event) {
if (event is PointerUpEvent || event is PointerCancelEvent) {
stopTrackingPointer(event.pointer);
}
}
@override
void acceptGesture(int pointer) {
onGestureAccepted?.call();
}
@override
void rejectGesture(int pointer) { }
}
| flutter/packages/flutter/test/gestures/team_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/team_test.dart",
"repo_id": "flutter",
"token_count": 1600
} | 651 |
// 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';
import '../widgets/semantics_tester.dart';
import 'app_bar_utils.dart';
Widget buildSliverAppBarApp({
bool floating = false,
bool pinned = false,
double? collapsedHeight,
double? expandedHeight,
bool snap = false,
double toolbarHeight = kToolbarHeight,
}) {
return MaterialApp(
home: Scaffold(
body: DefaultTabController(
length: 3,
child: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar(
title: const Text('AppBar Title'),
floating: floating,
pinned: pinned,
collapsedHeight: collapsedHeight,
expandedHeight: expandedHeight,
toolbarHeight: toolbarHeight,
snap: snap,
bottom: TabBar(
tabs: <String>['A','B','C'].map<Widget>((String t) => Tab(text: 'TAB $t')).toList(),
),
),
SliverToBoxAdapter(
child: Container(
height: 1200.0,
color: Colors.orange[400],
),
),
],
),
),
),
);
}
void main() {
setUp(() {
debugResetSemanticsIdCounter();
});
testWidgets(
'SliverAppBar large & medium title respects automaticallyImplyLeading',
(WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/121511
const String title = 'AppBar Title';
const double titleSpacing = 16.0;
Widget buildWidget() {
return MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return Center(
child: FilledButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute<void>(
builder: (BuildContext context) {
return Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
const SliverAppBar.large(
title: Text(title),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
);
},
));
},
child: const Text('Go to page'),
),
);
}
),
),
);
}
await tester.pumpWidget(buildWidget());
expect(find.byType(BackButton), findsNothing);
await tester.tap(find.byType(FilledButton));
await tester.pumpAndSettle();
final Finder collapsedTitle = find.text(title).last;
final Offset backButtonOffset = tester.getTopRight(find.byType(BackButton));
final Offset titleOffset = tester.getTopLeft(collapsedTitle);
expect(titleOffset.dx, backButtonOffset.dx + titleSpacing);
});
testWidgets('SliverAppBar.medium with bottom widget', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/115091
const double collapsedAppBarHeight = 64;
const double expandedAppBarHeight = 112;
const double bottomHeight = 48;
const String title = 'Medium App Bar';
Widget buildWidget() {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.medium(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
),
title: const Text(title),
bottom: const TabBar(
tabs: <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
),
);
}
await tester.pumpWidget(buildWidget());
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight + bottomHeight);
final Finder expandedTitle = find.text(title).first;
final Offset expandedTitleOffset = tester.getBottomLeft(expandedTitle);
final Offset tabOffset = tester.getTopLeft(find.byType(TabBar));
expect(expandedTitleOffset.dy, tabOffset.dy);
// Scroll CustomScrollView to collapse SliverAppBar.
final ScrollController controller = primaryScrollController(tester);
controller.jumpTo(160);
await tester.pumpAndSettle();
expect(appBarHeight(tester), collapsedAppBarHeight + bottomHeight);
});
testWidgets('SliverAppBar.large with bottom widget', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/115091
const double collapsedAppBarHeight = 64;
const double expandedAppBarHeight = 152;
const double bottomHeight = 48;
const String title = 'Large App Bar';
Widget buildWidget() {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.large(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
),
title: const Text(title),
bottom: const TabBar(
tabs: <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
),
);
}
await tester.pumpWidget(buildWidget());
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight + bottomHeight);
final Finder expandedTitle = find.text(title).first;
final Offset expandedTitleOffset = tester.getBottomLeft(expandedTitle);
final Offset tabOffset = tester.getTopLeft(find.byType(TabBar));
expect(expandedTitleOffset.dy, tabOffset.dy);
// Scroll CustomScrollView to collapse SliverAppBar.
final ScrollController controller = primaryScrollController(tester);
controller.jumpTo(200);
await tester.pumpAndSettle();
expect(appBarHeight(tester), collapsedAppBarHeight + bottomHeight);
});
testWidgets('SliverAppBar.medium expanded title has upper limit on text scaling', (WidgetTester tester) async {
const String title = 'Medium AppBar';
Widget buildAppBar({double textScaleFactor = 1.0}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor,
maxScaleFactor: textScaleFactor,
child: Material(
child: CustomScrollView(
slivers: <Widget>[
const SliverAppBar.medium(
title: Text(title),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
),
);
}
await tester.pumpWidget(buildAppBar());
final Finder expandedTitle = find.text(title).first;
expect(tester.getRect(expandedTitle).height, 32.0);
verifyTextNotClipped(expandedTitle, tester);
await tester.pumpWidget(buildAppBar(textScaleFactor: 2.0));
expect(tester.getRect(expandedTitle).height, 43.0);
verifyTextNotClipped(expandedTitle, tester);
await tester.pumpWidget(buildAppBar(textScaleFactor: 3.0));
expect(tester.getRect(expandedTitle).height, 43.0);
verifyTextNotClipped(expandedTitle, tester);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('SliverAppBar.large expanded title has upper limit on text scaling', (WidgetTester tester) async {
const String title = 'Large AppBar';
Widget buildAppBar({double textScaleFactor = 1.0}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor,
maxScaleFactor: textScaleFactor,
child: Material(
child: CustomScrollView(
slivers: <Widget>[
const SliverAppBar.large(
title: Text(title, maxLines: 1),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
),
);
}
await tester.pumpWidget(buildAppBar());
final Finder expandedTitle = find.text(title).first;
expect(tester.getRect(expandedTitle).height, 36.0);
await tester.pumpWidget(buildAppBar(textScaleFactor: 2.0));
expect(tester.getRect(expandedTitle).height, closeTo(48.0, 0.1));
await tester.pumpWidget(buildAppBar(textScaleFactor: 3.0));
expect(tester.getRect(expandedTitle).height, closeTo(48.0, 0.1));
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('SliverAppBar.medium expanded title position is adjusted with textScaleFactor', (WidgetTester tester) async {
const String title = 'Medium AppBar';
Widget buildAppBar({double textScaleFactor = 1.0}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor,
maxScaleFactor: textScaleFactor,
child: Material(
child: CustomScrollView(
slivers: <Widget>[
const SliverAppBar.medium(
title: Text(title, maxLines: 1),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
),
);
}
await tester.pumpWidget(buildAppBar());
final Finder expandedTitle = find.text(title).first;
expect(tester.getBottomLeft(expandedTitle).dy, 96.0);
verifyTextNotClipped(expandedTitle, tester);
await tester.pumpWidget(buildAppBar(textScaleFactor: 2.0));
expect(tester.getBottomLeft(expandedTitle).dy, 107.0);
verifyTextNotClipped(expandedTitle, tester);
await tester.pumpWidget(buildAppBar(textScaleFactor: 3.0));
expect(tester.getBottomLeft(expandedTitle).dy, 107.0);
verifyTextNotClipped(expandedTitle, tester);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('SliverAppBar.large expanded title position is adjusted with textScaleFactor', (WidgetTester tester) async {
const String title = 'Large AppBar';
Widget buildAppBar({double textScaleFactor = 1.0}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor,
maxScaleFactor: textScaleFactor,
child: Material(
child: CustomScrollView(
slivers: <Widget>[
const SliverAppBar.large(
title: Text(title, maxLines: 1),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
),
);
}
await tester.pumpWidget(buildAppBar());
final Finder expandedTitle = find.text(title).first;
final RenderSliver renderSliverAppBar = tester.renderObject(find.byType(SliverAppBar));
expect(
tester.getBottomLeft(expandedTitle).dy,
renderSliverAppBar.geometry!.scrollExtent - 28.0,
reason: 'bottom padding of a large expanded title should be 28.',
);
verifyTextNotClipped(expandedTitle, tester);
await tester.pumpWidget(buildAppBar(textScaleFactor: 2.0));
expect(
tester.getBottomLeft(expandedTitle).dy,
renderSliverAppBar.geometry!.scrollExtent - 28.0,
reason: 'bottom padding of a large expanded title should be 28.',
);
verifyTextNotClipped(expandedTitle, tester);
// The bottom padding of the expanded title needs to be reduced for it to be
// fully visible.
await tester.pumpWidget(buildAppBar(textScaleFactor: 3.0));
expect(tester.getBottomLeft(expandedTitle).dy, 124.0);
verifyTextNotClipped(expandedTitle, tester);
});
testWidgets(
'SliverAppBar.medium collapsed title does not overlap with leading/actions widgets',
(WidgetTester tester) async {
const String title = 'Medium SliverAppBar Very Long Title';
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 200),
sliver: SliverAppBar.medium(
leading: IconButton(
icon: const Icon(Icons.menu),
onPressed: () {},
),
title: const Text(title, maxLines: 1),
centerTitle: true,
actions: const <Widget>[
Icon(Icons.search),
Icon(Icons.sort),
Icon(Icons.more_vert),
],
),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
));
// Scroll to collapse the SliverAppBar.
final ScrollController controller = primaryScrollController(tester);
controller.jumpTo(45);
await tester.pumpAndSettle();
final Offset leadingOffset = tester.getTopRight(find.byIcon(Icons.menu));
Offset titleOffset = tester.getTopLeft(find.text(title).last);
// The title widget should be to the right of the leading widget.
expect(titleOffset.dx, greaterThan(leadingOffset.dx));
titleOffset = tester.getTopRight(find.text(title).last);
final Offset searchOffset = tester.getTopLeft(find.byIcon(Icons.search));
// The title widget should be to the left of the search icon.
expect(titleOffset.dx, lessThan(searchOffset.dx));
});
testWidgets(
'SliverAppBar.large collapsed title does not overlap with leading/actions widgets',
(WidgetTester tester) async {
const String title = 'Large SliverAppBar Very Long Title';
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 200),
sliver: SliverAppBar.large(
leading: IconButton(
icon: const Icon(Icons.menu),
onPressed: () {},
),
title: const Text(title, maxLines: 1),
centerTitle: true,
actions: const <Widget>[
Icon(Icons.search),
Icon(Icons.sort),
Icon(Icons.more_vert),
],
),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
));
// Scroll to collapse the SliverAppBar.
final ScrollController controller = primaryScrollController(tester);
controller.jumpTo(45);
await tester.pumpAndSettle();
final Offset leadingOffset = tester.getTopRight(find.byIcon(Icons.menu));
Offset titleOffset = tester.getTopLeft(find.text(title).last);
// The title widget should be to the right of the leading widget.
expect(titleOffset.dx, greaterThan(leadingOffset.dx));
titleOffset = tester.getTopRight(find.text(title).last);
final Offset searchOffset = tester.getTopLeft(find.byIcon(Icons.search));
// The title widget should be to the left of the search icon.
expect(titleOffset.dx, lessThan(searchOffset.dx));
});
testWidgets('SliverAppBar.medium respects title spacing', (WidgetTester tester) async {
const String title = 'Medium SliverAppBar Very Long Title';
const double titleSpacing = 16.0;
Widget buildWidget({double? titleSpacing, bool? centerTitle}) {
return MaterialApp(
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 200),
sliver: SliverAppBar.medium(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
),
title: const Text(title, maxLines: 1),
centerTitle: centerTitle,
titleSpacing: titleSpacing,
actions: <Widget>[
IconButton(onPressed: () {}, icon: const Icon(Icons.sort)),
IconButton(onPressed: () {}, icon: const Icon(Icons.more_vert)),
],
),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
);
}
await tester.pumpWidget(buildWidget());
final Finder collapsedTitle = find.text(title).last;
// Scroll to collapse the SliverAppBar.
ScrollController controller = primaryScrollController(tester);
controller.jumpTo(120);
await tester.pumpAndSettle();
// By default, title widget should be to the right of the
// leading widget and title spacing should be respected.
Offset titleOffset = tester.getTopLeft(collapsedTitle);
Offset iconButtonOffset = tester.getTopRight(find.ancestor(of: find.widgetWithIcon(IconButton, Icons.menu), matching: find.byType(ConstrainedBox)));
expect(titleOffset.dx, iconButtonOffset.dx + titleSpacing);
await tester.pumpWidget(buildWidget(centerTitle: true));
// Scroll to collapse the SliverAppBar.
controller = primaryScrollController(tester);
controller.jumpTo(120);
await tester.pumpAndSettle();
// By default, title widget should be to the left of the first
// trailing widget and title spacing should be respected.
titleOffset = tester.getTopRight(collapsedTitle);
iconButtonOffset = tester.getTopLeft(find.widgetWithIcon(IconButton, Icons.sort));
expect(titleOffset.dx, iconButtonOffset.dx - titleSpacing);
// Test custom title spacing, set to 0.0.
await tester.pumpWidget(buildWidget(titleSpacing: 0.0));
// Scroll to collapse the SliverAppBar.
controller = primaryScrollController(tester);
controller.jumpTo(120);
await tester.pumpAndSettle();
// The title widget should be to the right of the leading
// widget with no spacing.
titleOffset = tester.getTopLeft(collapsedTitle);
iconButtonOffset = tester.getTopRight(find.ancestor(of: find.widgetWithIcon(IconButton, Icons.menu), matching: find.byType(ConstrainedBox)));
expect(titleOffset.dx, iconButtonOffset.dx);
// Set centerTitle to true so the end of the title can reach
// the action widgets.
await tester.pumpWidget(buildWidget(titleSpacing: 0.0, centerTitle: true));
// Scroll to collapse the SliverAppBar.
controller = primaryScrollController(tester);
controller.jumpTo(120);
await tester.pumpAndSettle();
// The title widget should be to the left of the first
// leading widget with no spacing.
titleOffset = tester.getTopRight(collapsedTitle);
iconButtonOffset = tester.getTopLeft(find.widgetWithIcon(IconButton, Icons.sort));
expect(titleOffset.dx, iconButtonOffset.dx);
});
testWidgets('SliverAppBar.large respects title spacing', (WidgetTester tester) async {
const String title = 'Large SliverAppBar Very Long Title';
const double titleSpacing = 16.0;
Widget buildWidget({double? titleSpacing, bool? centerTitle}) {
return MaterialApp(
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 200),
sliver: SliverAppBar.large(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
),
title: const Text(title, maxLines: 1),
centerTitle: centerTitle,
titleSpacing: titleSpacing,
actions: <Widget>[
IconButton(onPressed: () {}, icon: const Icon(Icons.sort)),
IconButton(onPressed: () {}, icon: const Icon(Icons.more_vert)),
],
),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
);
}
await tester.pumpWidget(buildWidget());
final Finder collapsedTitle = find.text(title).last;
// Scroll to collapse the SliverAppBar.
ScrollController controller = primaryScrollController(tester);
controller.jumpTo(160);
await tester.pumpAndSettle();
// By default, title widget should be to the right of the leading
// widget and title spacing should be respected.
Offset titleOffset = tester.getTopLeft(collapsedTitle);
Offset iconButtonOffset = tester.getTopRight(find.ancestor(of: find.widgetWithIcon(IconButton, Icons.menu), matching: find.byType(ConstrainedBox)));
expect(titleOffset.dx, iconButtonOffset.dx + titleSpacing);
await tester.pumpWidget(buildWidget(centerTitle: true));
// Scroll to collapse the SliverAppBar.
controller = primaryScrollController(tester);
controller.jumpTo(160);
await tester.pumpAndSettle();
// By default, title widget should be to the left of the
// leading widget and title spacing should be respected.
titleOffset = tester.getTopRight(collapsedTitle);
iconButtonOffset = tester.getTopLeft(find.widgetWithIcon(IconButton, Icons.sort));
expect(titleOffset.dx, iconButtonOffset.dx - titleSpacing);
// Test custom title spacing, set to 0.0.
await tester.pumpWidget(buildWidget(titleSpacing: 0.0));
controller = primaryScrollController(tester);
controller.jumpTo(160);
await tester.pumpAndSettle();
// The title widget should be to the right of the leading
// widget with no spacing.
titleOffset = tester.getTopLeft(collapsedTitle);
iconButtonOffset = tester.getTopRight(find.ancestor(of: find.widgetWithIcon(IconButton, Icons.menu), matching: find.byType(ConstrainedBox)));
expect(titleOffset.dx, iconButtonOffset.dx);
// Set centerTitle to true so the end of the title can reach
// the action widgets.
await tester.pumpWidget(buildWidget(titleSpacing: 0.0, centerTitle: true));
// Scroll to collapse the SliverAppBar.
controller = primaryScrollController(tester);
controller.jumpTo(160);
await tester.pumpAndSettle();
// The title widget should be to the left of the first
// leading widget with no spacing.
titleOffset = tester.getTopRight(collapsedTitle);
iconButtonOffset = tester.getTopLeft(find.widgetWithIcon(IconButton, Icons.sort));
expect(titleOffset.dx, iconButtonOffset.dx);
});
testWidgets(
'SliverAppBar.medium without the leading widget updates collapsed title padding',
(WidgetTester tester) async {
const String title = 'Medium SliverAppBar Title';
const double leadingPadding = 56.0;
const double titleSpacing = 16.0;
Widget buildWidget({ bool showLeading = true }) {
return MaterialApp(
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.medium(
automaticallyImplyLeading: false,
leading: showLeading
? IconButton(
icon: const Icon(Icons.menu),
onPressed: () {},
)
: null,
title: const Text(title),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
);
}
await tester.pumpWidget(buildWidget());
final Finder collapsedTitle = find.text(title).last;
// Scroll to collapse the SliverAppBar.
ScrollController controller = primaryScrollController(tester);
controller.jumpTo(45);
await tester.pumpAndSettle();
// If the leading widget is present, the title widget should be to the
// right of the leading widget and title spacing should be respected.
Offset titleOffset = tester.getTopLeft(collapsedTitle);
expect(titleOffset.dx, leadingPadding + titleSpacing);
// Hide the leading widget.
await tester.pumpWidget(buildWidget(showLeading: false));
// Scroll to collapse the SliverAppBar.
controller = primaryScrollController(tester);
controller.jumpTo(45);
await tester.pumpAndSettle();
// If the leading widget is not present, the title widget will
// only have the default title spacing.
titleOffset = tester.getTopLeft(collapsedTitle);
expect(titleOffset.dx, titleSpacing);
});
testWidgets(
'SliverAppBar.large without the leading widget updates collapsed title padding',
(WidgetTester tester) async {
const String title = 'Large SliverAppBar Title';
const double leadingPadding = 56.0;
const double titleSpacing = 16.0;
Widget buildWidget({ bool showLeading = true }) {
return MaterialApp(
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.large(
automaticallyImplyLeading: false,
leading: showLeading
? IconButton(
icon: const Icon(Icons.menu),
onPressed: () {},
)
: null,
title: const Text(title),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
);
}
await tester.pumpWidget(buildWidget());
final Finder collapsedTitle = find.text(title).last;
// Scroll CustomScrollView to collapse SliverAppBar.
ScrollController controller = primaryScrollController(tester);
controller.jumpTo(45);
await tester.pumpAndSettle();
// If the leading widget is present, the title widget should be to the
// right of the leading widget and title spacing should be respected.
Offset titleOffset = tester.getTopLeft(collapsedTitle);
expect(titleOffset.dx, leadingPadding + titleSpacing);
// Hide the leading widget.
await tester.pumpWidget(buildWidget(showLeading: false));
// Scroll to collapse the SliverAppBar.
controller = primaryScrollController(tester);
controller.jumpTo(45);
await tester.pumpAndSettle();
// If the leading widget is not present, the title widget will
// only have the default title spacing.
titleOffset = tester.getTopLeft(collapsedTitle);
expect(titleOffset.dx, titleSpacing);
});
group('MaterialStateColor scrolledUnder', () {
const double collapsedHeight = kToolbarHeight;
const double expandedHeight = 200.0;
const Color scrolledColor = Color(0xff00ff00);
const Color defaultColor = Color(0xff0000ff);
Widget buildSliverApp({
required double contentHeight,
bool reverse = false,
bool includeFlexibleSpace = false,
}) {
return MaterialApp(
home: Scaffold(
body: CustomScrollView(
reverse: reverse,
slivers: <Widget>[
SliverAppBar(
elevation: 0,
backgroundColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
return states.contains(MaterialState.scrolledUnder)
? scrolledColor
: defaultColor;
}),
expandedHeight: expandedHeight,
pinned: true,
flexibleSpace: includeFlexibleSpace
? const FlexibleSpaceBar(title: Text('SliverAppBar'))
: null,
),
SliverList(
delegate: SliverChildListDelegate(
<Widget>[
Container(height: contentHeight, color: Colors.teal),
],
),
),
],
),
),
);
}
testWidgets('backgroundColor', (WidgetTester tester) async {
await tester.pumpWidget(
buildSliverApp(contentHeight: 1200.0)
);
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
TestGesture gesture = await tester.startGesture(const Offset(50.0, 400.0));
await gesture.moveBy(const Offset(0.0, -expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), scrolledColor);
expect(tester.getSize(findAppBarMaterial()).height, collapsedHeight);
gesture = await tester.startGesture(const Offset(50.0, 300.0));
await gesture.moveBy(const Offset(0.0, expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
});
testWidgets('backgroundColor with FlexibleSpace', (WidgetTester tester) async {
await tester.pumpWidget(
buildSliverApp(contentHeight: 1200.0, includeFlexibleSpace: true)
);
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
TestGesture gesture = await tester.startGesture(const Offset(50.0, 400.0));
await gesture.moveBy(const Offset(0.0, -expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), scrolledColor);
expect(tester.getSize(findAppBarMaterial()).height, collapsedHeight);
gesture = await tester.startGesture(const Offset(50.0, 300.0));
await gesture.moveBy(const Offset(0.0, expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
});
testWidgets('backgroundColor - reverse', (WidgetTester tester) async {
await tester.pumpWidget(
buildSliverApp(contentHeight: 1200.0, reverse: true)
);
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
TestGesture gesture = await tester.startGesture(const Offset(50.0, 400.0));
await gesture.moveBy(const Offset(0.0, expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), scrolledColor);
expect(tester.getSize(findAppBarMaterial()).height, collapsedHeight);
gesture = await tester.startGesture(const Offset(50.0, 300.0));
await gesture.moveBy(const Offset(0.0, -expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
});
testWidgets('backgroundColor with FlexibleSpace - reverse', (WidgetTester tester) async {
await tester.pumpWidget(
buildSliverApp(
contentHeight: 1200.0,
reverse: true,
includeFlexibleSpace: true,
)
);
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
TestGesture gesture = await tester.startGesture(const Offset(50.0, 400.0));
await gesture.moveBy(const Offset(0.0, expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), scrolledColor);
expect(tester.getSize(findAppBarMaterial()).height, collapsedHeight);
gesture = await tester.startGesture(const Offset(50.0, 300.0));
await gesture.moveBy(const Offset(0.0, -expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
});
testWidgets('backgroundColor - not triggered in reverse for short content', (WidgetTester tester) async {
await tester.pumpWidget(
buildSliverApp(contentHeight: 200, reverse: true)
);
// In reverse, the content here is not long enough to scroll under the app
// bar.
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
final TestGesture gesture = await tester.startGesture(const Offset(50.0, 400.0));
await gesture.moveBy(const Offset(0.0, expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
});
testWidgets('backgroundColor with FlexibleSpace - not triggered in reverse for short content', (WidgetTester tester) async {
await tester.pumpWidget(
buildSliverApp(
contentHeight: 200,
reverse: true,
includeFlexibleSpace: true,
)
);
// In reverse, the content here is not long enough to scroll under the app
// bar.
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
final TestGesture gesture = await tester.startGesture(const Offset(50.0, 400.0));
await gesture.moveBy(const Offset(0.0, expandedHeight));
await gesture.up();
await tester.pumpAndSettle();
expect(getAppBarBackgroundColor(tester), defaultColor);
expect(tester.getSize(findAppBarMaterial()).height, expandedHeight);
});
});
testWidgets('SliverAppBar default configuration', (WidgetTester tester) async {
await tester.pumpWidget(buildSliverAppBarApp());
final ScrollController controller = primaryScrollController(tester);
expect(controller.offset, 0.0);
expect(find.byType(SliverAppBar), findsOneWidget);
final double initialAppBarHeight = appBarHeight(tester);
final double initialTabBarHeight = tabBarHeight(tester);
// Scroll the not-pinned appbar partially out of view
controller.jumpTo(50.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), initialAppBarHeight);
expect(tabBarHeight(tester), initialTabBarHeight);
// Scroll the not-pinned appbar out of view
controller.jumpTo(600.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsNothing);
expect(appBarHeight(tester), initialAppBarHeight);
expect(tabBarHeight(tester), initialTabBarHeight);
// Scroll the not-pinned appbar back into view
controller.jumpTo(0.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), initialAppBarHeight);
expect(tabBarHeight(tester), initialTabBarHeight);
});
testWidgets('SliverAppBar expandedHeight, pinned', (WidgetTester tester) async {
await tester.pumpWidget(buildSliverAppBarApp(
pinned: true,
expandedHeight: 128.0,
));
final ScrollController controller = primaryScrollController(tester);
expect(controller.offset, 0.0);
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), 128.0);
const double initialAppBarHeight = 128.0;
final double initialTabBarHeight = tabBarHeight(tester);
// Scroll the not-pinned appbar, collapsing the expanded height. At this
// point both the toolbar and the tabbar are visible.
controller.jumpTo(600.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(tabBarHeight(tester), initialTabBarHeight);
expect(appBarHeight(tester), lessThan(initialAppBarHeight));
expect(appBarHeight(tester), greaterThan(initialTabBarHeight));
// Scroll the not-pinned appbar back into view
controller.jumpTo(0.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), initialAppBarHeight);
expect(tabBarHeight(tester), initialTabBarHeight);
});
testWidgets('SliverAppBar expandedHeight, pinned and floating', (WidgetTester tester) async {
await tester.pumpWidget(buildSliverAppBarApp(
floating: true,
pinned: true,
expandedHeight: 128.0,
));
final ScrollController controller = primaryScrollController(tester);
expect(controller.offset, 0.0);
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), 128.0);
const double initialAppBarHeight = 128.0;
final double initialTabBarHeight = tabBarHeight(tester);
// Scroll the floating-pinned appbar, collapsing the expanded height. At this
// point only the tabBar is visible.
controller.jumpTo(600.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(tabBarHeight(tester), initialTabBarHeight);
expect(appBarHeight(tester), lessThan(initialAppBarHeight));
expect(appBarHeight(tester), initialTabBarHeight);
// Scroll the floating-pinned appbar back into view
controller.jumpTo(0.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), initialAppBarHeight);
expect(tabBarHeight(tester), initialTabBarHeight);
});
testWidgets('SliverAppBar expandedHeight, floating with snap:true', (WidgetTester tester) async {
await tester.pumpWidget(buildSliverAppBarApp(
floating: true,
snap: true,
expandedHeight: 128.0,
));
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarTop(tester), 0.0);
expect(appBarHeight(tester), 128.0);
expect(appBarBottom(tester), 128.0);
// Scroll to the middle of the list. The (floating) appbar is no longer visible.
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
position.jumpTo(256.00);
await tester.pumpAndSettle();
expect(find.byType(SliverAppBar), findsNothing);
expect(appBarTop(tester), lessThanOrEqualTo(-128.0));
// Drag the scrollable up and down. The app bar should not snap open, its
// height should just track the drag offset.
TestGesture gesture = await tester.startGesture(const Offset(50.0, 256.0));
await gesture.moveBy(const Offset(0.0, 128.0)); // drag the appbar all the way open
await tester.pump();
expect(appBarTop(tester), 0.0);
expect(appBarHeight(tester), 128.0);
await gesture.moveBy(const Offset(0.0, -50.0));
await tester.pump();
expect(appBarBottom(tester), 78.0); // 78 == 128 - 50
// Trigger the snap open animation: drag down and release
await gesture.moveBy(const Offset(0.0, 10.0));
await gesture.up();
// Now verify that the appbar is animating open
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
double bottom = appBarBottom(tester);
expect(bottom, greaterThan(88.0)); // 88 = 78 + 10
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(appBarBottom(tester), greaterThan(bottom));
// The animation finishes when the appbar is full height.
await tester.pumpAndSettle();
expect(appBarHeight(tester), 128.0);
// Now that the app bar is open, perform the same drag scenario
// in reverse: drag the appbar up and down and then trigger the
// snap closed animation.
gesture = await tester.startGesture(const Offset(50.0, 256.0));
await gesture.moveBy(const Offset(0.0, -128.0)); // drag the appbar closed
await tester.pump();
expect(appBarBottom(tester), 0.0);
await gesture.moveBy(const Offset(0.0, 100.0));
await tester.pump();
expect(appBarBottom(tester), 100.0);
// Trigger the snap close animation: drag upwards and release
await gesture.moveBy(const Offset(0.0, -10.0));
await gesture.up();
// Now verify that the appbar is animating closed
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
bottom = appBarBottom(tester);
expect(bottom, lessThan(90.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(appBarBottom(tester), lessThan(bottom));
// The animation finishes when the appbar is off screen.
await tester.pumpAndSettle();
expect(appBarTop(tester), lessThanOrEqualTo(0.0));
expect(appBarBottom(tester), lessThanOrEqualTo(0.0));
});
testWidgets('SliverAppBar expandedHeight, floating and pinned with snap:true', (WidgetTester tester) async {
await tester.pumpWidget(buildSliverAppBarApp(
floating: true,
pinned: true,
snap: true,
expandedHeight: 128.0,
));
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarTop(tester), 0.0);
expect(appBarHeight(tester), 128.0);
expect(appBarBottom(tester), 128.0);
// Scroll to the middle of the list. The only the tab bar is visible
// because this is a pinned appbar.
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
position.jumpTo(256.0);
await tester.pumpAndSettle();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarTop(tester), 0.0);
expect(appBarHeight(tester), kTextTabBarHeight);
// Drag the scrollable up and down. The app bar should not snap open, the
// bottom of the appbar should just track the drag offset.
TestGesture gesture = await tester.startGesture(const Offset(50.0, 200.0));
await gesture.moveBy(const Offset(0.0, 100.0));
await tester.pump();
expect(appBarHeight(tester), 100.0);
await gesture.moveBy(const Offset(0.0, -25.0));
await tester.pump();
expect(appBarHeight(tester), 75.0);
// Trigger the snap animation: drag down and release
await gesture.moveBy(const Offset(0.0, 10.0));
await gesture.up();
// Now verify that the appbar is animating open
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
final double height = appBarHeight(tester);
expect(height, greaterThan(85.0));
expect(height, lessThan(128.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(appBarHeight(tester), greaterThan(height));
expect(appBarHeight(tester), lessThan(128.0));
// The animation finishes when the appbar is fully expanded
await tester.pumpAndSettle();
expect(appBarTop(tester), 0.0);
expect(appBarHeight(tester), 128.0);
expect(appBarBottom(tester), 128.0);
// Now that the appbar is fully expanded, Perform the same drag
// scenario in reverse: drag the appbar up and down and then trigger
// the snap closed animation.
gesture = await tester.startGesture(const Offset(50.0, 256.0));
await gesture.moveBy(const Offset(0.0, -128.0));
await tester.pump();
expect(appBarBottom(tester), kTextTabBarHeight);
await gesture.moveBy(const Offset(0.0, 100.0));
await tester.pump();
expect(appBarBottom(tester), 100.0);
// Trigger the snap close animation: drag upwards and release
await gesture.moveBy(const Offset(0.0, -10.0));
await gesture.up();
// Now verify that the appbar is animating closed
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
final double bottom = appBarBottom(tester);
expect(bottom, lessThan(90.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(appBarBottom(tester), lessThan(bottom));
// The animation finishes when the appbar shrinks back to its pinned height
await tester.pumpAndSettle();
expect(appBarTop(tester), lessThanOrEqualTo(0.0));
expect(appBarBottom(tester), kTextTabBarHeight);
});
testWidgets('SliverAppBar expandedHeight, collapsedHeight', (WidgetTester tester) async {
const double expandedAppBarHeight = 400.0;
const double collapsedAppBarHeight = 200.0;
await tester.pumpWidget(buildSliverAppBarApp(
collapsedHeight: collapsedAppBarHeight,
expandedHeight: expandedAppBarHeight,
));
final ScrollController controller = primaryScrollController(tester);
expect(controller.offset, 0.0);
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
final double initialTabBarHeight = tabBarHeight(tester);
// Scroll the not-pinned appbar partially out of view.
controller.jumpTo(50.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight - 50.0);
expect(tabBarHeight(tester), initialTabBarHeight);
// Scroll the not-pinned appbar out of view, to its collapsed height.
controller.jumpTo(600.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsNothing);
expect(appBarHeight(tester), collapsedAppBarHeight + initialTabBarHeight);
expect(tabBarHeight(tester), initialTabBarHeight);
// Scroll the not-pinned appbar back into view.
controller.jumpTo(0.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tabBarHeight(tester), initialTabBarHeight);
});
testWidgets('Material3 - SliverAppBar.medium defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
const double collapsedAppBarHeight = 64;
const double expandedAppBarHeight = 112;
await tester.pumpWidget(MaterialApp(
theme: theme,
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
const SliverAppBar.medium(
title: Text('AppBar Title'),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
));
final ScrollController controller = primaryScrollController(tester);
// There are two widgets for the title. The first title is a larger version
// that is shown at the bottom when the app bar is expanded. It scrolls under
// the main row until it is completely hidden and then the first title is
// faded in. The last is the title on the mainrow with the icons. It is
// transparent when the app bar is expanded, and opaque when it is collapsed.
final Finder expandedTitle = find.text('AppBar Title').first;
final Finder expandedTitleClip = find.ancestor(
of: expandedTitle,
matching: find.byType(ClipRect),
).first;
final Finder collapsedTitle = find.text('AppBar Title').last;
final Finder collapsedTitleOpacity = find.ancestor(
of: collapsedTitle,
matching: find.byType(AnimatedOpacity),
);
// Default, fully expanded app bar.
expect(controller.offset, 0);
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight);
// Test the expanded title is positioned correctly.
final Offset titleOffset = tester.getBottomLeft(expandedTitle);
expect(titleOffset.dx, 16.0);
if (!kIsWeb || isCanvasKit) {
expect(titleOffset.dy, 96.0);
}
verifyTextNotClipped(expandedTitle, tester);
// Test the expanded title default color.
expect(
tester.renderObject<RenderParagraph>(expandedTitle).text.style!.color,
theme.colorScheme.onSurface,
);
// Scroll the expanded app bar partially out of view.
controller.jumpTo(45);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight - 45);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight - 45);
// Scroll so that it is completely collapsed.
controller.jumpTo(600);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), collapsedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 1);
expect(tester.getSize(expandedTitleClip).height, 0);
// Scroll back to fully expanded.
controller.jumpTo(0);
await tester.pumpAndSettle();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight);
});
testWidgets('Material3 - SliverAppBar.large defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
const double collapsedAppBarHeight = 64;
const double expandedAppBarHeight = 152;
await tester.pumpWidget(MaterialApp(
theme: theme,
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
const SliverAppBar.large(
title: Text('AppBar Title'),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
));
final ScrollController controller = primaryScrollController(tester);
// There are two widgets for the title. The first title is a larger version
// that is shown at the bottom when the app bar is expanded. It scrolls under
// the main row until it is completely hidden and then the first title is
// faded in. The last is the title on the mainrow with the icons. It is
// transparent when the app bar is expanded, and opaque when it is collapsed.
final Finder expandedTitle = find.text('AppBar Title').first;
final Finder expandedTitleClip = find.ancestor(
of: expandedTitle,
matching: find.byType(ClipRect),
).first;
final Finder collapsedTitle = find.text('AppBar Title').last;
final Finder collapsedTitleOpacity = find.ancestor(
of: collapsedTitle,
matching: find.byType(AnimatedOpacity),
);
// Default, fully expanded app bar.
expect(controller.offset, 0);
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight);
// Test the expanded title is positioned correctly.
final Offset titleOffset = tester.getBottomLeft(expandedTitle);
expect(titleOffset.dx, 16.0);
final RenderSliver renderSliverAppBar = tester.renderObject(find.byType(SliverAppBar));
// The expanded title and the bottom padding fits in the flexible space.
expect(
titleOffset.dy,
renderSliverAppBar.geometry!.scrollExtent - 28.0,
reason: 'bottom padding of a large expanded title should be 28.',
);
verifyTextNotClipped(expandedTitle, tester);
// Test the expanded title default color.
expect(
tester.renderObject<RenderParagraph>(expandedTitle).text.style!.color,
theme.colorScheme.onSurface,
);
// Scroll the expanded app bar partially out of view.
controller.jumpTo(45);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight - 45);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight - 45);
// Scroll so that it is completely collapsed.
controller.jumpTo(600);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), collapsedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 1);
expect(tester.getSize(expandedTitleClip).height, 0);
// Scroll back to fully expanded.
controller.jumpTo(0);
await tester.pumpAndSettle();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight);
});
group('SliverAppBar elevation', () {
Widget buildSliverAppBar(bool forceElevated, {double? elevation, double? themeElevation}) {
return MaterialApp(
theme: ThemeData(
appBarTheme: AppBarTheme(
elevation: themeElevation,
scrolledUnderElevation: themeElevation,
),
),
home: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: const Text('Title'),
forceElevated: forceElevated,
elevation: elevation,
scrolledUnderElevation: elevation,
),
],
),
);
}
testWidgets('Respects forceElevated parameter', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/59158.
AppBar getAppBar() => tester.widget<AppBar>(find.byType(AppBar));
Material getMaterial() => tester.widget<Material>(find.byType(Material));
final bool useMaterial3 = ThemeData().useMaterial3;
// When forceElevated is off, SliverAppBar should not be elevated.
await tester.pumpWidget(buildSliverAppBar(false));
expect(getMaterial().elevation, 0.0);
// Default elevation should be used by the material, but
// the AppBar's elevation should not be specified by SliverAppBar.
// When useMaterial3 is true, and forceElevated is true, the default elevation
// should be the value of `scrolledUnderElevation` which is 3.0
await tester.pumpWidget(buildSliverAppBar(true));
expect(getMaterial().elevation, useMaterial3 ? 3.0 : 4.0);
expect(getAppBar().elevation, null);
// SliverAppBar should use the specified elevation.
await tester.pumpWidget(buildSliverAppBar(true, elevation: 8.0));
expect(getMaterial().elevation, 8.0);
});
testWidgets('Uses elevation of AppBarTheme by default', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/73525.
Material getMaterial() => tester.widget<Material>(find.byType(Material));
await tester.pumpWidget(buildSliverAppBar(false, themeElevation: 12.0));
expect(getMaterial().elevation, 0.0);
await tester.pumpWidget(buildSliverAppBar(true, themeElevation: 12.0));
expect(getMaterial().elevation, 12.0);
await tester.pumpWidget(buildSliverAppBar(true, elevation: 8.0, themeElevation: 12.0));
expect(getMaterial().elevation, 8.0);
});
});
group('SliverAppBar.forceMaterialTransparency', () {
Material getSliverAppBarMaterial(WidgetTester tester) {
return tester.widget<Material>(find
.descendant(of: find.byType(SliverAppBar), matching: find.byType(Material))
.first);
}
// Generates a MaterialApp with a SliverAppBar in a CustomScrollView.
// The first cell of the scroll view contains a button at its top, and is
// initially scrolled so that it is beneath the SliverAppBar.
(ScrollController, Widget) buildWidget({
required bool forceMaterialTransparency,
required VoidCallback onPressed
}) {
const double appBarHeight = 120;
final ScrollController controller = ScrollController(initialScrollOffset: appBarHeight);
return (
controller,
MaterialApp(
home: Scaffold(
body: CustomScrollView(
controller: controller,
slivers: <Widget>[
SliverAppBar(
collapsedHeight: appBarHeight,
expandedHeight: appBarHeight,
pinned: true,
elevation: 0,
backgroundColor: Colors.transparent,
forceMaterialTransparency: forceMaterialTransparency,
title: const Text('AppBar'),
),
SliverList(
delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
return SizedBox(
height: appBarHeight,
child: index == 0
? Align(
alignment: Alignment.topCenter,
child: TextButton(onPressed: onPressed, child: const Text('press')))
: const SizedBox(),
);
},
childCount: 20,
),
),
]),
),
),
);
}
testWidgets(
'forceMaterialTransparency == true allows gestures beneath the app bar', (WidgetTester tester) async {
bool buttonWasPressed = false;
final (ScrollController controller, Widget widget) = buildWidget(
forceMaterialTransparency:true,
onPressed:() { buttonWasPressed = true; },
);
await tester.pumpWidget(widget);
final Material material = getSliverAppBarMaterial(tester);
expect(material.type, MaterialType.transparency);
final Finder buttonFinder = find.byType(TextButton);
await tester.tap(buttonFinder);
await tester.pump();
expect(buttonWasPressed, isTrue);
controller.dispose();
});
testWidgets(
'forceMaterialTransparency == false does not allow gestures beneath the app bar', (WidgetTester tester) async {
// Set this, and tester.tap(warnIfMissed:false), to suppress
// errors/warning that the button is not hittable (which is expected).
WidgetController.hitTestWarningShouldBeFatal = false;
bool buttonWasPressed = false;
final (ScrollController controller, Widget widget) = buildWidget(
forceMaterialTransparency:false,
onPressed:() { buttonWasPressed = true; },
);
await tester.pumpWidget(widget);
final Material material = getSliverAppBarMaterial(tester);
expect(material.type, MaterialType.canvas);
final Finder buttonFinder = find.byType(TextButton);
await tester.tap(buttonFinder, warnIfMissed:false);
await tester.pump();
expect(buttonWasPressed, isFalse);
controller.dispose();
});
});
testWidgets('SliverAppBar positioning of leading and trailing widgets with top padding', (WidgetTester tester) async {
const MediaQueryData topPadding100 = MediaQueryData(padding: EdgeInsets.only(top: 100.0));
final Key leadingKey = UniqueKey();
final Key titleKey = UniqueKey();
final Key trailingKey = UniqueKey();
await tester.pumpWidget(
Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: Directionality(
textDirection: TextDirection.rtl,
child: MediaQuery(
data: topPadding100,
child: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar(
leading: Placeholder(key: leadingKey),
title: Placeholder(key: titleKey, fallbackHeight: kToolbarHeight),
actions: <Widget>[ Placeholder(key: trailingKey) ],
),
],
),
),
),
),
);
expect(tester.getTopLeft(find.byType(AppBar)), Offset.zero);
expect(tester.getTopLeft(find.byKey(leadingKey)), const Offset(800.0 - 56.0, 100.0));
expect(tester.getTopLeft(find.byKey(titleKey)), const Offset(416.0, 100.0));
expect(tester.getTopLeft(find.byKey(trailingKey)), const Offset(0.0, 100.0));
});
testWidgets('SliverAppBar positioning of leading and trailing widgets with bottom padding', (WidgetTester tester) async {
const MediaQueryData topPadding100 = MediaQueryData(padding: EdgeInsets.only(top: 100.0, bottom: 50.0));
final Key leadingKey = UniqueKey();
final Key titleKey = UniqueKey();
final Key trailingKey = UniqueKey();
await tester.pumpWidget(
Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: Directionality(
textDirection: TextDirection.rtl,
child: MediaQuery(
data: topPadding100,
child: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar(
leading: Placeholder(key: leadingKey),
title: Placeholder(key: titleKey),
actions: <Widget>[ Placeholder(key: trailingKey) ],
),
],
),
),
),
),
);
expect(tester.getRect(find.byType(AppBar)), const Rect.fromLTRB(0.0, 0.0, 800.00, 100.0 + 56.0));
expect(tester.getRect(find.byKey(leadingKey)), const Rect.fromLTRB(800.0 - 56.0, 100.0, 800.0, 100.0 + 56.0));
expect(tester.getRect(find.byKey(trailingKey)), const Rect.fromLTRB(0.0, 100.0, 400.0, 100.0 + 56.0));
});
testWidgets('SliverAppBar provides correct semantics in LTR', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
home: Center(
child: AppBar(
leading: const Text('Leading'),
title: const Text('Title'),
actions: const <Widget>[
Text('Action 1'),
Text('Action 2'),
Text('Action 3'),
],
bottom: const PreferredSize(
preferredSize: Size(0.0, kToolbarHeight),
child: Text('Bottom'),
),
),
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics> [
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: 'Leading',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.namesRoute,
SemanticsFlag.isHeader,
],
label: 'Title',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Action 1',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Action 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Action 3',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Bottom',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
],
),
],
),
ignoreRect: true,
ignoreTransform: true,
ignoreId: true,
));
semantics.dispose();
});
testWidgets('SliverAppBar provides correct semantics in RTL', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
home: Semantics(
textDirection: TextDirection.rtl,
child: Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: AppBar(
leading: const Text('Leading'),
title: const Text('Title'),
actions: const <Widget>[
Text('Action 1'),
Text('Action 2'),
Text('Action 3'),
],
bottom: const PreferredSize(
preferredSize: Size(0.0, kToolbarHeight),
child: Text('Bottom'),
),
),
),
),
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.rtl,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: 'Leading',
textDirection: TextDirection.rtl,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.namesRoute,
SemanticsFlag.isHeader,
],
label: 'Title',
textDirection: TextDirection.rtl,
),
TestSemantics(
label: 'Action 1',
textDirection: TextDirection.rtl,
),
TestSemantics(
label: 'Action 2',
textDirection: TextDirection.rtl,
),
TestSemantics(
label: 'Action 3',
textDirection: TextDirection.rtl,
),
TestSemantics(
label: 'Bottom',
textDirection: TextDirection.rtl,
),
],
),
],
),
],
),
],
),
],
),
],
),
ignoreRect: true,
ignoreTransform: true,
ignoreId: true,
));
semantics.dispose();
});
testWidgets('SliverAppBar excludes header semantics correctly', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
const MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
leading: Text('Leading'),
flexibleSpace: ExcludeSemantics(child: Text('Title')),
actions: <Widget>[Text('Action 1')],
excludeHeaderSemantics: true,
),
],
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: 'Leading',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Action 1',
textDirection: TextDirection.ltr,
),
],
),
TestSemantics(),
],
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
),
],
),
],
),
],
),
],
),
],
),
ignoreRect: true,
ignoreTransform: true,
ignoreId: true,
));
semantics.dispose();
});
testWidgets('SliverAppBar with flexible space has correct semantics order', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/64922.
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
const MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
leading: Text('Leading'),
flexibleSpace: Text('Flexible space'),
actions: <Widget>[Text('Action 1')],
),
],
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: 'Leading',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Action 1',
textDirection: TextDirection.ltr,
),
],
),
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isHeader],
label: 'Flexible space',
textDirection: TextDirection.ltr,
),
],
),
],
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
),
],
),
],
),
],
),
],
),
],
),
ignoreRect: true,
ignoreTransform: true,
ignoreId: true,
));
semantics.dispose();
});
testWidgets('Changing SliverAppBar snap from true to false', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/17598
const double appBarHeight = 256.0;
bool snap = true;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
expandedHeight: appBarHeight,
floating: true,
snap: snap,
actions: <Widget>[
TextButton(
child: const Text('snap=false'),
onPressed: () {
setState(() {
snap = false;
});
},
),
],
flexibleSpace: FlexibleSpaceBar(
background: Container(
height: appBarHeight,
color: Colors.orange,
),
),
),
SliverList(
delegate: SliverChildListDelegate(
<Widget>[
Container(height: 1200.0, color: Colors.teal),
],
),
),
],
),
);
},
),
),
);
TestGesture gesture = await tester.startGesture(const Offset(50.0, 400.0));
await gesture.moveBy(const Offset(0.0, -100.0));
await gesture.up();
await tester.tap(find.text('snap=false'));
await tester.pumpAndSettle();
gesture = await tester.startGesture(const Offset(50.0, 400.0));
await gesture.moveBy(const Offset(0.0, -100.0));
await gesture.up();
await tester.pump();
});
testWidgets('SliverAppBar shape default', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
leading: Text('L'),
title: Text('No Scaffold'),
actions: <Widget>[Text('A1'), Text('A2')],
),
],
),
),
);
final Finder sliverAppBarFinder = find.byType(SliverAppBar);
SliverAppBar getSliverAppBarWidget(Finder finder) => tester.widget<SliverAppBar>(finder);
expect(getSliverAppBarWidget(sliverAppBarFinder).shape, null);
final Finder materialFinder = find.byType(Material);
Material getMaterialWidget(Finder finder) => tester.widget<Material>(finder);
expect(getMaterialWidget(materialFinder).shape, null);
});
testWidgets('SliverAppBar with shape', (WidgetTester tester) async {
const RoundedRectangleBorder roundedRectangleBorder = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15.0)),
);
await tester.pumpWidget(
const MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
leading: Text('L'),
title: Text('No Scaffold'),
actions: <Widget>[Text('A1'), Text('A2')],
shape: roundedRectangleBorder,
),
],
),
),
);
final Finder sliverAppBarFinder = find.byType(SliverAppBar);
SliverAppBar getSliverAppBarWidget(Finder finder) => tester.widget<SliverAppBar>(finder);
expect(getSliverAppBarWidget(sliverAppBarFinder).shape, roundedRectangleBorder);
final Finder materialFinder = find.byType(Material);
Material getMaterialWidget(Finder finder) => tester.widget<Material>(finder);
expect(getMaterialWidget(materialFinder).shape, roundedRectangleBorder);
});
testWidgets('SliverAppBar configures the delegate properly', (WidgetTester tester) async {
Future<void> buildAndVerifyDelegate({ required bool pinned, required bool floating, required bool snap }) async {
await tester.pumpWidget(
MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: const Text('Jumbo'),
pinned: pinned,
floating: floating,
snap: snap,
),
],
),
),
);
final SliverPersistentHeaderDelegate delegate = tester
.widget<SliverPersistentHeader>(find.byType(SliverPersistentHeader))
.delegate;
// Ensure we have a non-null vsync when it's needed.
if (!floating || (delegate.snapConfiguration == null && delegate.showOnScreenConfiguration == null)) {
expect(delegate.vsync, isNotNull);
}
expect(delegate.showOnScreenConfiguration != null, snap && floating);
}
await buildAndVerifyDelegate(pinned: false, floating: true, snap: false);
await buildAndVerifyDelegate(pinned: false, floating: true, snap: true);
await buildAndVerifyDelegate(pinned: true, floating: true, snap: false);
await buildAndVerifyDelegate(pinned: true, floating: true, snap: true);
});
testWidgets('SliverAppBar default collapsedHeight with respect to toolbarHeight', (WidgetTester tester) async {
const double toolbarHeight = 100.0;
await tester.pumpWidget(buildSliverAppBarApp(
toolbarHeight: toolbarHeight,
));
final ScrollController controller = primaryScrollController(tester);
final double initialTabBarHeight = tabBarHeight(tester);
// Scroll the not-pinned appbar out of view, to its collapsed height.
controller.jumpTo(300.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsNothing);
// By default, the collapsedHeight is toolbarHeight + bottom.preferredSize.height,
// in this case initialTabBarHeight.
expect(appBarHeight(tester), toolbarHeight + initialTabBarHeight);
});
testWidgets('SliverAppBar collapsedHeight with toolbarHeight', (WidgetTester tester) async {
const double toolbarHeight = 100.0;
const double collapsedHeight = 150.0;
await tester.pumpWidget(buildSliverAppBarApp(
toolbarHeight: toolbarHeight,
collapsedHeight: collapsedHeight,
));
final ScrollController controller = primaryScrollController(tester);
final double initialTabBarHeight = tabBarHeight(tester);
// Scroll the not-pinned appbar out of view, to its collapsed height.
controller.jumpTo(300.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsNothing);
expect(appBarHeight(tester), collapsedHeight + initialTabBarHeight);
});
testWidgets('SliverAppBar collapsedHeight', (WidgetTester tester) async {
const double collapsedHeight = 56.0;
await tester.pumpWidget(buildSliverAppBarApp(
collapsedHeight: collapsedHeight,
));
final ScrollController controller = primaryScrollController(tester);
final double initialTabBarHeight = tabBarHeight(tester);
// Scroll the not-pinned appbar out of view, to its collapsed height.
controller.jumpTo(300.0);
await tester.pump();
expect(find.byType(SliverAppBar), findsNothing);
expect(appBarHeight(tester), collapsedHeight + initialTabBarHeight);
});
testWidgets('SliverAppBar respects leadingWidth', (WidgetTester tester) async {
const Key key = Key('leading');
await tester.pumpWidget(const MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
leading: Placeholder(key: key),
leadingWidth: 100,
title: Text('Title'),
),
],
),
));
// By default toolbarHeight is 56.0.
expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0, 0, 100, 56));
});
testWidgets('SliverAppBar.titleSpacing defaults to NavigationToolbar.kMiddleSpacing', (WidgetTester tester) async {
await tester.pumpWidget(buildSliverAppBarApp());
final NavigationToolbar navToolBar = tester.widget(find.byType(NavigationToolbar));
expect(navToolBar.middleSpacing, NavigationToolbar.kMiddleSpacing);
});
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 - SliverAppBar.medium defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
const double collapsedAppBarHeight = 64;
const double expandedAppBarHeight = 112;
await tester.pumpWidget(MaterialApp(
theme: theme,
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
const SliverAppBar.medium(
title: Text('AppBar Title'),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
));
final ScrollController controller = primaryScrollController(tester);
// There are two widgets for the title. The first title is a larger version
// that is shown at the bottom when the app bar is expanded. It scrolls under
// the main row until it is completely hidden and then the first title is
// faded in. The last is the title on the mainrow with the icons. It is
// transparent when the app bar is expanded, and opaque when it is collapsed.
final Finder expandedTitle = find.text('AppBar Title').first;
final Finder expandedTitleClip = find.ancestor(
of: expandedTitle,
matching: find.byType(ClipRect),
);
final Finder collapsedTitle = find.text('AppBar Title').last;
final Finder collapsedTitleOpacity = find.ancestor(
of: collapsedTitle,
matching: find.byType(AnimatedOpacity),
);
// Default, fully expanded app bar.
expect(controller.offset, 0);
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight);
// Test the expanded title is positioned correctly.
final Offset titleOffset = tester.getBottomLeft(expandedTitle);
expect(titleOffset, const Offset(16.0, 92.0));
// Test the expanded title default color.
expect(
tester.renderObject<RenderParagraph>(expandedTitle).text.style!.color,
theme.colorScheme.onPrimary,
);
// Scroll the expanded app bar partially out of view.
controller.jumpTo(45);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight - 45);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight - 45);
// Scroll so that it is completely collapsed.
controller.jumpTo(600);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), collapsedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 1);
expect(tester.getSize(expandedTitleClip).height, 0);
// Scroll back to fully expanded.
controller.jumpTo(0);
await tester.pumpAndSettle();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight);
});
testWidgets('Material2 - SliverAppBar.large defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
const double collapsedAppBarHeight = 64;
const double expandedAppBarHeight = 152;
await tester.pumpWidget(MaterialApp(
theme: theme,
home: Scaffold(
body: CustomScrollView(
primary: true,
slivers: <Widget>[
const SliverAppBar.large(
title: Text('AppBar Title'),
),
SliverToBoxAdapter(
child: Container(
height: 1200,
color: Colors.orange[400],
),
),
],
),
),
));
final ScrollController controller = primaryScrollController(tester);
// There are two widgets for the title. The first title is a larger version
// that is shown at the bottom when the app bar is expanded. It scrolls under
// the main row until it is completely hidden and then the first title is
// faded in. The last is the title on the mainrow with the icons. It is
// transparent when the app bar is expanded, and opaque when it is collapsed.
final Finder expandedTitle = find.text('AppBar Title').first;
final Finder expandedTitleClip = find.ancestor(
of: expandedTitle,
matching: find.byType(ClipRect),
);
final Finder collapsedTitle = find.text('AppBar Title').last;
final Finder collapsedTitleOpacity = find.ancestor(
of: collapsedTitle,
matching: find.byType(AnimatedOpacity),
);
// Default, fully expanded app bar.
expect(controller.offset, 0);
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight);
// Test the expanded title is positioned correctly.
final Offset titleOffset = tester.getBottomLeft(expandedTitle);
expect(titleOffset, const Offset(16.0, 124.0));
// Test the expanded title default color.
expect(
tester.renderObject<RenderParagraph>(expandedTitle).text.style!.color,
theme.colorScheme.onPrimary,
);
// Scroll the expanded app bar partially out of view.
controller.jumpTo(45);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight - 45);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight - 45);
// Scroll so that it is completely collapsed.
controller.jumpTo(600);
await tester.pump();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), collapsedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 1);
expect(tester.getSize(expandedTitleClip).height, 0);
// Scroll back to fully expanded.
controller.jumpTo(0);
await tester.pumpAndSettle();
expect(find.byType(SliverAppBar), findsOneWidget);
expect(appBarHeight(tester), expandedAppBarHeight);
expect(tester.widget<AnimatedOpacity>(collapsedTitleOpacity).opacity, 0);
expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight);
});
});
}
| flutter/packages/flutter/test/material/app_bar_sliver_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/app_bar_sliver_test.dart",
"repo_id": "flutter",
"token_count": 40826
} | 652 |
// 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';
import 'package:vector_math/vector_math_64.dart' show Vector3;
void main() {
test('BottomNavigationBarThemeData copyWith, ==, hashCode basics', () {
expect(const BottomNavigationBarThemeData(), const BottomNavigationBarThemeData().copyWith());
expect(const BottomNavigationBarThemeData().hashCode, const BottomNavigationBarThemeData().copyWith().hashCode);
});
test('BottomNavigationBarThemeData lerp special cases', () {
const BottomNavigationBarThemeData data = BottomNavigationBarThemeData();
expect(identical(BottomNavigationBarThemeData.lerp(data, data, 0.5), data), true);
});
test('BottomNavigationBarThemeData defaults', () {
const BottomNavigationBarThemeData themeData = BottomNavigationBarThemeData();
expect(themeData.backgroundColor, null);
expect(themeData.elevation, null);
expect(themeData.selectedIconTheme, null);
expect(themeData.unselectedIconTheme, null);
expect(themeData.selectedItemColor, null);
expect(themeData.unselectedItemColor, null);
expect(themeData.selectedLabelStyle, null);
expect(themeData.unselectedLabelStyle, null);
expect(themeData.showSelectedLabels, null);
expect(themeData.showUnselectedLabels, null);
expect(themeData.type, null);
expect(themeData.landscapeLayout, null);
expect(themeData.mouseCursor, null);
const BottomNavigationBarTheme theme = BottomNavigationBarTheme(data: BottomNavigationBarThemeData(), child: SizedBox());
expect(theme.data.backgroundColor, null);
expect(theme.data.elevation, null);
expect(theme.data.selectedIconTheme, null);
expect(theme.data.unselectedIconTheme, null);
expect(theme.data.selectedItemColor, null);
expect(theme.data.unselectedItemColor, null);
expect(theme.data.selectedLabelStyle, null);
expect(theme.data.unselectedLabelStyle, null);
expect(theme.data.showSelectedLabels, null);
expect(theme.data.showUnselectedLabels, null);
expect(theme.data.type, null);
expect(themeData.landscapeLayout, null);
expect(themeData.mouseCursor, null);
});
testWidgets('Default BottomNavigationBarThemeData debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const BottomNavigationBarThemeData().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('BottomNavigationBarThemeData implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const BottomNavigationBarThemeData(
backgroundColor: Color(0xfffffff0),
elevation: 10.0,
selectedIconTheme: IconThemeData(size: 1.0),
unselectedIconTheme: IconThemeData(size: 2.0),
selectedItemColor: Color(0xfffffff1),
unselectedItemColor: Color(0xfffffff2),
selectedLabelStyle: TextStyle(fontSize: 3.0),
unselectedLabelStyle: TextStyle(fontSize: 4.0),
showSelectedLabels: true,
showUnselectedLabels: true,
type: BottomNavigationBarType.fixed,
mouseCursor: MaterialStateMouseCursor.clickable,
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description[0], 'backgroundColor: Color(0xfffffff0)');
expect(description[1], 'elevation: 10.0');
// Ignore instance address for IconThemeData.
expect(description[2].contains('selectedIconTheme: IconThemeData'), isTrue);
expect(description[2].contains('(size: 1.0)'), isTrue);
expect(description[3].contains('unselectedIconTheme: IconThemeData'), isTrue);
expect(description[3].contains('(size: 2.0)'), isTrue);
expect(description[4], 'selectedItemColor: Color(0xfffffff1)');
expect(description[5], 'unselectedItemColor: Color(0xfffffff2)');
expect(description[6], 'selectedLabelStyle: TextStyle(inherit: true, size: 3.0)');
expect(description[7], 'unselectedLabelStyle: TextStyle(inherit: true, size: 4.0)');
expect(description[8], 'showSelectedLabels: true');
expect(description[9], 'showUnselectedLabels: true');
expect(description[10], 'type: BottomNavigationBarType.fixed');
expect(description[11], 'mouseCursor: WidgetStateMouseCursor(clickable)');
});
testWidgets('BottomNavigationBar is themeable', (WidgetTester tester) async {
const Color backgroundColor = Color(0xFF000001);
const Color selectedItemColor = Color(0xFF000002);
const Color unselectedItemColor = Color(0xFF000003);
const IconThemeData selectedIconTheme = IconThemeData(size: 10);
const IconThemeData unselectedIconTheme = IconThemeData(size: 11);
const TextStyle selectedTextStyle = TextStyle(fontSize: 22);
const TextStyle unselectedTextStyle = TextStyle(fontSize: 21);
const double elevation = 9.0;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: backgroundColor,
selectedItemColor: selectedItemColor,
unselectedItemColor: unselectedItemColor,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
elevation: elevation,
showUnselectedLabels: true,
showSelectedLabels: true,
type: BottomNavigationBarType.fixed,
selectedLabelStyle: selectedTextStyle,
unselectedLabelStyle: unselectedTextStyle,
mouseCursor: MaterialStateProperty.resolveWith<MouseCursor?>((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return SystemMouseCursors.grab;
}
return SystemMouseCursors.move;
}),
),
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final Finder findACTransform = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.ancestor(
of: find.text('AC'),
matching: find.byType(Transform),
),
);
final Finder findAlarmTransform = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.ancestor(
of: find.text('Alarm'),
matching: find.byType(Transform),
),
);
final TextStyle selectedFontStyle = tester.renderObject<RenderParagraph>(find.text('AC')).text.style!;
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedFontStyle.fontSize, selectedFontStyle.fontSize);
// Unselected label has a font size of 22 but is scaled down to be font size 21.
expect(
tester.firstWidget<Transform>(findAlarmTransform).transform,
equals(Matrix4.diagonal3(Vector3.all(unselectedTextStyle.fontSize! / selectedTextStyle.fontSize!))),
);
expect(selectedIcon.color, equals(selectedItemColor));
expect(selectedIcon.fontSize, equals(selectedIconTheme.size));
expect(unselectedIcon.color, equals(unselectedItemColor));
expect(unselectedIcon.fontSize, equals(unselectedIconTheme.size));
// There should not be any [Opacity] or [FadeTransition] widgets
// since showUnselectedLabels and showSelectedLabels are true.
final Finder findOpacity = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(Opacity),
);
final Finder findFadeTransition = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(FadeTransition),
);
expect(findOpacity, findsNothing);
expect(findFadeTransition, findsNothing);
expect(_material(tester).elevation, equals(elevation));
expect(_material(tester).color, equals(backgroundColor));
final Offset selectedBarItem = tester.getCenter(findACTransform);
final Offset unselectedBarItem = tester.getCenter(findAlarmTransform);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(selectedBarItem);
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab);
await gesture.moveTo(unselectedBarItem);
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.move);
});
testWidgets('BottomNavigationBar properties are taken over the theme values', (WidgetTester tester) async {
const Color themeBackgroundColor = Color(0xFF000001);
const Color themeSelectedItemColor = Color(0xFF000002);
const Color themeUnselectedItemColor = Color(0xFF000003);
const IconThemeData themeSelectedIconTheme = IconThemeData(size: 10);
const IconThemeData themeUnselectedIconTheme = IconThemeData(size: 11);
const TextStyle themeSelectedTextStyle = TextStyle(fontSize: 22);
const TextStyle themeUnselectedTextStyle = TextStyle(fontSize: 21);
const double themeElevation = 9.0;
const BottomNavigationBarLandscapeLayout themeLandscapeLayout = BottomNavigationBarLandscapeLayout.centered;
const MaterialStateMouseCursor themeCursor = MaterialStateMouseCursor.clickable;
const Color backgroundColor = Color(0xFF000004);
const Color selectedItemColor = Color(0xFF000005);
const Color unselectedItemColor = Color(0xFF000006);
const IconThemeData selectedIconTheme = IconThemeData(size: 15);
const IconThemeData unselectedIconTheme = IconThemeData(size: 16);
const TextStyle selectedTextStyle = TextStyle(fontSize: 25);
const TextStyle unselectedTextStyle = TextStyle(fontSize: 26);
const double elevation = 7.0;
const BottomNavigationBarLandscapeLayout landscapeLayout = BottomNavigationBarLandscapeLayout.spread;
const MaterialStateMouseCursor cursor = MaterialStateMouseCursor.textable;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
backgroundColor: themeBackgroundColor,
selectedItemColor: themeSelectedItemColor,
unselectedItemColor: themeUnselectedItemColor,
selectedIconTheme: themeSelectedIconTheme,
unselectedIconTheme: themeUnselectedIconTheme,
elevation: themeElevation,
showUnselectedLabels: false,
showSelectedLabels: false,
type: BottomNavigationBarType.shifting,
selectedLabelStyle: themeSelectedTextStyle,
unselectedLabelStyle: themeUnselectedTextStyle,
landscapeLayout: themeLandscapeLayout,
mouseCursor: themeCursor,
),
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
backgroundColor: backgroundColor,
selectedItemColor: selectedItemColor,
unselectedItemColor: unselectedItemColor,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
elevation: elevation,
showUnselectedLabels: true,
showSelectedLabels: true,
type: BottomNavigationBarType.fixed,
selectedLabelStyle: selectedTextStyle,
unselectedLabelStyle: unselectedTextStyle,
landscapeLayout: landscapeLayout,
mouseCursor: cursor,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
Finder findDescendantOfBottomNavigationBar(Finder finder) {
return find.descendant(
of: find.byType(BottomNavigationBar),
matching: finder,
);
}
final TextStyle selectedFontStyle = tester.renderObject<RenderParagraph>(find.text('AC')).text.style!;
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedFontStyle.fontSize, selectedFontStyle.fontSize);
// Unselected label has a font size of 22 but is scaled down to be font size 21.
expect(
tester.firstWidget<Transform>(
findDescendantOfBottomNavigationBar(
find.ancestor(
of: find.text('Alarm'),
matching: find.byType(Transform),
),
),
).transform,
equals(Matrix4.diagonal3(Vector3.all(unselectedTextStyle.fontSize! / selectedTextStyle.fontSize!))),
);
expect(selectedIcon.color, equals(selectedItemColor));
expect(selectedIcon.fontSize, equals(selectedIconTheme.size));
expect(unselectedIcon.color, equals(unselectedItemColor));
expect(unselectedIcon.fontSize, equals(unselectedIconTheme.size));
// There should not be any [Opacity] or [FadeTransition] widgets
// since showUnselectedLabels and showSelectedLabels are true.
final Finder findOpacity = findDescendantOfBottomNavigationBar(
find.byType(Opacity),
);
final Finder findFadeTransition = findDescendantOfBottomNavigationBar(
find.byType(FadeTransition),
);
expect(findOpacity, findsNothing);
expect(findFadeTransition, findsNothing);
expect(_material(tester).elevation, equals(elevation));
expect(_material(tester).color, equals(backgroundColor));
final Offset barItem = tester.getCenter(
findDescendantOfBottomNavigationBar(
find.ancestor(
of: find.text('AC'),
matching: find.byType(Transform),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(barItem);
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
});
testWidgets('BottomNavigationBarTheme can be used to hide all labels', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/66738.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
showSelectedLabels: false,
showUnselectedLabels: false,
),
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final Finder findVisibility = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(Visibility),
);
expect(findVisibility, findsNWidgets(2));
expect(tester.widget<Visibility>(findVisibility.at(0)).visible, false);
expect(tester.widget<Visibility>(findVisibility.at(1)).visible, false);
});
testWidgets('BottomNavigationBarTheme can be used to hide selected labels', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/66738.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
showSelectedLabels: false,
showUnselectedLabels: true,
),
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final Finder findFadeTransition = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(FadeTransition),
);
expect(findFadeTransition, findsNWidgets(2));
expect(tester.widget<FadeTransition>(findFadeTransition.at(0)).opacity.value, 0.0);
expect(tester.widget<FadeTransition>(findFadeTransition.at(1)).opacity.value, 1.0);
});
testWidgets('BottomNavigationBarTheme can be used to hide unselected labels', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
showSelectedLabels: true,
showUnselectedLabels: false,
),
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final Finder findFadeTransition = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(FadeTransition),
);
expect(findFadeTransition, findsNWidgets(2));
expect(tester.widget<FadeTransition>(findFadeTransition.at(0)).opacity.value, 1.0);
expect(tester.widget<FadeTransition>(findFadeTransition.at(1)).opacity.value, 0.0);
});
}
TextStyle _iconStyle(WidgetTester tester, IconData icon) {
final RichText iconRichText = tester.widget<RichText>(
find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)),
);
return iconRichText.text.style!;
}
Material _material(WidgetTester tester) {
return tester.firstWidget<Material>(
find.descendant(of: find.byType(BottomNavigationBar), matching: find.byType(Material)),
);
}
| flutter/packages/flutter/test/material/bottom_navigation_bar_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/bottom_navigation_bar_theme_test.dart",
"repo_id": "flutter",
"token_count": 7435
} | 653 |
// 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:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import '../image_data.dart';
import '../painting/mocks_for_image_cache.dart';
void main() {
testWidgets('CircleAvatar with dark background color', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade900;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundColor: backgroundColor,
radius: 50.0,
child: const Text('Z'),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorLight));
});
testWidgets('CircleAvatar with light background color', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade100;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundColor: backgroundColor,
radius: 50.0,
child: const Text('Z'),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorDark));
});
testWidgets('CircleAvatar with image background', (WidgetTester tester) async {
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundImage: MemoryImage(Uint8List.fromList(kTransparentImage)),
radius: 50.0,
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.image!.fit, equals(BoxFit.cover));
});
testWidgets('CircleAvatar with image foreground', (WidgetTester tester) async {
await tester.pumpWidget(
wrap(
child: CircleAvatar(
foregroundImage: MemoryImage(Uint8List.fromList(kBlueRectPng)),
radius: 50.0,
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.image!.fit, equals(BoxFit.cover));
});
testWidgets('CircleAvatar backgroundImage is used as a fallback for foregroundImage',
// TODO(polina-c): clean up leaks, https://github.com/flutter/flutter/issues/134787 [leaks-to-clean]
experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(),
(WidgetTester tester) async {
final ErrorImageProvider errorImage = ErrorImageProvider();
bool caughtForegroundImageError = false;
await tester.pumpWidget(
wrap(
child: RepaintBoundary(
child: CircleAvatar(
foregroundImage: errorImage,
backgroundImage: MemoryImage(Uint8List.fromList(kBlueRectPng)),
radius: 50.0,
onForegroundImageError: (_,__) => caughtForegroundImageError = true,
),
),
),
);
expect(caughtForegroundImageError, true);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.image!.fit, equals(BoxFit.cover));
await expectLater(
find.byType(CircleAvatar),
matchesGoldenFile('circle_avatar.fallback.png'),
);
});
testWidgets('CircleAvatar with foreground color', (WidgetTester tester) async {
final Color foregroundColor = Colors.red.shade100;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
foregroundColor: foregroundColor,
child: const Text('Z'),
),
),
);
final ThemeData fallback = ThemeData.fallback();
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(40.0, 40.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(fallback.primaryColorDark));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(foregroundColor));
});
testWidgets('Material3 - CircleAvatar default colors', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
wrap(
child: Theme(
data: theme,
child: const CircleAvatar(
child: Text('Z'),
),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(theme.colorScheme.primaryContainer));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(theme.colorScheme.onPrimaryContainer));
});
testWidgets('CircleAvatar text does not expand with textScaler', (WidgetTester tester) async {
final Color foregroundColor = Colors.red.shade100;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
foregroundColor: foregroundColor,
child: const Text('Z'),
),
),
);
expect(tester.getSize(find.text('Z')), equals(const Size(16.0, 16.0)));
await tester.pumpWidget(
wrap(
child: MediaQuery(
data: const MediaQueryData(
textScaler: TextScaler.linear(2.0),
size: Size(111.0, 111.0),
devicePixelRatio: 1.1,
padding: EdgeInsets.all(11.0),
),
child: CircleAvatar(
child: Builder(
builder: (BuildContext context) {
final MediaQueryData data = MediaQuery.of(context);
// These should not change.
expect(data.size, equals(const Size(111.0, 111.0)));
expect(data.devicePixelRatio, equals(1.1));
expect(data.padding, equals(const EdgeInsets.all(11.0)));
// This should be overridden to 1.0.
expect(data.textScaler, TextScaler.noScaling);
return const Text('Z');
},
),
),
),
),
);
expect(tester.getSize(find.text('Z')), equals(const Size(16.0, 16.0)));
});
testWidgets('CircleAvatar respects minRadius', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade900;
await tester.pumpWidget(
wrap(
child: UnconstrainedBox(
child: CircleAvatar(
backgroundColor: backgroundColor,
minRadius: 50.0,
child: const Text('Z'),
),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorLight));
});
testWidgets('CircleAvatar respects maxRadius', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade900;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundColor: backgroundColor,
maxRadius: 50.0,
child: const Text('Z'),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorLight));
});
testWidgets('CircleAvatar respects setting both minRadius and maxRadius', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade900;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundColor: backgroundColor,
maxRadius: 50.0,
minRadius: 50.0,
child: const Text('Z'),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorLight));
});
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 - CircleAvatar default colors with light theme', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false, primaryColor: Colors.grey.shade100);
await tester.pumpWidget(
wrap(
child: Theme(
data: theme,
child: const CircleAvatar(
child: Text('Z'),
),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(theme.primaryColorLight));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(theme.primaryTextTheme.titleLarge!.color));
});
testWidgets('Material2 - CircleAvatar default colors with dark theme', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false, primaryColor: Colors.grey.shade800);
await tester.pumpWidget(
wrap(
child: Theme(
data: theme,
child: const CircleAvatar(
child: Text('Z'),
),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(theme.primaryColorDark));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(theme.primaryTextTheme.titleLarge!.color));
});
});
}
Widget wrap({ required Widget child }) {
return Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Center(child: child)),
),
);
}
| flutter/packages/flutter/test/material/circle_avatar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/circle_avatar_test.dart",
"repo_id": "flutter",
"token_count": 4944
} | 654 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('DrawerButton control test', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: DrawerButton(),
drawer: Drawer(),
),
),
);
await tester.pumpAndSettle();
expect(find.byType(Drawer), findsNothing);
await tester.tap(find.byType(DrawerButton));
await tester.pumpAndSettle();
expect(find.byType(Drawer), findsOneWidget);
});
testWidgets('DrawerButton onPressed overrides default end drawer open behaviour',
(WidgetTester tester) async {
bool customCallbackWasCalled = false;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: DrawerButton(
onPressed: () => customCallbackWasCalled = true),
),
drawer: const Drawer(),
),
),
);
await tester.pumpAndSettle();
expect(find.byType(Drawer), findsNothing); // Start off with a closed drawer
expect(customCallbackWasCalled,
false); // customCallbackWasCalled should still be false.
await tester.tap(find.byType(DrawerButton));
await tester.pumpAndSettle();
// Drawer is still closed
expect(find.byType(Drawer), findsNothing);
// The custom callback is called, setting customCallbackWasCalled to true.
expect(customCallbackWasCalled, true);
});
testWidgets('DrawerButton icon', (WidgetTester tester) async {
final Key androidKey = UniqueKey();
final Key iOSKey = UniqueKey();
final Key linuxKey = UniqueKey();
final Key macOSKey = UniqueKey();
final Key windowsKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Column(
children: <Widget>[
Theme(
data: ThemeData(platform: TargetPlatform.android),
child: DrawerButtonIcon(key: androidKey),
),
Theme(
data: ThemeData(platform: TargetPlatform.iOS),
child: DrawerButtonIcon(key: iOSKey),
),
Theme(
data: ThemeData(platform: TargetPlatform.linux),
child: DrawerButtonIcon(key: linuxKey),
),
Theme(
data: ThemeData(platform: TargetPlatform.macOS),
child: DrawerButtonIcon(key: macOSKey),
),
Theme(
data: ThemeData(platform: TargetPlatform.windows),
child: DrawerButtonIcon(key: windowsKey),
),
],
),
),
);
final Icon androidIcon = tester.widget(find.descendant(
of: find.byKey(androidKey), matching: find.byType(Icon)));
final Icon iOSIcon = tester.widget(
find.descendant(of: find.byKey(iOSKey), matching: find.byType(Icon)));
final Icon linuxIcon = tester.widget(
find.descendant(of: find.byKey(linuxKey), matching: find.byType(Icon)));
final Icon macOSIcon = tester.widget(
find.descendant(of: find.byKey(macOSKey), matching: find.byType(Icon)));
final Icon windowsIcon = tester.widget(find.descendant(
of: find.byKey(windowsKey), matching: find.byType(Icon)));
// All icons for drawer are the same
expect(iOSIcon.icon == androidIcon.icon, isTrue);
expect(linuxIcon.icon == androidIcon.icon, isTrue);
expect(macOSIcon.icon == androidIcon.icon, isTrue);
expect(windowsIcon.icon == androidIcon.icon, isTrue);
});
testWidgets('DrawerButton color', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: DrawerButton(
color: Colors.red,
),
),
),
);
final RichText iconText = tester.firstWidget(find.descendant(
of: find.byType(DrawerButton),
matching: find.byType(RichText),
));
expect(iconText.text.style!.color, Colors.red);
});
testWidgets('DrawerButton color with ButtonStyle', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const Material(
child: DrawerButton(
style: ButtonStyle(
iconColor: MaterialStatePropertyAll<Color>(Colors.red),
),
),
),
),
);
final RichText iconText = tester.firstWidget(find.descendant(
of: find.byType(DrawerButton),
matching: find.byType(RichText),
));
expect(iconText.text.style!.color, Colors.red);
});
testWidgets('DrawerButton semantics', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Center(
child: DrawerButton(),
),
),
),
);
await tester.pumpAndSettle();
final String? expectedLabel;
switch (defaultTargetPlatform) {
case TargetPlatform.android:
expectedLabel = 'Open navigation menu';
case TargetPlatform.fuchsia:
case TargetPlatform.iOS:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
expectedLabel = null;
}
expect(tester.getSemantics(find.byType(DrawerButton)), matchesSemantics(
tooltip: 'Open navigation menu',
label: expectedLabel,
isButton: true,
hasEnabledState: true,
isEnabled: true,
hasTapAction: true,
isFocusable: true,
));
handle.dispose();
}, variant: TargetPlatformVariant.all());
testWidgets('EndDrawerButton control test', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: EndDrawerButton(),
endDrawer: Drawer(),
),
),
);
await tester.pumpAndSettle();
expect(find.byType(Drawer), findsNothing);
await tester.tap(find.byType(EndDrawerButton));
await tester.pumpAndSettle();
expect(find.byType(Drawer), findsOneWidget);
});
testWidgets('EndDrawerButton semantics', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Center(
child: EndDrawerButton(),
),
),
),
);
await tester.pumpAndSettle();
final String? expectedLabel;
switch (defaultTargetPlatform) {
case TargetPlatform.android:
expectedLabel = 'Open navigation menu';
case TargetPlatform.fuchsia:
case TargetPlatform.iOS:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
expectedLabel = null;
}
expect(tester.getSemantics(find.byType(EndDrawerButton)), matchesSemantics(
tooltip: 'Open navigation menu',
label: expectedLabel,
isButton: true,
hasEnabledState: true,
isEnabled: true,
hasTapAction: true,
isFocusable: true,
));
handle.dispose();
}, variant: TargetPlatformVariant.all());
testWidgets('EndDrawerButton color', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: EndDrawerButton(
color: Colors.red,
),
),
),
);
final RichText iconText = tester.firstWidget(find.descendant(
of: find.byType(EndDrawerButton),
matching: find.byType(RichText),
));
expect(iconText.text.style!.color, Colors.red);
});
testWidgets('EndDrawerButton color with ButtonStyle', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const Material(
child: EndDrawerButton(
style: ButtonStyle(
iconColor: MaterialStatePropertyAll<Color>(Colors.red),
),
),
),
),
);
final RichText iconText = tester.firstWidget(find.descendant(
of: find.byType(EndDrawerButton),
matching: find.byType(RichText),
));
expect(iconText.text.style!.color, Colors.red);
});
testWidgets('EndDrawerButton onPressed overrides default end drawer open behaviour',
(WidgetTester tester) async {
bool customCallbackWasCalled = false;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: EndDrawerButton(onPressed: () => customCallbackWasCalled = true),
),
endDrawer: const Drawer(),
),
),
);
await tester.pumpAndSettle();
expect(find.byType(Drawer), findsNothing); // Start off with a closed drawer
expect(customCallbackWasCalled,
false); // customCallbackWasCalled should still be false.
await tester.tap(find.byType(EndDrawerButton));
await tester.pumpAndSettle();
// Drawer is still closed
expect(find.byType(Drawer), findsNothing);
// The custom callback is called, setting customCallbackWasCalled to true.
expect(customCallbackWasCalled, true);
});
}
| flutter/packages/flutter/test/material/drawer_button_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/drawer_button_test.dart",
"repo_id": "flutter",
"token_count": 3858
} | 655 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// 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/src/foundation/constants.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('InkSparkle in a Button compiles and does not crash', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(splashFactory: InkSparkle.splashFactory),
child: const Text('Sparkle!'),
onPressed: () { },
),
),
),
));
final Finder buttonFinder = find.text('Sparkle!');
await tester.tap(buttonFinder);
await tester.pump();
await tester.pumpAndSettle();
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
testWidgets('InkSparkle default splashFactory paints with drawRect when bounded', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Center(
child: InkWell(
splashFactory: InkSparkle.splashFactory,
child: const Text('Sparkle!'),
onTap: () { },
),
),
),
));
final Finder buttonFinder = find.text('Sparkle!');
await tester.tap(buttonFinder);
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
final MaterialInkController material = Material.of(tester.element(buttonFinder));
expect(material, paintsExactlyCountTimes(#drawRect, 1));
expect((material as dynamic).debugInkFeatures, hasLength(1));
await tester.pumpAndSettle();
// ink feature is disposed.
expect((material as dynamic).debugInkFeatures, isEmpty);
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
testWidgets('InkSparkle default splashFactory paints with drawPaint when unbounded', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Center(
child: InkResponse(
splashFactory: InkSparkle.splashFactory,
child: const Text('Sparkle!'),
onTap: () { },
),
),
),
));
final Finder buttonFinder = find.text('Sparkle!');
await tester.tap(buttonFinder);
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
final MaterialInkController material = Material.of(tester.element(buttonFinder));
expect(material, paintsExactlyCountTimes(#drawPaint, 1));
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
/////////////
// Goldens //
/////////////
testWidgets('Material2 - InkSparkle renders with sparkles when top left of button is tapped', (WidgetTester tester) async {
await _runTest(tester, 'top_left', 0.2);
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
testWidgets('Material3 - InkSparkle renders with sparkles when top left of button is tapped', (WidgetTester tester) async {
await _runM3Test(tester, 'top_left', 0.2);
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
testWidgets('Material2 - InkSparkle renders with sparkles when center of button is tapped', (WidgetTester tester) async {
await _runTest(tester, 'center', 0.5);
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
testWidgets('Material3 - InkSparkle renders with sparkles when center of button is tapped', (WidgetTester tester) async {
await _runM3Test(tester, 'center', 0.5);
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
testWidgets('Material2 - InkSparkle renders with sparkles when bottom right of button is tapped', (WidgetTester tester) async {
await _runTest(tester, 'bottom_right', 0.8);
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
testWidgets('Material3 - InkSparkle renders with sparkles when bottom right of button is tapped', (WidgetTester tester) async {
await _runM3Test(tester, 'bottom_right', 0.8);
},
skip: kIsWeb, // [intended] shaders are not yet supported for web.
);
}
Future<void> _runTest(WidgetTester tester, String positionName, double distanceFromTopLeft) async {
final Key repaintKey = UniqueKey();
final Key buttonKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: RepaintBoundary(
key: repaintKey,
child: ElevatedButton(
key: buttonKey,
style: ElevatedButton.styleFrom(splashFactory: InkSparkle.constantTurbulenceSeedSplashFactory),
child: const Text('Sparkle!'),
onPressed: () { },
),
),
),
),
));
final Finder buttonFinder = find.byKey(buttonKey);
final Finder repaintFinder = find.byKey(repaintKey);
final Offset topLeft = tester.getTopLeft(buttonFinder);
final Offset bottomRight = tester.getBottomRight(buttonFinder);
await _warmUpShader(tester, buttonFinder);
final Offset target = topLeft + (bottomRight - topLeft) * distanceFromTopLeft;
await tester.tapAt(target);
for (int i = 0; i <= 5; i++) {
await tester.pump(const Duration(milliseconds: 50));
await expectLater(
repaintFinder,
matchesGoldenFile('m2_ink_sparkle.$positionName.$i.png'),
);
}
}
Future<void> _runM3Test(WidgetTester tester, String positionName, double distanceFromTopLeft) async {
final Key repaintKey = UniqueKey();
final Key buttonKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: Center(
child: RepaintBoundary(
key: repaintKey,
child: ElevatedButton(
key: buttonKey,
style: ElevatedButton.styleFrom(),
child: const Text('Sparkle!'),
onPressed: () { },
),
),
),
),
));
final Finder buttonFinder = find.byKey(buttonKey);
final Finder repaintFinder = find.byKey(repaintKey);
final Offset topLeft = tester.getTopLeft(buttonFinder);
final Offset bottomRight = tester.getBottomRight(buttonFinder);
await _warmUpShader(tester, buttonFinder);
final Offset target = topLeft + (bottomRight - topLeft) * distanceFromTopLeft;
await tester.tapAt(target);
for (int i = 0; i <= 5; i++) {
await tester.pump(const Duration(milliseconds: 50));
await expectLater(
repaintFinder,
matchesGoldenFile('m3_ink_sparkle.$positionName.$i.png'),
);
}
}
// Warm up shader. Compilation is of the order of 10 milliseconds and
// Animation is < 1000 milliseconds. Use 2000 milliseconds as a safety
// net to prevent flakiness.
Future<void> _warmUpShader(WidgetTester tester, Finder buttonFinder) async {
await tester.tap(buttonFinder);
await tester.pumpAndSettle(const Duration(milliseconds: 2000));
}
| flutter/packages/flutter/test/material/ink_sparkle_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/ink_sparkle_test.dart",
"repo_id": "flutter",
"token_count": 2719
} | 656 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'data_table_test_utils.dart';
class TestDataSource extends DataTableSource {
TestDataSource({
this.allowSelection = false,
});
final bool allowSelection;
int get generation => _generation;
int _generation = 0;
set generation(int value) {
if (_generation == value) {
return;
}
_generation = value;
notifyListeners();
}
final Set<int> _selectedRows = <int>{};
void _handleSelected(int index, bool? selected) {
if (selected ?? false) {
_selectedRows.add(index);
} else {
_selectedRows.remove(index);
}
notifyListeners();
}
@override
DataRow getRow(int index) {
final Dessert dessert = kDesserts[index % kDesserts.length];
final int page = index ~/ kDesserts.length;
return DataRow.byIndex(
index: index,
selected: _selectedRows.contains(index),
cells: <DataCell>[
DataCell(Text('${dessert.name} ($page)')),
DataCell(Text('${dessert.calories}')),
DataCell(Text('$generation')),
],
onSelectChanged: allowSelection ? (bool? selected) => _handleSelected(index, selected) : null,
);
}
@override
int get rowCount => 50 * kDesserts.length;
@override
bool get isRowCountApproximate => false;
@override
int get selectedRowCount => _selectedRows.length;
}
void main() {
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
late TestDataSource source;
setUp(() => source = TestDataSource());
tearDown(() => source.dispose());
testWidgets('PaginatedDataTable paging', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(MaterialApp(
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
showFirstLastButtons: true,
availableRowsPerPage: const <int>[
2, 4, 8, 16,
],
onRowsPerPageChanged: (int? rowsPerPage) {
log.add('rows-per-page-changed: $rowsPerPage');
},
onPageChanged: (int rowIndex) {
log.add('page-changed: $rowIndex');
},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
));
await tester.tap(find.byTooltip('Next page'));
expect(log, <String>['page-changed: 2']);
log.clear();
await tester.pump();
expect(find.text('Frozen yogurt (0)'), findsNothing);
expect(find.text('Eclair (0)'), findsOneWidget);
expect(find.text('Gingerbread (0)'), findsNothing);
await tester.tap(find.byIcon(Icons.chevron_left));
expect(log, <String>['page-changed: 0']);
log.clear();
await tester.pump();
expect(find.text('Frozen yogurt (0)'), findsOneWidget);
expect(find.text('Eclair (0)'), findsNothing);
expect(find.text('Gingerbread (0)'), findsNothing);
final Finder lastPageButton = find.ancestor(
of: find.byTooltip('Last page'),
matching: find.byWidgetPredicate((Widget widget) => widget is IconButton),
);
expect(tester.widget<IconButton>(lastPageButton).onPressed, isNotNull);
await tester.tap(lastPageButton);
expect(log, <String>['page-changed: 498']);
log.clear();
await tester.pump();
expect(tester.widget<IconButton>(lastPageButton).onPressed, isNull);
expect(find.text('Frozen yogurt (0)'), findsNothing);
expect(find.text('Donut (49)'), findsOneWidget);
expect(find.text('KitKat (49)'), findsOneWidget);
final Finder firstPageButton = find.ancestor(
of: find.byTooltip('First page'),
matching: find.byWidgetPredicate((Widget widget) => widget is IconButton),
);
expect(tester.widget<IconButton>(firstPageButton).onPressed, isNotNull);
await tester.tap(firstPageButton);
expect(log, <String>['page-changed: 0']);
log.clear();
await tester.pump();
expect(tester.widget<IconButton>(firstPageButton).onPressed, isNull);
expect(find.text('Frozen yogurt (0)'), findsOneWidget);
expect(find.text('Eclair (0)'), findsNothing);
expect(find.text('Gingerbread (0)'), findsNothing);
await tester.tap(find.byIcon(Icons.chevron_left));
expect(log, isEmpty);
await tester.tap(find.text('2'));
await tester.pumpAndSettle(const Duration(milliseconds: 200));
await tester.tap(find.text('8').last);
await tester.pumpAndSettle(const Duration(milliseconds: 200));
expect(log, <String>['rows-per-page-changed: 8']);
log.clear();
});
testWidgets('PaginatedDataTable footer page number', (WidgetTester tester) async {
int rowsPerPage = 2;
Widget buildTable(TestDataSource source, int rowsPerPage) {
return PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: rowsPerPage,
showFirstLastButtons: true,
availableRowsPerPage: const <int>[
2, 3, 4, 5, 7, 8,
],
onRowsPerPageChanged: (int? rowsPerPage) {
},
onPageChanged: (int rowIndex) {
},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
);
}
await tester.pumpWidget(MaterialApp(
home: buildTable(source, rowsPerPage)
));
expect(find.text('1–2 of 500'), findsOneWidget);
await tester.tap(find.byTooltip('Next page'));
await tester.pump();
expect(find.text('3–4 of 500'), findsOneWidget);
final Finder lastPageButton = find.ancestor(
of: find.byTooltip('Last page'),
matching: find.byWidgetPredicate((Widget widget) => widget is IconButton),
);
expect(tester.widget<IconButton>(lastPageButton).onPressed, isNotNull);
await tester.tap(lastPageButton);
await tester.pump();
expect(find.text('499–500 of 500'), findsOneWidget);
final PaginatedDataTableState state = tester.state(find.byType(PaginatedDataTable));
state.pageTo(1);
rowsPerPage = 3;
await tester.pumpWidget(MaterialApp(
home: buildTable(source, rowsPerPage)
));
expect(find.textContaining('1–3 of 500'), findsOneWidget);
await tester.tap(find.byTooltip('Next page'));
await tester.pump();
expect(find.text('4–6 of 500'), findsOneWidget);
expect(tester.widget<IconButton>(lastPageButton).onPressed, isNotNull);
await tester.tap(lastPageButton);
await tester.pump();
expect(find.text('499–500 of 500'), findsOneWidget);
state.pageTo(1);
rowsPerPage = 4;
await tester.pumpWidget(MaterialApp(
home: buildTable(source, rowsPerPage)
));
expect(find.textContaining('1–4 of 500'), findsOneWidget);
await tester.tap(find.byTooltip('Next page'));
await tester.pump();
expect(find.text('5–8 of 500'), findsOneWidget);
expect(tester.widget<IconButton>(lastPageButton).onPressed, isNotNull);
await tester.tap(lastPageButton);
await tester.pump();
expect(find.text('497–500 of 500'), findsOneWidget);
state.pageTo(1);
rowsPerPage = 5;
await tester.pumpWidget(MaterialApp(
home: buildTable(source, rowsPerPage)
));
expect(find.textContaining('1–5 of 500'), findsOneWidget);
await tester.tap(find.byTooltip('Next page'));
await tester.pump();
expect(find.text('6–10 of 500'), findsOneWidget);
expect(tester.widget<IconButton>(lastPageButton).onPressed, isNotNull);
await tester.tap(lastPageButton);
await tester.pump();
expect(find.text('496–500 of 500'), findsOneWidget);
state.pageTo(1);
rowsPerPage = 8;
await tester.pumpWidget(MaterialApp(
home: buildTable(source, rowsPerPage)
));
expect(find.textContaining('1–8 of 500'), findsOneWidget);
await tester.tap(find.byTooltip('Next page'));
await tester.pump();
expect(find.text('9–16 of 500'), findsOneWidget);
expect(tester.widget<IconButton>(lastPageButton).onPressed, isNotNull);
await tester.tap(lastPageButton);
await tester.pump();
expect(find.text('497–500 of 500'), findsOneWidget);
});
testWidgets('PaginatedDataTable Last Page Empty Space', (WidgetTester tester) async {
final TestDataSource source = TestDataSource();
int rowsPerPage = 3;
final int rowCount = source.rowCount;
addTearDown(source.dispose);
Widget buildTable(TestDataSource source, int rowsPerPage) {
return PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: rowsPerPage,
showFirstLastButtons: true,
dataRowHeight: 46,
availableRowsPerPage: const <int>[
3, 6, 7, 8, 9,
],
onRowsPerPageChanged: (int? rowsPerPage) {
},
onPageChanged: (int rowIndex) {
},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
showEmptyRows: false,
);
}
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: Center(child: buildTable(source, rowsPerPage)))
));
expect(find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == 0), findsOneWidget);
await tester.tap(find.byIcon(Icons.skip_next));
await tester.pump();
expect(find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == (rowsPerPage - (rowCount % rowsPerPage)) * 46.0), findsOneWidget);
rowsPerPage = 6;
await tester.pumpWidget(MaterialApp(
home: buildTable(source, rowsPerPage)
));
await tester.tap(find.byIcon(Icons.skip_previous));
await tester.pump();
expect(find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == 0), findsOneWidget);
await tester.tap(find.byIcon(Icons.skip_next));
await tester.pump();
expect(find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == (rowsPerPage - (rowCount % rowsPerPage)) * 46.0), findsOneWidget);
rowsPerPage = 7;
await tester.pumpWidget(MaterialApp(
home: buildTable(source, rowsPerPage)
));
await tester.tap(find.byIcon(Icons.skip_previous));
await tester.pump();
expect(find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == 0), findsOneWidget);
await tester.tap(find.byIcon(Icons.skip_next));
await tester.pump();
expect(find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == (rowsPerPage - (rowCount % rowsPerPage)) * 46.0), findsOneWidget);
rowsPerPage = 8;
await tester.pumpWidget(MaterialApp(
home: buildTable(source, rowsPerPage)
));
await tester.tap(find.byIcon(Icons.skip_previous));
await tester.pump();
expect(find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == 0), findsOneWidget);
await tester.tap(find.byIcon(Icons.skip_next));
await tester.pump();
expect(find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == (rowsPerPage - (rowCount % rowsPerPage)) * 46.0), findsOneWidget);
});
testWidgets('PaginatedDataTable control test', (WidgetTester tester) async {
TestDataSource source = TestDataSource()
..generation = 42;
addTearDown(source.dispose);
final List<String> log = <String>[];
Widget buildTable(TestDataSource source) {
return PaginatedDataTable(
header: const Text('Test table'),
source: source,
onPageChanged: (int rowIndex) {
log.add('page-changed: $rowIndex');
},
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {
log.add('column-sort: $columnIndex $ascending');
},
),
const DataColumn(
label: Text('Generation'),
tooltip: 'Generation',
),
],
actions: <Widget>[
IconButton(
icon: const Icon(Icons.adjust),
onPressed: () {
log.add('action: adjust');
},
),
],
);
}
await tester.pumpWidget(MaterialApp(
home: buildTable(source),
));
// the column overflows because we're forcing it to 600 pixels high
final dynamic exception = tester.takeException();
expect(exception, isFlutterError);
// ignore: avoid_dynamic_calls
expect(exception.diagnostics.first.level, DiagnosticLevel.summary);
// ignore: avoid_dynamic_calls
expect(exception.diagnostics.first.toString(), startsWith('A RenderFlex overflowed by '));
expect(find.text('Gingerbread (0)'), findsOneWidget);
expect(find.text('Gingerbread (1)'), findsNothing);
expect(find.text('42'), findsNWidgets(10));
source.generation = 43;
await tester.pump();
expect(find.text('42'), findsNothing);
expect(find.text('43'), findsNWidgets(10));
source = TestDataSource()
..generation = 15;
addTearDown(source.dispose);
await tester.pumpWidget(MaterialApp(
home: buildTable(source),
));
expect(find.text('42'), findsNothing);
expect(find.text('43'), findsNothing);
expect(find.text('15'), findsNWidgets(10));
final PaginatedDataTableState state = tester.state(find.byType(PaginatedDataTable));
expect(log, isEmpty);
state.pageTo(23);
expect(log, <String>['page-changed: 20']);
log.clear();
await tester.pump();
expect(find.text('Gingerbread (0)'), findsNothing);
expect(find.text('Gingerbread (1)'), findsNothing);
expect(find.text('Gingerbread (2)'), findsOneWidget);
await tester.tap(find.byIcon(Icons.adjust));
expect(log, <String>['action: adjust']);
log.clear();
});
testWidgets('PaginatedDataTable text alignment', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: PaginatedDataTable(
header: const Text('HEADER'),
source: source,
rowsPerPage: 8,
availableRowsPerPage: const <int>[
8, 9,
],
onRowsPerPageChanged: (int? rowsPerPage) { },
columns: const <DataColumn>[
DataColumn(label: Text('COL1')),
DataColumn(label: Text('COL2')),
DataColumn(label: Text('COL3')),
],
),
));
expect(find.text('Rows per page:'), findsOneWidget);
expect(find.text('8'), findsOneWidget);
expect(tester.getTopRight(find.text('8')).dx, tester.getTopRight(find.text('Rows per page:')).dx + 40.0); // per spec
});
testWidgets('PaginatedDataTable with and without header and actions', (WidgetTester tester) async {
await binding.setSurfaceSize(const Size(800, 800));
const String headerText = 'HEADER';
final List<Widget> actions = <Widget>[
IconButton(onPressed: () {}, icon: const Icon(Icons.add)),
];
final TestDataSource source = TestDataSource(allowSelection: true);
addTearDown(source.dispose);
Widget buildTable({String? header, List<Widget>? actions}) => MaterialApp(
home: PaginatedDataTable(
header: header != null ? Text(header) : null,
actions: actions,
source: source,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
);
await tester.pumpWidget(buildTable(header: headerText));
expect(find.text(headerText), findsOneWidget);
expect(find.byIcon(Icons.add), findsNothing);
await tester.pumpWidget(buildTable(header: headerText, actions: actions));
expect(find.text(headerText), findsOneWidget);
expect(find.byIcon(Icons.add), findsOneWidget);
await tester.pumpWidget(buildTable());
expect(find.text(headerText), findsNothing);
expect(find.byIcon(Icons.add), findsNothing);
expect(() => buildTable(actions: actions), throwsAssertionError);
await binding.setSurfaceSize(null);
});
testWidgets('PaginatedDataTable with large text', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: MediaQuery.withClampedTextScaling(
minScaleFactor: 20.0,
maxScaleFactor: 20.0,
child: PaginatedDataTable(
header: const Text('HEADER'),
source: source,
rowsPerPage: 501,
availableRowsPerPage: const <int>[ 501 ],
onRowsPerPageChanged: (int? rowsPerPage) { },
columns: const <DataColumn>[
DataColumn(label: Text('COL1')),
DataColumn(label: Text('COL2')),
DataColumn(label: Text('COL3')),
],
),
),
));
// the column overflows because we're forcing it to 600 pixels high
final dynamic exception = tester.takeException();
expect(exception, isFlutterError);
// ignore: avoid_dynamic_calls
expect(exception.diagnostics.first.level, DiagnosticLevel.summary);
// ignore: avoid_dynamic_calls
expect(exception.diagnostics.first.toString(), contains('A RenderFlex overflowed by'));
expect(find.text('Rows per page:'), findsOneWidget);
// Test that we will show some options in the drop down even if the lowest option is bigger than the source:
assert(501 > source.rowCount);
expect(find.text('501'), findsOneWidget);
// Test that it fits:
expect(tester.getTopRight(find.text('501')).dx, greaterThanOrEqualTo(tester.getTopRight(find.text('Rows per page:')).dx + 40.0));
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/43433
testWidgets('PaginatedDataTable footer scrolls', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 100.0,
child: PaginatedDataTable(
header: const Text('HEADER'),
source: source,
rowsPerPage: 5,
dragStartBehavior: DragStartBehavior.down,
availableRowsPerPage: const <int>[ 5 ],
onRowsPerPageChanged: (int? rowsPerPage) { },
columns: const <DataColumn>[
DataColumn(label: Text('COL1')),
DataColumn(label: Text('COL2')),
DataColumn(label: Text('COL3')),
],
),
),
),
),
);
expect(find.text('Rows per page:'), findsOneWidget);
expect(tester.getTopLeft(find.text('Rows per page:')).dx, lessThan(0.0)); // off screen
await tester.dragFrom(
Offset(50.0, tester.getTopLeft(find.text('Rows per page:')).dy),
const Offset(1000.0, 0.0),
);
await tester.pump();
expect(find.text('Rows per page:'), findsOneWidget);
expect(tester.getTopLeft(find.text('Rows per page:')).dx, 18.0); // 14 padding in the footer row, 4 padding from the card
});
testWidgets('PaginatedDataTable custom row height', (WidgetTester tester) async {
Widget buildCustomHeightPaginatedTable({
double? dataRowHeight,
double? dataRowMinHeight,
double? dataRowMaxHeight,
double headingRowHeight = 56.0,
}) {
return PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
availableRowsPerPage: const <int>[
2, 4, 8, 16,
],
onRowsPerPageChanged: (int? rowsPerPage) {},
onPageChanged: (int rowIndex) {},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
dataRowHeight: dataRowHeight,
dataRowMinHeight: dataRowMinHeight,
dataRowMaxHeight: dataRowMaxHeight,
headingRowHeight: headingRowHeight,
);
}
// DEFAULT VALUES
await tester.pumpWidget(MaterialApp(
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
availableRowsPerPage: const <int>[
2, 4, 8, 16,
],
onRowsPerPageChanged: (int? rowsPerPage) {},
onPageChanged: (int rowIndex) {},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
));
expect(tester.renderObject<RenderBox>(
find.widgetWithText(Container, 'Name').first,
).size.height, 56.0); // This is the header row height
expect(tester.renderObject<RenderBox>(
find.widgetWithText(Container, 'Frozen yogurt (0)').first,
).size.height, 48.0); // This is the data row height
// CUSTOM VALUES
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomHeightPaginatedTable(headingRowHeight: 48.0)),
));
expect(tester.renderObject<RenderBox>(
find.widgetWithText(Container, 'Name').first,
).size.height, 48.0);
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomHeightPaginatedTable(headingRowHeight: 64.0)),
));
expect(tester.renderObject<RenderBox>(
find.widgetWithText(Container, 'Name').first,
).size.height, 64.0);
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomHeightPaginatedTable(dataRowHeight: 30.0)),
));
expect(tester.renderObject<RenderBox>(
find.widgetWithText(Container, 'Frozen yogurt (0)').first,
).size.height, 30.0);
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomHeightPaginatedTable(dataRowHeight: 56.0)),
));
expect(tester.renderObject<RenderBox>(
find.widgetWithText(Container, 'Frozen yogurt (0)').first,
).size.height, 56.0);
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomHeightPaginatedTable(dataRowMinHeight: 51.0, dataRowMaxHeight: 51.0)),
));
expect(tester.renderObject<RenderBox>(
find.widgetWithText(Container, 'Frozen yogurt (0)').first,
).size.height, 51.0);
});
testWidgets('PaginatedDataTable custom horizontal padding - checkbox', (WidgetTester tester) async {
const double defaultHorizontalMargin = 24.0;
const double defaultColumnSpacing = 56.0;
const double customHorizontalMargin = 10.0;
const double customColumnSpacing = 15.0;
const double width = 400;
const double height = 400;
final Size originalSize = binding.renderView.size;
// Ensure the containing Card is small enough that we don't expand too
// much, resulting in our custom margin being ignored.
await binding.setSurfaceSize(const Size(width, height));
final TestDataSource source = TestDataSource(allowSelection: true);
addTearDown(source.dispose);
Finder cellContent;
Finder checkbox;
Finder padding;
await tester.pumpWidget(MaterialApp(
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
availableRowsPerPage: const <int>[
2, 4,
],
onRowsPerPageChanged: (int? rowsPerPage) {},
onPageChanged: (int rowIndex) {},
onSelectAll: (bool? value) {},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
));
// default checkbox padding
checkbox = find.byType(Checkbox).first;
padding = find.ancestor(of: checkbox, matching: find.byType(Padding)).first;
expect(
tester.getRect(checkbox).left - tester.getRect(padding).left,
defaultHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(checkbox).right,
defaultHorizontalMargin / 2,
);
// default first column padding
padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)'); // DataTable wraps its DataCells in an Align widget
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultHorizontalMargin / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultColumnSpacing / 2,
);
// default middle column padding
padding = find.widgetWithText(Padding, '159').first;
cellContent = find.widgetWithText(Align, '159');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultColumnSpacing / 2,
);
// default last column padding
padding = find.widgetWithText(Padding, '0').first;
cellContent = find.widgetWithText(Align, '0').first;
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultHorizontalMargin,
);
// CUSTOM VALUES
await tester.pumpWidget(MaterialApp(
home: Material(
child: PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
availableRowsPerPage: const <int>[
2, 4,
],
onRowsPerPageChanged: (int? rowsPerPage) {},
onPageChanged: (int rowIndex) {},
onSelectAll: (bool? value) {},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
horizontalMargin: customHorizontalMargin,
columnSpacing: customColumnSpacing,
),
),
));
// custom checkbox padding
checkbox = find.byType(Checkbox).first;
padding = find.ancestor(of: checkbox, matching: find.byType(Padding)).first;
expect(
tester.getRect(checkbox).left - tester.getRect(padding).left,
customHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(checkbox).right,
customHorizontalMargin / 2,
);
// custom first column padding
padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)'); // DataTable wraps its DataCells in an Align widget
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customHorizontalMargin / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customColumnSpacing / 2,
);
// custom middle column padding
padding = find.widgetWithText(Padding, '159').first;
cellContent = find.widgetWithText(Align, '159');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customColumnSpacing / 2,
);
// custom last column padding
padding = find.widgetWithText(Padding, '0').first;
cellContent = find.widgetWithText(Align, '0').first;
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customHorizontalMargin,
);
// Reset the surface size.
await binding.setSurfaceSize(originalSize);
});
testWidgets('PaginatedDataTable custom horizontal padding - no checkbox', (WidgetTester tester) async {
const double defaultHorizontalMargin = 24.0;
const double defaultColumnSpacing = 56.0;
const double customHorizontalMargin = 10.0;
const double customColumnSpacing = 15.0;
Finder cellContent;
Finder padding;
await tester.pumpWidget(MaterialApp(
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
availableRowsPerPage: const <int>[
2, 4, 8, 16,
],
onRowsPerPageChanged: (int? rowsPerPage) {},
onPageChanged: (int rowIndex) {},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
));
// default first column padding
padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)'); // DataTable wraps its DataCells in an Align widget
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultColumnSpacing / 2,
);
// default middle column padding
padding = find.widgetWithText(Padding, '159').first;
cellContent = find.widgetWithText(Align, '159');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultColumnSpacing / 2,
);
// default last column padding
padding = find.widgetWithText(Padding, '0').first;
cellContent = find.widgetWithText(Align, '0').first;
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultHorizontalMargin,
);
// CUSTOM VALUES
await tester.pumpWidget(MaterialApp(
home: Material(
child: PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
availableRowsPerPage: const <int>[
2, 4, 8, 16,
],
onRowsPerPageChanged: (int? rowsPerPage) {},
onPageChanged: (int rowIndex) {},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
horizontalMargin: customHorizontalMargin,
columnSpacing: customColumnSpacing,
),
),
));
// custom first column padding
padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customColumnSpacing / 2,
);
// custom middle column padding
padding = find.widgetWithText(Padding, '159').first;
cellContent = find.widgetWithText(Align, '159');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customColumnSpacing / 2,
);
// custom last column padding
padding = find.widgetWithText(Padding, '0').first;
cellContent = find.widgetWithText(Align, '0').first;
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customHorizontalMargin,
);
});
testWidgets('PaginatedDataTable table fills Card width', (WidgetTester tester) async {
// 800 is wide enough to ensure that all of the columns fit in the
// Card. The test makes sure that the DataTable is exactly as wide
// as the Card, minus the Card's margin.
const double originalWidth = 800;
const double expandedWidth = 1600;
const double height = 400;
// By default, the margin of a Card is 4 in all directions, so
// the size of the DataTable (inside the Card) is horizontally
// reduced by 4 * 2; the left and right margins.
const double cardMargin = 8;
final Size originalSize = binding.renderView.size;
Widget buildWidget() => MaterialApp(
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
availableRowsPerPage: const <int>[
2, 4, 8, 16,
],
onRowsPerPageChanged: (int? rowsPerPage) {},
onPageChanged: (int rowIndex) {},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
);
await binding.setSurfaceSize(const Size(originalWidth, height));
await tester.pumpWidget(buildWidget());
double cardWidth = tester.renderObject<RenderBox>(find.byType(Card).first).size.width;
// Widths should be equal before we resize...
expect(
tester.renderObject<RenderBox>(find.byType(DataTable).first).size.width,
moreOrLessEquals(cardWidth - cardMargin),
);
await binding.setSurfaceSize(const Size(expandedWidth, height));
await tester.pumpWidget(buildWidget());
cardWidth = tester.renderObject<RenderBox>(find.byType(Card).first).size.width;
// ... and should still be equal after the resize.
expect(
tester.renderObject<RenderBox>(find.byType(DataTable).first).size.width,
moreOrLessEquals(cardWidth - cardMargin),
);
// Double check to ensure we actually resized the surface properly.
expect(cardWidth, moreOrLessEquals(expandedWidth));
// Reset the surface size.
await binding.setSurfaceSize(originalSize);
});
testWidgets('PaginatedDataTable with optional column checkbox', (WidgetTester tester) async {
await binding.setSurfaceSize(const Size(800, 800));
addTearDown(() => binding.setSurfaceSize(null));
final TestDataSource source = TestDataSource(allowSelection: true);
addTearDown(source.dispose);
Widget buildTable(bool checkbox) => MaterialApp(
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
showCheckboxColumn: checkbox,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
);
await tester.pumpWidget(buildTable(true));
expect(find.byType(Checkbox), findsNWidgets(11));
await tester.pumpWidget(buildTable(false));
expect(find.byType(Checkbox), findsNothing);
});
testWidgets('Table should not use decoration from DataTableTheme', (WidgetTester tester) async {
final Size originalSize = binding.renderView.size;
await binding.setSurfaceSize(const Size(800, 800));
Widget buildTable() {
final TestDataSource source = TestDataSource(allowSelection: true);
addTearDown(source.dispose);
return MaterialApp(
theme: ThemeData.light().copyWith(
dataTableTheme: const DataTableThemeData(
decoration: BoxDecoration(color: Colors.white),
),
),
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
);
}
await tester.pumpWidget(buildTable());
final Finder tableContainerFinder = find.ancestor(of: find.byType(Table), matching: find.byType(Container)).first;
expect(tester.widget<Container>(tableContainerFinder).decoration, const BoxDecoration());
// Reset the surface size.
await binding.setSurfaceSize(originalSize);
});
testWidgets('dataRowMinHeight & dataRowMaxHeight if not set will use DataTableTheme', (WidgetTester tester) async {
addTearDown(() => binding.setSurfaceSize(null));
await binding.setSurfaceSize(const Size(800, 800));
const double minMaxDataRowHeight = 30.0;
final TestDataSource source = TestDataSource(allowSelection: true);
addTearDown(source.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
dataTableTheme: const DataTableThemeData(
dataRowMinHeight: minMaxDataRowHeight,
dataRowMaxHeight: minMaxDataRowHeight,
),
),
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
));
final Container rowContainer = tester.widget<Container>(find.descendant(
of: find.byType(Table),
matching: find.byType(Container),
).last);
expect(rowContainer.constraints?.minHeight, minMaxDataRowHeight);
expect(rowContainer.constraints?.maxHeight, minMaxDataRowHeight);
});
testWidgets('PaginatedDataTable custom checkboxHorizontalMargin properly applied', (WidgetTester tester) async {
const double customCheckboxHorizontalMargin = 15.0;
const double customHorizontalMargin = 10.0;
const double width = 400;
const double height = 400;
final Size originalSize = binding.renderView.size;
// Ensure the containing Card is small enough that we don't expand too
// much, resulting in our custom margin being ignored.
await binding.setSurfaceSize(const Size(width, height));
final TestDataSource source = TestDataSource(allowSelection: true);
addTearDown(source.dispose);
Finder cellContent;
Finder checkbox;
Finder padding;
// CUSTOM VALUES
await tester.pumpWidget(MaterialApp(
home: Material(
child: PaginatedDataTable(
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
availableRowsPerPage: const <int>[
2, 4,
],
onRowsPerPageChanged: (int? rowsPerPage) {},
onPageChanged: (int rowIndex) {},
onSelectAll: (bool? value) {},
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
horizontalMargin: customHorizontalMargin,
checkboxHorizontalMargin: customCheckboxHorizontalMargin,
),
),
));
// Custom checkbox padding.
checkbox = find.byType(Checkbox).first;
padding = find.ancestor(of: checkbox, matching: find.byType(Padding)).first;
expect(
tester.getRect(checkbox).left - tester.getRect(padding).left,
customCheckboxHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(checkbox).right,
customCheckboxHorizontalMargin,
);
// Custom first column padding.
padding = find.widgetWithText(Padding, 'Frozen yogurt (0)').first;
cellContent = find.widgetWithText(Align, 'Frozen yogurt (0)'); // DataTable wraps its DataCells in an Align widget.
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customHorizontalMargin,
);
// Reset the surface size.
await binding.setSurfaceSize(originalSize);
});
testWidgets('Items selected text uses secondary color', (WidgetTester tester) async {
const Color selectedTextColor = Color(0xff00ddff);
final ColorScheme colors = const ColorScheme.light().copyWith(secondary: selectedTextColor);
final ThemeData theme = ThemeData.from(colorScheme: colors);
final TestDataSource source = TestDataSource(allowSelection: true);
addTearDown(source.dispose);
Widget buildTable() {
return MaterialApp(
theme: theme,
home: PaginatedDataTable(
header: const Text('Test table'),
source: source,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
);
}
await binding.setSurfaceSize(const Size(800, 800));
await tester.pumpWidget(buildTable());
expect(find.text('Test table'), findsOneWidget);
// Select a row with yogurt
await tester.tap(find.text('Frozen yogurt (0)'));
await tester.pumpAndSettle();
// The header should be replace with a selected text item
expect(find.text('Test table'), findsNothing);
expect(find.text('1 item selected'), findsOneWidget);
// The color of the selected text item should be the colorScheme.secondary
final TextStyle selectedTextStyle = tester.renderObject<RenderParagraph>(find.text('1 item selected')).text.style!;
expect(selectedTextStyle.color, equals(selectedTextColor));
await binding.setSurfaceSize(null);
});
testWidgets('PaginatedDataTable arrowHeadColor set properly', (WidgetTester tester) async {
await binding.setSurfaceSize(const Size(800, 800));
addTearDown(() => binding.setSurfaceSize(null));
const Color arrowHeadColor = Color(0xFFE53935);
await tester.pumpWidget(
MaterialApp(
home: PaginatedDataTable(
arrowHeadColor: arrowHeadColor,
showFirstLastButtons: true,
header: const Text('Test table'),
source: source,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
)
);
final Iterable<Icon> icons = tester.widgetList(find.byType(Icon));
expect(icons.elementAt(0).color, arrowHeadColor);
expect(icons.elementAt(1).color, arrowHeadColor);
expect(icons.elementAt(2).color, arrowHeadColor);
expect(icons.elementAt(3).color, arrowHeadColor);
});
testWidgets('OverflowBar header left alignment', (WidgetTester tester) async {
// Test an old special case that tried to align the first child of a ButtonBar
// and the left edge of a Text header widget. Still possible with OverflowBar
// albeit without any special case in the implementation's build method.
Widget buildFrame(Widget header) {
return MaterialApp(
home: PaginatedDataTable(
header: header,
rowsPerPage: 2,
source: source,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
);
}
await tester.pumpWidget(buildFrame(const Text('HEADER')));
final double headerX = tester.getTopLeft(find.text('HEADER')).dx;
final Widget overflowBar = OverflowBar(
children: <Widget>[ElevatedButton(onPressed: () {}, child: const Text('BUTTON'))],
);
await tester.pumpWidget(buildFrame(overflowBar));
expect(headerX, tester.getTopLeft(find.byType(ElevatedButton)).dx);
});
testWidgets('PaginatedDataTable can be scrolled using ScrollController', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
Widget buildTable(TestDataSource source) {
return Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 100,
child: PaginatedDataTable(
controller: scrollController,
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
columns: const <DataColumn>[
DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: Text('Calories'),
tooltip: 'Calories',
numeric: true,
),
DataColumn(
label: Text('Generation'),
tooltip: 'Generation',
),
],
),
),
);
}
await tester.pumpWidget(MaterialApp(
home: buildTable(source),
));
// DataTable uses provided ScrollController
final Scrollable bodyScrollView = tester.widget(find.byType(Scrollable).first);
expect(bodyScrollView.controller, scrollController);
expect(scrollController.offset, 0.0);
scrollController.jumpTo(50.0);
await tester.pumpAndSettle();
expect(scrollController.offset, 50.0);
});
testWidgets('PaginatedDataTable uses PrimaryScrollController when primary ', (WidgetTester tester) async {
final ScrollController primaryScrollController = ScrollController();
addTearDown(primaryScrollController.dispose);
await tester.pumpWidget(
MaterialApp(
home: PrimaryScrollController(
controller: primaryScrollController,
child: PaginatedDataTable(
primary: true,
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
),
)
);
// DataTable uses primaryScrollController
final Scrollable bodyScrollView = tester.widget(find.byType(Scrollable).first);
expect(bodyScrollView.controller, primaryScrollController);
// Footer does not use primaryScrollController
final Scrollable footerScrollView = tester.widget(find.byType(Scrollable).last);
expect(footerScrollView.controller, null);
});
testWidgets('PaginatedDataTable custom heading row color', (WidgetTester tester) async {
const MaterialStateProperty<Color> headingRowColor = MaterialStatePropertyAll<Color>(Color(0xffFF0000));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: PaginatedDataTable(
primary: true,
header: const Text('Test table'),
source: source,
rowsPerPage: 2,
headingRowColor: headingRowColor,
columns: const <DataColumn>[
DataColumn(label: Text('Name')),
DataColumn(label: Text('Calories'), numeric: true),
DataColumn(label: Text('Generation')),
],
),
),
)
);
final Table table = tester.widget(find.byType(Table));
final TableRow tableRow = table.children[0];
final BoxDecoration tableRowBoxDecoration = tableRow.decoration! as BoxDecoration;
expect(tableRowBoxDecoration.color, headingRowColor.resolve(<MaterialState>{}));
});
}
| flutter/packages/flutter/test/material/paginated_data_table_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/paginated_data_table_test.dart",
"repo_id": "flutter",
"token_count": 18860
} | 657 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
// The const represents the starting position of the scrollbar thumb for
// the below tests. The thumb is 90 pixels long, and 8 pixels wide, with a 2
// pixel margin to the right edge of the viewport.
const Rect _kMaterialDesignInitialThumbRect = Rect.fromLTRB(790.0, 0.0, 798.0, 90.0);
const Radius _kDefaultThumbRadius = Radius.circular(8.0);
const Color _kDefaultIdleThumbColor = Color(0x1a000000);
const Color _kDefaultDragThumbColor = Color(0x99000000);
void main() {
test('ScrollbarThemeData copyWith, ==, hashCode basics', () {
expect(const ScrollbarThemeData(), const ScrollbarThemeData().copyWith());
expect(const ScrollbarThemeData().hashCode, const ScrollbarThemeData().copyWith().hashCode);
});
test('ScrollbarThemeData lerp special cases', () {
expect(ScrollbarThemeData.lerp(null, null, 0), const ScrollbarThemeData());
const ScrollbarThemeData data = ScrollbarThemeData();
expect(identical(ScrollbarThemeData.lerp(data, data, 0.5), data), true);
});
testWidgets('Passing no ScrollbarTheme returns defaults', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: false,
scrollbarTheme: ScrollbarThemeData(
trackVisibility: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return true;
}
return false;
})
)
),
home: ScrollConfiguration(
behavior: const NoScrollbarBehavior(),
child: Scrollbar(
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
),
),
);
await tester.pumpAndSettle();
// Idle scrollbar behavior
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
_kMaterialDesignInitialThumbRect,
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
// Drag scrollbar behavior
const double scrollAmount = 10.0;
final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
_kMaterialDesignInitialThumbRect,
_kDefaultThumbRadius,
),
// Drag color
color: _kDefaultDragThumbColor,
),
);
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
// Hover scrollbar behavior
final TestGesture gesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(const Offset(794.0, 5.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(784.0, 0.0, 800.0, 600.0),
color: const Color(0x08000000),
)
..line(
p1: const Offset(784.0, 0.0),
p2: const Offset(784.0, 600.0),
strokeWidth: 1.0,
color: const Color(0x1a000000),
)
..rrect(
rrect: RRect.fromRectAndRadius(
// Scrollbar thumb is larger
const Rect.fromLTRB(786.0, 10.0, 798.0, 100.0),
_kDefaultThumbRadius,
),
// Hover color
color: const Color(0x80000000),
),
);
scrollController.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
TargetPlatform.fuchsia,
}),
);
testWidgets('Scrollbar uses values from ScrollbarTheme', (WidgetTester tester) async {
final ScrollbarThemeData scrollbarTheme = _scrollbarTheme();
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
scrollbarTheme: scrollbarTheme,
),
home: ScrollConfiguration(
behavior: const NoScrollbarBehavior(),
child: Scrollbar(
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
),
));
await tester.pumpAndSettle();
// Idle scrollbar behavior
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(785.0, 10.0, 795.0, 97.0),
const Radius.circular(6.0),
),
color: const Color(0xff4caf50),
),
);
// Drag scrollbar behavior
const double scrollAmount = 10.0;
final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(785.0, 10.0, 795.0, 97.0),
const Radius.circular(6.0),
),
// Drag color
color: const Color(0xfff44336),
),
);
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
// Hover scrollbar behavior
final TestGesture gesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(const Offset(794.0, 15.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(770.0, 0.0, 800.0, 600.0),
color: const Color(0xff000000),
)
..line(
p1: const Offset(770.0, 00.0),
p2: const Offset(770.0, 600.0),
strokeWidth: 1.0,
color: const Color(0xffffeb3b),
)
..rrect(
rrect: RRect.fromRectAndRadius(
// Scrollbar thumb is larger
const Rect.fromLTRB(775.0, 20.0, 795.0, 107.0),
const Radius.circular(6.0),
),
// Hover color
color: const Color(0xff2196f3),
),
);
scrollController.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
TargetPlatform.fuchsia,
}),
);
testWidgets(
'Scrollbar uses values from ScrollbarTheme if exists instead of values from Theme',
(WidgetTester tester) async {
final ScrollbarThemeData scrollbarTheme = _scrollbarTheme();
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
scrollbarTheme: scrollbarTheme,
),
home: ScrollConfiguration(
behavior: const NoScrollbarBehavior(),
child: ScrollbarTheme(
data: _scrollbarTheme().copyWith(
thumbColor: MaterialStateProperty.all(const Color(0xFF000000)),
),
child: Scrollbar(
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
),
),
),
);
await tester.pumpAndSettle();
// Idle scrollbar behavior
expect(
find.byType(Scrollbar),
paints
..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(785.0, 10.0, 795.0, 97.0),
const Radius.circular(6.0),
),
color: const Color(0xFF000000),
),
);
scrollController.dispose();
},
);
testWidgets('ScrollbarTheme can disable gestures', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false, scrollbarTheme: const ScrollbarThemeData(interactive: false)),
home: Scrollbar(
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
));
await tester.pumpAndSettle();
// Idle scrollbar behavior
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
_kMaterialDesignInitialThumbRect,
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
// Try to drag scrollbar.
const double scrollAmount = 10.0;
final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
// Expect no change
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
_kMaterialDesignInitialThumbRect,
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
scrollController.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.fuchsia }));
testWidgets('Scrollbar.interactive takes priority over ScrollbarTheme', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false, scrollbarTheme: const ScrollbarThemeData(interactive: false)),
home: Scrollbar(
interactive: true,
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
));
await tester.pumpAndSettle();
// Idle scrollbar behavior
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
_kMaterialDesignInitialThumbRect,
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
// Drag scrollbar.
const double scrollAmount = 10.0;
final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
// Gestures handled by Scrollbar.
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(790.0, 10.0, 798.0, 100.0),
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
scrollController.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.fuchsia }));
testWidgets('Scrollbar widget properties take priority over theme', (WidgetTester tester) async {
const double thickness = 4.0;
const double edgeMargin = 2.0;
const Radius radius = Radius.circular(3.0);
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: const ColorScheme.light(),
scrollbarTheme: ScrollbarThemeData(
trackVisibility: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return true;
}
return false;
})
),
),
home: ScrollConfiguration(
behavior: const NoScrollbarBehavior(),
child: Scrollbar(
thickness: thickness,
thumbVisibility: true,
radius: radius,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
),
),
);
await tester.pumpAndSettle();
// Idle scrollbar behavior
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(800 - thickness - edgeMargin, 0.0, 798.0, 90.0),
const Radius.circular(3.0),
),
color: _kDefaultIdleThumbColor,
),
);
// Drag scrollbar behavior.
const double scrollAmount = 10.0;
final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(800 - thickness - edgeMargin, 0.0, 798.0, 90.0),
const Radius.circular(3.0),
),
// Drag color
color: _kDefaultDragThumbColor,
),
);
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
// Hover scrollbar behavior.
final TestGesture gesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(const Offset(794.0, 5.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(792.0, 0.0, 800.0, 600.0),
color: const Color(0x08000000),
)
..line(
p1: const Offset(792.0, 0.0),
p2: const Offset(792.0, 600.0),
strokeWidth: 1.0,
color: const Color(0x1a000000),
)
..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(800 - thickness - edgeMargin, 10.0, 798.0, 100.0),
const Radius.circular(3.0),
),
// Hover color
color: const Color(0x80000000),
),
);
scrollController.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
TargetPlatform.fuchsia,
}),
);
testWidgets('ThemeData colorScheme is used when no ScrollbarTheme is set', (WidgetTester tester) async {
(ScrollController, Widget) buildFrame(ThemeData appTheme) {
final ScrollController scrollController = ScrollController();
final ThemeData theme = appTheme.copyWith(
scrollbarTheme: ScrollbarThemeData(
trackVisibility: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return true;
}
return false;
})
),
);
return (
scrollController,
MaterialApp(
theme: theme,
home: ScrollConfiguration(
behavior: const NoScrollbarBehavior(),
child: Scrollbar(
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
),
),
);
}
// Scrollbar defaults for light themes:
// - coloring based on ColorScheme.onSurface
final (ScrollController controller1, Widget frame1) = buildFrame(ThemeData(
colorScheme: const ColorScheme.light(),
));
await tester.pumpWidget(frame1);
await tester.pumpAndSettle();
// Idle scrollbar behavior
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
_kMaterialDesignInitialThumbRect,
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
// Drag scrollbar behavior
const double scrollAmount = 10.0;
TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
_kMaterialDesignInitialThumbRect,
_kDefaultThumbRadius,
),
// Drag color
color: _kDefaultDragThumbColor,
),
);
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
// Hover scrollbar behavior
final TestGesture hoverGesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await hoverGesture.addPointer();
addTearDown(hoverGesture.removePointer);
await hoverGesture.moveTo(const Offset(794.0, 5.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(784.0, 0.0, 800.0, 600.0),
color: const Color(0x08000000),
)
..line(
p1: const Offset(784.0, 0.0),
p2: const Offset(784.0, 600.0),
strokeWidth: 1.0,
color: const Color(0x1a000000),
)
..rrect(
rrect: RRect.fromRectAndRadius(
// Scrollbar thumb is larger
const Rect.fromLTRB(786.0, 10.0, 798.0, 100.0),
_kDefaultThumbRadius,
),
// Hover color
color: const Color(0x80000000),
),
);
await hoverGesture.moveTo(Offset.zero);
// Scrollbar defaults for dark themes:
// - coloring slightly different based on ColorScheme.onSurface
final (ScrollController controller2, Widget frame2) = buildFrame(ThemeData(
colorScheme: const ColorScheme.dark(),
));
await tester.pumpWidget(frame2);
await tester.pumpAndSettle(); // Theme change animation
// Idle scrollbar behavior
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(790.0, 10.0, 798.0, 100.0),
_kDefaultThumbRadius,
),
color: const Color(0x4dffffff),
),
);
// Drag scrollbar behavior
dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
const Rect.fromLTRB(790.0, 10.0, 798.0, 100.0),
_kDefaultThumbRadius,
),
// Drag color
color: const Color(0xbfffffff),
),
);
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
// Hover scrollbar behavior
await hoverGesture.moveTo(const Offset(794.0, 5.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(784.0, 0.0, 800.0, 600.0),
color: const Color(0x0dffffff),
)
..line(
p1: const Offset(784.0, 0.0),
p2: const Offset(784.0, 600.0),
strokeWidth: 1.0,
color: const Color(0x40ffffff),
)
..rrect(
rrect: RRect.fromRectAndRadius(
// Scrollbar thumb is larger
const Rect.fromLTRB(786.0, 20.0, 798.0, 110.0),
_kDefaultThumbRadius,
),
// Hover color
color: const Color(0xa6ffffff),
),
);
controller1.dispose();
controller2.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
TargetPlatform.fuchsia,
}),
);
testWidgets('ScrollbarThemeData.trackVisibility test', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
bool? getTrackVisibility(Set<MaterialState> states) {
return true;
}
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false).copyWith(
scrollbarTheme: _scrollbarTheme(
trackVisibility: MaterialStateProperty.resolveWith(getTrackVisibility),
),
),
home: ScrollConfiguration(
behavior: const NoScrollbarBehavior(),
child: Scrollbar(
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
),
),
);
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(color: const Color(0x08000000))
..line(
strokeWidth: 1.0,
color: const Color(0x1a000000),
)
..rrect(color: const Color(0xff4caf50)),
);
scrollController.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
TargetPlatform.fuchsia,
}),
);
testWidgets('Default ScrollbarTheme debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const ScrollbarThemeData().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('ScrollbarTheme implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
ScrollbarThemeData(
thickness: MaterialStateProperty.resolveWith(_getThickness),
thumbVisibility: MaterialStateProperty.resolveWith(_getThumbVisibility),
radius: const Radius.circular(3.0),
thumbColor: MaterialStateProperty.resolveWith(_getThumbColor),
trackColor: MaterialStateProperty.resolveWith(_getTrackColor),
trackBorderColor: MaterialStateProperty.resolveWith(_getTrackBorderColor),
crossAxisMargin: 3.0,
mainAxisMargin: 6.0,
minThumbLength: 120.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>[
"thumbVisibility: Instance of '_WidgetStatePropertyWith<bool?>'",
"thickness: Instance of '_WidgetStatePropertyWith<double?>'",
'radius: Radius.circular(3.0)',
"thumbColor: Instance of '_WidgetStatePropertyWith<Color?>'",
"trackColor: Instance of '_WidgetStatePropertyWith<Color?>'",
"trackBorderColor: Instance of '_WidgetStatePropertyWith<Color?>'",
'crossAxisMargin: 3.0',
'mainAxisMargin: 6.0',
'minThumbLength: 120.0',
]);
// On the web, Dart doubles and ints are backed by the same kind of object because
// JavaScript does not support integers. So, the Dart double "4.0" is identical
// to "4", which results in the web evaluating to the value "4" regardless of which
// one is used. This results in a difference for doubles in debugFillProperties between
// the web and the rest of Flutter's target platforms.
}, skip: kIsWeb); // [intended]
}
class NoScrollbarBehavior extends ScrollBehavior {
const NoScrollbarBehavior();
@override
Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) => child;
}
ScrollbarThemeData _scrollbarTheme({
MaterialStateProperty<double?>? thickness,
MaterialStateProperty<bool?>? trackVisibility,
MaterialStateProperty<bool?>? thumbVisibility,
Radius radius = const Radius.circular(6.0),
MaterialStateProperty<Color?>? thumbColor,
MaterialStateProperty<Color?>? trackColor,
MaterialStateProperty<Color?>? trackBorderColor,
double crossAxisMargin = 5.0,
double mainAxisMargin = 10.0,
double minThumbLength = 50.0,
}) {
return ScrollbarThemeData(
thickness: thickness ?? MaterialStateProperty.resolveWith(_getThickness),
trackVisibility: trackVisibility ?? MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return true;
}
return false;
}),
thumbVisibility: thumbVisibility,
radius: radius,
thumbColor: thumbColor ?? MaterialStateProperty.resolveWith(_getThumbColor),
trackColor: trackColor ?? MaterialStateProperty.resolveWith(_getTrackColor),
trackBorderColor: trackBorderColor ?? MaterialStateProperty.resolveWith(_getTrackBorderColor),
crossAxisMargin: crossAxisMargin,
mainAxisMargin: mainAxisMargin,
minThumbLength: minThumbLength,
);
}
double? _getThickness(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return 20.0;
}
return 10.0;
}
bool? _getThumbVisibility(Set<MaterialState> states) => true;
Color? _getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.dragged)) {
return Colors.red;
}
if (states.contains(MaterialState.hovered)) {
return Colors.blue;
}
return Colors.green;
}
Color? _getTrackColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return Colors.black;
}
return null;
}
Color? _getTrackBorderColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return Colors.yellow;
}
return null;
}
| flutter/packages/flutter/test/material/scrollbar_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/scrollbar_theme_test.dart",
"repo_id": "flutter",
"token_count": 11533
} | 658 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
final ThemeData theme = ThemeData();
testWidgets('Switch can toggle on tap', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
key: switchKey,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
),
);
},
),
),
);
expect(value, isFalse);
await tester.tap(find.byKey(switchKey));
expect(value, isTrue);
});
testWidgets('Switch size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
Theme(
data: theme.copyWith(materialTapTargetSize: MaterialTapTargetSize.padded),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: true,
onChanged: (bool newValue) { },
),
),
),
),
),
);
// switch width = trackWidth - 2 * trackRadius + _kSwitchMinSize
// M2 width = 33 - 2 * 7 + 40
// M3 width = 52 - 2 * 16 + 40
expect(tester.getSize(find.byType(Switch)), material3 ? const Size(60.0, 48.0) : const Size(59.0, 48.0));
await tester.pumpWidget(
Theme(
data: theme.copyWith(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: true,
onChanged: (bool newValue) { },
),
),
),
),
),
);
expect(tester.getSize(find.byType(Switch)), material3 ? const Size(60.0, 40.0) : const Size(59.0, 40.0));
});
testWidgets('Material2 - Switch does not get distorted upon changing constraints with parent', (WidgetTester tester) async {
const double maxWidth = 300;
const double maxHeight = 100;
const ValueKey<String> boundaryKey = ValueKey<String>('switch container');
Widget buildSwitch({required double width, required double height}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: maxWidth,
height: maxHeight,
child: RepaintBoundary(
key: boundaryKey,
child: SizedBox(
width: width,
height: height,
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: true,
onChanged: (_) {},
),
),
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch(
width: maxWidth,
height: maxHeight,
));
await expectLater(
find.byKey(boundaryKey),
matchesGoldenFile('m2_switch_test.big.on.png'),
);
await tester.pumpWidget(buildSwitch(
width: 20,
height: 10,
));
await expectLater(
find.byKey(boundaryKey),
matchesGoldenFile('m2_switch_test.small.on.png'),
);
});
testWidgets('Material3 - Switch does not get distorted upon changing constraints with parent', (WidgetTester tester) async {
const double maxWidth = 300;
const double maxHeight = 100;
const ValueKey<String> boundaryKey = ValueKey<String>('switch container');
Widget buildSwitch({required double width, required double height}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: maxWidth,
height: maxHeight,
child: RepaintBoundary(
key: boundaryKey,
child: SizedBox(
width: width,
height: height,
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: true,
onChanged: (_) {},
),
),
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch(
width: maxWidth,
height: maxHeight,
));
await expectLater(
find.byKey(boundaryKey),
matchesGoldenFile('m3_switch_test.big.on.png'),
);
await tester.pumpWidget(buildSwitch(
width: 20,
height: 10,
));
await expectLater(
find.byKey(boundaryKey),
matchesGoldenFile('m3_switch_test.small.on.png'),
);
});
testWidgets('Switch can drag (LTR)', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
Theme(
data: theme,
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(value, isFalse);
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
expect(value, isFalse);
await tester.drag(find.byType(Switch), const Offset(30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(Switch), const Offset(30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
expect(value, isFalse);
});
testWidgets('Switch can drag with dragStartBehavior', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
Theme(
data: theme,
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(value, isFalse);
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
expect(value, isFalse);
await tester.drag(find.byType(Switch), const Offset(30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(Switch), const Offset(30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
expect(value, isFalse);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
);
await tester.pumpAndSettle();
final Rect switchRect = tester.getRect(find.byType(Switch));
TestGesture gesture = await tester.startGesture(switchRect.center);
// We have to execute the drag in two frames because the first update will
// just set the start position.
await gesture.moveBy(const Offset(20.0, 0.0));
await gesture.moveBy(const Offset(20.0, 0.0));
expect(value, isFalse);
await gesture.up();
expect(value, isTrue);
await tester.pump();
gesture = await tester.startGesture(switchRect.center);
await gesture.moveBy(const Offset(20.0, 0.0));
await gesture.moveBy(const Offset(20.0, 0.0));
expect(value, isTrue);
await gesture.up();
expect(value, isTrue);
await tester.pump();
gesture = await tester.startGesture(switchRect.center);
await gesture.moveBy(const Offset(-20.0, 0.0));
await gesture.moveBy(const Offset(-20.0, 0.0));
expect(value, isTrue);
await gesture.up();
expect(value, isFalse);
});
testWidgets('Switch can drag (RTL)', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
Theme(
data: theme,
child: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
await tester.drag(find.byType(Switch), const Offset(30.0, 0.0));
expect(value, isFalse);
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(Switch), const Offset(30.0, 0.0));
expect(value, isFalse);
});
testWidgets('Material2 - Switch has default colors when enabled', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x52000000), // Black with 32% opacity
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: Colors.grey.shade50),
reason: 'Inactive enabled switch should match these colors',
);
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x802196f3),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: const Color(0xff2196f3)),
reason: 'Active enabled switch should match these colors',
);
});
testWidgets('Material3 - Switch has default colors when enabled', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
final ColorScheme colors = theme.colorScheme;
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..save()
..rrect(
style: PaintingStyle.fill,
color: colors.surfaceContainerHighest,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect(
style: PaintingStyle.stroke,
color: colors.outline,
rrect: RRect.fromLTRBR(5.0, 9.0, 55.0, 39.0, const Radius.circular(16.0)),
)
..rrect(color: colors.outline), // thumb color
reason: 'Inactive enabled switch should match these colors',
);
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..save()
..rrect(
style: PaintingStyle.fill,
color: colors.primary,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: colors.onPrimary), // thumb color
reason: 'Active enabled switch should match these colors',
);
});
testWidgets('Switch.adaptive(Cupertino) has default colors when enabled', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
final ColorScheme colors = theme.colorScheme;
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch.adaptive(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..save()
..rrect(
style: PaintingStyle.fill,
color: colors.surfaceContainerHighest,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect(
style: PaintingStyle.stroke,
color: colors.outline,
rrect: RRect.fromLTRBR(5.0, 9.0, 55.0, 39.0, const Radius.circular(16.0)),
)
..rrect(color: colors.outline), // thumb color
reason: 'Inactive enabled switch should match these colors',
);
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..save()
..rrect(
style: PaintingStyle.fill,
color: colors.primary,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: colors.onPrimary), // thumb color
reason: 'Active enabled switch should match these colors',
);
});
testWidgets('Material2 - Switch has default colors when disabled', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: const Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
value: false,
onChanged: null,
),
),
)
),
),
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Colors.black12,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: Colors.grey.shade400),
reason: 'Inactive disabled switch should match these colors',
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: const Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
value: true,
onChanged: null,
),
),
),
),
),
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Colors.black12,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: Colors.grey.shade400),
reason: 'Active disabled switch should match these colors',
);
});
testWidgets('Material3 - Inactive Switch has default colors when disabled', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final ColorScheme colors = themeData.colorScheme;
await tester.pumpWidget(MaterialApp(
theme: themeData,
home: const Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
value: false,
onChanged: null,
),
),
),
),
));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..save()
..rrect(
style: PaintingStyle.fill,
color: colors.surfaceContainerHighest.withOpacity(0.12),
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect(
style: PaintingStyle.stroke,
color: colors.onSurface.withOpacity(0.12),
rrect: RRect.fromLTRBR(5.0, 9.0, 55.0, 39.0, const Radius.circular(16.0)),
)
..rrect(color: Color.alphaBlend(colors.onSurface.withOpacity(0.38), colors.surface)), // thumb color
reason: 'Inactive disabled switch should match these colors',
);
});
testWidgets('Material3 - Active Switch has default colors when disabled', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final ColorScheme colors = themeData.colorScheme;
await tester.pumpWidget(MaterialApp(
theme: themeData,
home: const Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
value: true,
onChanged: null,
),
),
),
),
));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..save()
..rrect(
style: PaintingStyle.fill,
color: colors.onSurface.withOpacity(0.12),
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: colors.surface), // thumb color
reason: 'Active disabled switch should match these colors',
);
});
testWidgets('Material2 - Switch default overlayColor resolves hovered/focused state', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
Finder findSwitch() {
return find.byWidgetPredicate((Widget widget) => widget is Switch);
}
MaterialInkController? getSwitchMaterial(WidgetTester tester) {
return Material.of(tester.element(findSwitch()));
}
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Switch(
focusNode: focusNode,
value: true,
onChanged: (_) { },
),
),
));
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(getSwitchMaterial(tester),
paints
..circle(color: theme.focusColor)
);
// On both hovered and focused, the overlay color should show hovered overlay color.
final Offset center = tester.getCenter(find.byType(Switch));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(getSwitchMaterial(tester),
paints..circle(color: theme.hoverColor)
);
focusNode.dispose();
});
testWidgets('Material3 - Switch default overlayColor resolves hovered/focused state', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
Finder findSwitch() {
return find.byWidgetPredicate((Widget widget) => widget is Switch);
}
MaterialInkController? getSwitchMaterial(WidgetTester tester) {
return Material.of(tester.element(findSwitch()));
}
await tester.pumpWidget(MaterialApp(
theme: theme,
home: Scaffold(
body: Switch(
focusNode: focusNode,
value: true,
onChanged: (_) { },
),
),
));
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(getSwitchMaterial(tester),
paints..circle(color: theme.colorScheme.primary.withOpacity(0.1))
);
// On both hovered and focused, the overlay color should show hovered overlay color.
final Offset center = tester.getCenter(find.byType(Switch));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(getSwitchMaterial(tester),
paints..circle(color: theme.colorScheme.primary.withOpacity(0.08))
);
focusNode.dispose();
});
testWidgets('Material2 - Switch can be set color', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
activeColor: Colors.red[500],
activeTrackColor: Colors.green[500],
inactiveThumbColor: Colors.yellow[500],
inactiveTrackColor: Colors.blue[500],
),
),
);
},
),
),
),
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Colors.blue[500],
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: Colors.yellow[500]),
);
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Colors.green[500],
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: Colors.red[500]),
);
});
testWidgets('Material3 - Switch can be set color', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final ColorScheme colors = themeData.colorScheme;
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: themeData,
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
activeColor: Colors.red[500],
activeTrackColor: Colors.green[500],
inactiveThumbColor: Colors.yellow[500],
inactiveTrackColor: Colors.blue[500],
),
),
);
},
),
),
),
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: Colors.blue[500],
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect(
style: PaintingStyle.stroke,
color: colors.outline,
)
..rrect(color: Colors.yellow[500]), // thumb color
);
await tester.drag(find.byType(Switch), const Offset(-30.0, 0.0));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: Colors.green[500],
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: Colors.red[500]), // thumb color
);
});
testWidgets('Drag ends after animation completes', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/17773
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(value, isFalse);
final Rect switchRect = tester.getRect(find.byType(Switch));
final TestGesture gesture = await tester.startGesture(switchRect.centerLeft);
await tester.pump();
await gesture.moveBy(Offset(switchRect.width, 0.0));
await tester.pump();
await gesture.up();
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(value, isTrue);
expect(tester.hasRunningAnimations, false);
});
testWidgets('can veto switch dragging result', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
Theme(
data: theme,
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = value || newValue;
});
},
),
),
);
},
),
),
),
);
// Move a little to the right, not past the middle.
TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(Switch)).center);
await gesture.moveBy(const Offset(kTouchSlop + 0.1, 0.0));
await tester.pump();
await gesture.moveBy(const Offset(-kTouchSlop + 5.1, 0.0));
await tester.pump();
await gesture.up();
await tester.pump();
expect(value, isFalse);
final ToggleableStateMixin state = tester.state<ToggleableStateMixin>(
find.descendant(
of: find.byType(Switch),
matching: find.byWidgetPredicate(
(Widget widget) => widget.runtimeType.toString() == '_MaterialSwitch',
),
),
);
expect(state.position.value, lessThan(0.5));
await tester.pump();
await tester.pumpAndSettle();
expect(value, isFalse);
expect(state.position.value, 0);
// Move past the middle.
gesture = await tester.startGesture(tester.getRect(find.byType(Switch)).center);
await gesture.moveBy(const Offset(kTouchSlop + 0.1, 0.0));
await tester.pump();
await gesture.up();
await tester.pump();
expect(value, isTrue);
expect(state.position.value, greaterThan(0.5));
await tester.pump();
await tester.pumpAndSettle();
expect(value, isTrue);
expect(state.position.value, 1.0);
// Now move back to the left, the revert animation should play.
gesture = await tester.startGesture(tester.getRect(find.byType(Switch)).center);
await gesture.moveBy(const Offset(-kTouchSlop - 0.1, 0.0));
await tester.pump();
await gesture.up();
await tester.pump();
expect(value, isTrue);
expect(state.position.value, lessThan(0.5));
await tester.pump();
await tester.pumpAndSettle();
expect(value, isTrue);
expect(state.position.value, 1.0);
});
testWidgets('switch has semantic events', (WidgetTester tester) async {
dynamic semanticEvent;
bool value = false;
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, (dynamic message) async {
semanticEvent = message;
});
final SemanticsTester semanticsTester = SemanticsTester(tester);
await tester.pumpWidget(
Theme(
data: theme,
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
await tester.tap(find.byType(Switch));
final RenderObject object = tester.firstRenderObject(find.byType(Switch));
expect(value, true);
expect(semanticEvent, <String, dynamic>{
'type': 'tap',
'nodeId': object.debugSemantics!.id,
'data': <String, dynamic>{},
});
expect(object.debugSemantics!.getSemanticsData().hasAction(SemanticsAction.tap), true);
semanticsTester.dispose();
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null);
});
testWidgets('switch sends semantic events from parent if fully merged', (WidgetTester tester) async {
dynamic semanticEvent;
bool value = false;
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, (dynamic message) async {
semanticEvent = message;
});
final SemanticsTester semanticsTester = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
void onChanged(bool newValue) {
setState(() {
value = newValue;
});
}
return Material(
child: MergeSemantics(
child: ListTile(
leading: const Text('test'),
onTap: () {
onChanged(!value);
},
trailing: Switch(
value: value,
onChanged: onChanged,
),
),
),
);
},
),
),
);
await tester.tap(find.byType(MergeSemantics));
final RenderObject object = tester.firstRenderObject(find.byType(MergeSemantics));
expect(value, true);
expect(semanticEvent, <String, dynamic>{
'type': 'tap',
'nodeId': object.debugSemantics!.id,
'data': <String, dynamic>{},
});
expect(object.debugSemantics!.getSemanticsData().hasAction(SemanticsAction.tap), true);
semanticsTester.dispose();
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null);
});
testWidgets('Switch.adaptive', (WidgetTester tester) async {
bool value = false;
const Color activeTrackColor = Color(0xffff1200);
const Color inactiveTrackColor = Color(0xffff12ff);
const Color thumbColor = Color(0xffffff00);
const Color focusColor = Color(0xff00ff00);
Widget buildFrame(TargetPlatform platform) {
return MaterialApp(
theme: ThemeData(platform: platform),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch.adaptive(
value: value,
activeColor: activeTrackColor,
inactiveTrackColor: inactiveTrackColor,
thumbColor: const MaterialStatePropertyAll<Color?>(thumbColor),
focusColor: focusColor,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
);
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
value = false;
await tester.pumpWidget(buildFrame(platform));
expect(find.byType(Switch), findsOneWidget, reason: 'on ${platform.name}');
expect(find.byType(CupertinoSwitch), findsNothing);
final Switch adaptiveSwitch = tester.widget(find.byType(Switch));
expect(adaptiveSwitch.activeColor, activeTrackColor, reason: 'on ${platform.name}');
expect(adaptiveSwitch.inactiveTrackColor, inactiveTrackColor, reason: 'on ${platform.name}');
expect(adaptiveSwitch.thumbColor?.resolve(<MaterialState>{}), thumbColor, reason: 'on ${platform.name}');
expect(adaptiveSwitch.focusColor, focusColor, reason: 'on ${platform.name}');
expect(value, isFalse, reason: 'on ${platform.name}');
await tester.tap(find.byType(Switch));
expect(value, isTrue, reason: 'on ${platform.name}');
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows ]) {
value = false;
await tester.pumpWidget(buildFrame(platform));
await tester.pumpAndSettle(); // Finish the theme change animation.
expect(find.byType(CupertinoSwitch), findsNothing);
expect(value, isFalse, reason: 'on ${platform.name}');
await tester.tap(find.byType(Switch));
expect(value, isTrue, reason: 'on ${platform.name}');
}
});
testWidgets('Switch.adaptive default mouse cursor(Cupertino)', (WidgetTester tester) async {
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
await tester.pumpWidget(buildAdaptiveSwitch(
platform: platform,
value: false,
));
final Size switchSize = tester.getSize(find.byType(Switch));
expect(switchSize, const Size(60.0, 48.0));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(Switch)));
await tester.pump();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic);
await tester.pumpWidget(buildAdaptiveSwitch(platform: platform));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic);
// Test disabled switch.
await tester.pumpWidget(buildAdaptiveSwitch(platform: platform, enabled: false, value: false));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await gesture.removePointer(location: tester.getCenter(find.byType(Switch)));
await tester.pump();
}
});
testWidgets('Switch.adaptive default thumb/track color and size(Cupertino)', (WidgetTester tester) async {
const Color thumbColor = Colors.white;
const Color inactiveTrackColor = Color.fromARGB(40, 120, 120, 128); // Default inactive track color.
const Color activeTrackColor = Color.fromARGB(255, 52, 199, 89); // Default active track color.
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
// Switches have same sizes on both platform but they are more compact on macOS.
final RRect trackRRect = platform == TargetPlatform.iOS
? RRect.fromLTRBR(4.5, 8.5, 55.5, 39.5, const Radius.circular(15.5))
: RRect.fromLTRBR(4.5, 4.5, 55.5, 35.5, const Radius.circular(15.5));
final RRect inactiveThumbRRect = platform == TargetPlatform.iOS
? RRect.fromLTRBR(6.0, 10.0, 34.0, 38.0, const Radius.circular(14.0))
: RRect.fromLTRBR(6.0, 6.0, 34.0, 34.0, const Radius.circular(14.0));
final RRect activeThumbRRect = platform == TargetPlatform.iOS
? RRect.fromLTRBR(26.0, 10.0, 54.0, 38.0, const Radius.circular(14.0))
: RRect.fromLTRBR(26.0, 6.0, 54.0, 34.0, const Radius.circular(14.0));
await tester.pumpWidget(Container());
await tester.pumpWidget(buildAdaptiveSwitch(
platform: platform,
value: false
));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: inactiveTrackColor,
rrect: trackRRect,
) // Default cupertino inactive track color
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: thumbColor,
rrect: inactiveThumbRRect,
),
reason: 'Inactive enabled switch should have default track and thumb color',
);
expect(find.byType(Opacity), findsOneWidget);
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity, 1.0);
await tester.pumpWidget(Container());
await tester.pumpWidget(buildAdaptiveSwitch(platform: platform));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: activeTrackColor,
rrect: trackRRect,
) // Default cupertino active track color
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: thumbColor,
rrect: activeThumbRRect,
),
reason: 'Active enabled switch should have default track and thumb color',
);
expect(find.byType(Opacity), findsOneWidget);
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity, 1.0);
// Test disabled switch.
await tester.pumpWidget(Container());
await tester.pumpWidget(buildAdaptiveSwitch(
platform: platform,
enabled: false,
value: false,
));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: inactiveTrackColor,
rrect: trackRRect,
) // Default cupertino inactive track color
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: thumbColor,
rrect: inactiveThumbRRect,
),
reason: 'Inactive disabled switch should have default track and thumb color',
);
expect(find.byType(Opacity), findsOneWidget);
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity, 0.5);
await tester.pumpWidget(Container());
await tester.pumpWidget(buildAdaptiveSwitch(
platform: platform,
enabled: false,
));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: activeTrackColor,
rrect: trackRRect,
) // Default cupertino active track color
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: thumbColor,
rrect: activeThumbRRect,
),
reason: 'Active disabled switch should have default track and thumb color',
);
expect(find.byType(Opacity), findsOneWidget);
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity, 0.5);
}
});
testWidgets('Default Switch.adaptive are not affected by '
'ThemeData.switchThemeData on iOS/macOS', (WidgetTester tester) async {
const Color defaultThumbColor = Colors.white;
const Color defaultInactiveTrackColor = Color.fromARGB(40, 120, 120, 128);
const Color defaultActiveTrackColor = Color.fromARGB(255, 52, 199, 89);
const Color updatedThumbColor = Colors.red;
const Color updatedTrackColor = Colors.green;
const SwitchThemeData overallSwitchTheme = SwitchThemeData(
thumbColor: MaterialStatePropertyAll<Color>(updatedThumbColor),
trackColor: MaterialStatePropertyAll<Color>(updatedTrackColor),
);
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: platform,
overallSwitchThemeData: overallSwitchTheme
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: defaultActiveTrackColor,
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: defaultThumbColor,
),
reason: 'Active enabled switch should still have default track and thumb color',
);
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: platform,
value: false,
overallSwitchThemeData: overallSwitchTheme
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: defaultInactiveTrackColor,
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: defaultThumbColor,
),
reason: 'Inactive enabled switch should have default track and thumb color',
);
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: platform,
enabled: false,
value: false,
overallSwitchThemeData: overallSwitchTheme
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: defaultInactiveTrackColor,
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: defaultThumbColor,
),
reason: 'Inactive disabled switch should have default track and thumb color',
);
}
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: TargetPlatform.android,
overallSwitchThemeData: overallSwitchTheme
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Color(updatedTrackColor.value),
)
..rrect()
..rrect(
color: Color(updatedThumbColor.value),
),
reason: 'Switch.adaptive is affected by SwitchTheme on other platforms',
);
});
testWidgets('Default Switch.adaptive are not affected by '
'SwitchThemeData on iOS/macOS', (WidgetTester tester) async {
const Color defaultThumbColor = Colors.white;
const Color defaultInactiveTrackColor = Color.fromARGB(40, 120, 120, 128);
const Color defaultActiveTrackColor = Color.fromARGB(255, 52, 199, 89);
const Color updatedThumbColor = Colors.red;
const Color updatedTrackColor = Colors.green;
const SwitchThemeData switchTheme = SwitchThemeData(
thumbColor: MaterialStatePropertyAll<Color>(updatedThumbColor),
trackColor: MaterialStatePropertyAll<Color>(updatedTrackColor),
);
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: platform,
switchThemeData: switchTheme
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: defaultActiveTrackColor,
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: defaultThumbColor,
),
reason: 'Active enabled switch should still have default track and thumb color',
);
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: platform,
value: false,
switchThemeData: switchTheme
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: defaultInactiveTrackColor,
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: defaultThumbColor,
),
reason: 'Inactive enabled switch should have default track and thumb color',
);
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: platform,
enabled: false,
value: false,
switchThemeData: switchTheme
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: defaultInactiveTrackColor,
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000)) // Thumb border color(only cupertino)
..rrect(
color: defaultThumbColor,
),
reason: 'Inactive disabled switch should have default track and thumb color',
);
}
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: TargetPlatform.android,
switchThemeData: switchTheme
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Color(updatedTrackColor.value),
)
..rrect()
..rrect(
color: Color(updatedThumbColor.value),
),
reason: 'Switch.adaptive is affected by SwitchTheme on other platforms',
);
});
testWidgets('Override default adaptive SwitchThemeData on iOS/macOS', (WidgetTester tester) async {
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: platform,
switchThemeData: const SwitchThemeData(
thumbColor: MaterialStatePropertyAll<Color>(Colors.yellow),
trackColor: MaterialStatePropertyAll<Color>(Colors.brown),
),
switchThemeAdaptation: const _SwitchThemeAdaptation(),
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Color(Colors.deepPurple.value),
)..rrect()..rrect()..rrect()..rrect()
..rrect(
color: Color(Colors.lightGreen.value),
),
);
}
// Other platforms should not be affected by the adaptive switch theme.
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows ]) {
await tester.pumpWidget(Container());
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: platform,
switchThemeData: const SwitchThemeData(
thumbColor: MaterialStatePropertyAll<Color>(Colors.yellow),
trackColor: MaterialStatePropertyAll<Color>(Colors.brown),
),
switchThemeAdaptation: const _SwitchThemeAdaptation(),
)
);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Color(Colors.brown.value),
)..rrect()
..rrect(
color: Color(Colors.yellow.value),
),
);
}
});
testWidgets('Switch.adaptive default focus color(Cupertino)', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode node = FocusNode();
addTearDown(node.dispose);
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: TargetPlatform.macOS,
autofocus: true,
focusNode: node,
)
);
await tester.pumpAndSettle();
expect(node.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(color: const Color(0xff34c759)) // Track color
..rrect()
..rrect(color: const Color(0xcc6ef28f), strokeWidth: 3.5, style: PaintingStyle.stroke) // Focused outline
..rrect()
..rrect()
..rrect()
..rrect(color: const Color(0xffffffff)), // Thumb color
);
await tester.pumpWidget(
buildAdaptiveSwitch(
platform: TargetPlatform.macOS,
autofocus: true,
focusNode: node,
focusColor: Colors.red,
)
);
await tester.pumpAndSettle();
expect(node.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(color: const Color(0xff34c759)) // Track color
..rrect()
..rrect(color: Color(Colors.red.value), strokeWidth: 3.5, style: PaintingStyle.stroke) // Focused outline
..rrect()..rrect()..rrect()
..rrect(color: const Color(0xffffffff)), // Thumb color
);
});
testWidgets('Material2 - Switch is focusable and has correct focus color', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool value = true;
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Switch(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
focusColor: Colors.orange[500],
autofocus: true,
focusNode: focusNode,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x802196f3),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..circle(color: Colors.orange[500])
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: const Color(0xff2196f3)),
);
// Check the false value.
value = false;
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x52000000),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..circle(color: Colors.orange[500])
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: const Color(0xfffafafa)),
);
// Check what happens when disabled.
value = false;
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x1f000000),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: const Color(0xffbdbdbd)),
);
focusNode.dispose();
});
testWidgets('Material3 - Switch is focusable and has correct focus color', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final ColorScheme colors = themeData.colorScheme;
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool value = true;
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: themeData,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Switch(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
focusColor: Colors.orange[500],
autofocus: true,
focusNode: focusNode,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
// active, enabled switch
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.primary,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..circle(color: Colors.orange[500]),
);
// Check the false value: inactive enabled switch
value = false;
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.surfaceContainerHighest,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect(
style: PaintingStyle.stroke,
color: colors.outline,
rrect: RRect.fromLTRBR(5.0, 9.0, 55.0, 39.0, const Radius.circular(16.0)),
)
..circle(color: Colors.orange[500])
);
// Check what happens when disabled: inactive disabled switch.
value = false;
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.surfaceContainerHighest.withOpacity(0.12),
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect(
style: PaintingStyle.stroke,
color: colors.onSurface.withOpacity(0.12),
rrect: RRect.fromLTRBR(5.0, 9.0, 55.0, 39.0, const Radius.circular(16.0)),
)
..rrect(color: Color.alphaBlend(colors.onSurface.withOpacity(0.38), colors.surface)),
);
focusNode.dispose();
});
testWidgets('Switch with splash radius set', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const double splashRadius = 30;
Widget buildApp() {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Switch(
value: true,
onChanged: (bool newValue) {},
focusColor: Colors.orange[500],
autofocus: true,
splashRadius: splashRadius,
),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..circle(color: Colors.orange[500], radius: splashRadius),
);
});
testWidgets('Material2 - Switch can be hovered and has correct hover color', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool value = true;
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Switch(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
hoverColor: Colors.orange[500],
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x802196f3),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: const Color(0xff2196f3)),
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x802196f3),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..circle(color: Colors.orange[500])
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: const Color(0xff2196f3)),
);
// Check what happens when disabled.
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x1f000000),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: const Color(0xffbdbdbd)),
);
});
testWidgets('Material3 - Switch can be hovered and has correct hover color', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final ColorScheme colors = themeData.colorScheme;
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool value = true;
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: themeData,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Switch(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
hoverColor: Colors.orange[500],
);
}),
),
),
);
}
// active enabled switch
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: colors.primary,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: colors.onPrimary),
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: colors.primary,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..circle(color: Colors.orange[500]),
);
// Check what happens for disabled active switch
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: colors.onSurface.withOpacity(0.12),
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: colors.surface.withOpacity(1.0)),
);
});
testWidgets('Switch can be toggled by keyboard shortcuts', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool value = true;
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Switch(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
focusColor: Colors.orange[500],
autofocus: true,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
// On web, switches don't respond to the enter key.
expect(value, kIsWeb ? isTrue : isFalse);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(value, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
expect(value, isFalse);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
expect(value, isTrue);
});
testWidgets('Switch changes mouse cursor when hovered', (WidgetTester tester) async {
// Test Switch.adaptive() constructor
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: Switch.adaptive(
mouseCursor: SystemMouseCursors.text,
value: true,
onChanged: (_) {},
),
),
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(Switch)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test Switch() constructor
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: Switch(
mouseCursor: SystemMouseCursors.text,
value: true,
onChanged: (_) {},
),
),
),
),
),
),
);
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test default cursor
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: Switch(
value: true,
onChanged: (_) {},
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test default cursor when disabled
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: Switch(
value: true,
onChanged: null,
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await tester.pumpAndSettle();
});
testWidgets('Material switch should not recreate its render object when disabled', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/61247.
bool value = true;
bool enabled = true;
late StateSetter stateSetter;
await tester.pumpWidget(
Theme(
data: theme,
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return Material(
child: Center(
child: Switch(
value: value,
onChanged: !enabled ? null : (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
final ToggleableStateMixin oldSwitchState = tester.state(find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_MaterialSwitch'));
stateSetter(() { value = false; });
await tester.pump();
// Disable the switch when the implicit animation begins.
stateSetter(() { enabled = false; });
await tester.pump();
final ToggleableStateMixin updatedSwitchState = tester.state(find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_MaterialSwitch'));
expect(updatedSwitchState.isInteractive, false);
expect(updatedSwitchState, oldSwitchState);
expect(updatedSwitchState.position.isCompleted, false);
expect(updatedSwitchState.position.isDismissed, false);
});
testWidgets('Material2 - Switch thumb color resolves in active/enabled states', (WidgetTester tester) async {
const Color activeEnabledThumbColor = Color(0xFF000001);
const Color activeDisabledThumbColor = Color(0xFF000002);
const Color inactiveEnabledThumbColor = Color(0xFF000003);
const Color inactiveDisabledThumbColor = Color(0xFF000004);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledThumbColor;
}
return inactiveDisabledThumbColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledThumbColor;
}
return inactiveEnabledThumbColor;
}
final MaterialStateProperty<Color> thumbColor =
MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitch({required bool enabled, required bool active}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
thumbColor: thumbColor,
value: active,
onChanged: enabled ? (_) { } : null,
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch(enabled: false, active: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Colors.black12,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: inactiveDisabledThumbColor),
reason: 'Inactive disabled switch should default track and custom thumb color',
);
await tester.pumpWidget(buildSwitch(enabled: false, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Colors.black12,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: activeDisabledThumbColor),
reason: 'Active disabled switch should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x52000000), // Black with 32% opacity,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: inactiveEnabledThumbColor),
reason: 'Inactive enabled switch should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: false, active: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Colors.black12,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: inactiveDisabledThumbColor),
reason: 'Inactive disabled switch should match these colors',
);
});
testWidgets('Material3 - Switch thumb color resolves in active/enabled states', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final ColorScheme colors = themeData.colorScheme;
const Color activeEnabledThumbColor = Color(0xFF000001);
const Color activeDisabledThumbColor = Color(0xFF000002);
const Color inactiveEnabledThumbColor = Color(0xFF000003);
const Color inactiveDisabledThumbColor = Color(0xFF000004);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledThumbColor;
}
return inactiveDisabledThumbColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledThumbColor;
}
return inactiveEnabledThumbColor;
}
final MaterialStateProperty<Color> thumbColor = MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitch({required bool enabled, required bool active}) {
return Theme(
data: themeData,
child: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
thumbColor: thumbColor,
value: active,
onChanged: enabled ? (_) { } : null,
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch(enabled: false, active: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.surfaceContainerHighest.withOpacity(0.12),
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect(
style: PaintingStyle.stroke,
color: colors.onSurface.withOpacity(0.12),
rrect: RRect.fromLTRBR(5.0, 9.0, 55.0, 39.0, const Radius.circular(16.0)),
)
..rrect(color: inactiveDisabledThumbColor),
reason: 'Inactive disabled switch should default track and custom thumb color',
);
await tester.pumpWidget(buildSwitch(enabled: false, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.onSurface.withOpacity(0.12),
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: activeDisabledThumbColor),
reason: 'Active disabled switch should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.surfaceContainerHighest,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: inactiveEnabledThumbColor),
reason: 'Inactive enabled switch should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.primary,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: activeEnabledThumbColor),
reason: 'Active enabled switch should match these colors',
);
});
testWidgets('Material2 - Switch thumb color resolves in hovered/focused states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredThumbColor = Color(0xFF000001);
const Color focusedThumbColor = Color(0xFF000002);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredThumbColor;
}
if (states.contains(MaterialState.focused)) {
return focusedThumbColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> thumbColor =
MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitch() {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: Switch(
focusNode: focusNode,
autofocus: true,
value: true,
thumbColor: thumbColor,
onChanged: (_) { },
),
),
),
);
}
await tester.pumpWidget(buildSwitch());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x802196f3),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..circle() // Radial reaction
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: focusedThumbColor),
reason: 'Inactive disabled switch should default track and custom thumb color',
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: const Color(0x802196f3),
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..circle()
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: hoveredThumbColor),
reason: 'Inactive disabled switch should default track and custom thumb color',
);
focusNode.dispose();
});
testWidgets('Material3 - Switch thumb color resolves in hovered/focused states', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final ColorScheme colors = themeData.colorScheme;
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredThumbColor = Color(0xFF000001);
const Color focusedThumbColor = Color(0xFF000002);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredThumbColor;
}
if (states.contains(MaterialState.focused)) {
return focusedThumbColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> thumbColor = MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitch() {
return MaterialApp(
theme: themeData,
home: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
focusNode: focusNode,
autofocus: true,
value: true,
thumbColor: thumbColor,
onChanged: (_) { },
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.primary,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..circle(color: colors.primary.withOpacity(0.1))
..rrect(color: focusedThumbColor),
reason: 'active enabled switch should default track and custom thumb color',
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
style: PaintingStyle.fill,
color: colors.primary,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..circle(color: colors.primary.withOpacity(0.08))
..rrect(color: hoveredThumbColor),
reason: 'active enabled switch should default track and custom thumb color',
);
focusNode.dispose();
});
testWidgets('Material2 - Track color resolves in active/enabled states', (WidgetTester tester) async {
const Color activeEnabledTrackColor = Color(0xFF000001);
const Color activeDisabledTrackColor = Color(0xFF000002);
const Color inactiveEnabledTrackColor = Color(0xFF000003);
const Color inactiveDisabledTrackColor = Color(0xFF000004);
Color getTrackColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledTrackColor;
}
return inactiveDisabledTrackColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledTrackColor;
}
return inactiveEnabledTrackColor;
}
final MaterialStateProperty<Color> trackColor =
MaterialStateColor.resolveWith(getTrackColor);
Widget buildSwitch({required bool enabled, required bool active}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: Switch(
trackColor: trackColor,
value: active,
onChanged: enabled ? (_) { } : null,
),
),
),
);
}
await tester.pumpWidget(buildSwitch(enabled: false, active: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: inactiveDisabledTrackColor,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
),
reason: 'Inactive disabled switch track should use this value',
);
await tester.pumpWidget(buildSwitch(enabled: false, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: activeDisabledTrackColor,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
),
reason: 'Active disabled switch should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: inactiveEnabledTrackColor,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
),
reason: 'Inactive enabled switch should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: false, active: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: inactiveDisabledTrackColor,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
),
reason: 'Inactive disabled switch should match these colors',
);
});
testWidgets('Material3 - Track color resolves in active/enabled states', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
const Color activeEnabledTrackColor = Color(0xFF000001);
const Color activeDisabledTrackColor = Color(0xFF000002);
const Color inactiveEnabledTrackColor = Color(0xFF000003);
const Color inactiveDisabledTrackColor = Color(0xFF000004);
Color getTrackColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledTrackColor;
}
return inactiveDisabledTrackColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledTrackColor;
}
return inactiveEnabledTrackColor;
}
final MaterialStateProperty<Color> trackColor =
MaterialStateColor.resolveWith(getTrackColor);
Widget buildSwitch({required bool enabled, required bool active}) {
return Theme(
data: themeData,
child: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
trackColor: trackColor,
value: active,
onChanged: enabled ? (_) { } : null,
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch(enabled: false, active: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: inactiveDisabledTrackColor,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
),
reason: 'Inactive disabled switch track should use this value',
);
await tester.pumpWidget(buildSwitch(enabled: false, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: activeDisabledTrackColor,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
),
reason: 'Active disabled switch should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: inactiveEnabledTrackColor,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
),
reason: 'Inactive enabled switch should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: activeEnabledTrackColor,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
),
reason: 'Active enabled switch should match these colors',
);
});
testWidgets('Material2 - Switch track color resolves in hovered/focused states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredTrackColor = Color(0xFF000001);
const Color focusedTrackColor = Color(0xFF000002);
Color getTrackColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredTrackColor;
}
if (states.contains(MaterialState.focused)) {
return focusedTrackColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> trackColor =
MaterialStateColor.resolveWith(getTrackColor);
Widget buildSwitch() {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
focusNode: focusNode,
autofocus: true,
value: true,
trackColor: trackColor,
onChanged: (_) { },
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: focusedTrackColor,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
),
reason: 'Inactive enabled switch should match these colors',
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: hoveredTrackColor,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
),
reason: 'Inactive enabled switch should match these colors',
);
focusNode.dispose();
});
testWidgets('Material3 - Switch track color resolves in hovered/focused states', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredTrackColor = Color(0xFF000001);
const Color focusedTrackColor = Color(0xFF000002);
Color getTrackColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredTrackColor;
}
if (states.contains(MaterialState.focused)) {
return focusedTrackColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> trackColor =
MaterialStateColor.resolveWith(getTrackColor);
Widget buildSwitch() {
return Theme(
data: themeData,
child: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
focusNode: focusNode,
autofocus: true,
value: true,
trackColor: trackColor,
onChanged: (_) { },
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: focusedTrackColor,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
),
reason: 'Active enabled switch should match these colors',
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: hoveredTrackColor,
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
),
reason: 'Active enabled switch should match these colors',
);
focusNode.dispose();
});
testWidgets('Material2 - Switch thumb color is blended against surface color', (WidgetTester tester) async {
final Color activeDisabledThumbColor = Colors.blue.withOpacity(.60);
final ThemeData theme = ThemeData.light(useMaterial3: false);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return activeDisabledThumbColor;
}
return Colors.black;
}
final MaterialStateProperty<Color> thumbColor =
MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitch({required bool enabled, required bool active}) {
return Directionality(
textDirection: TextDirection.rtl,
child: Theme(
data: theme,
child: Material(
child: Center(
child: Switch(
thumbColor: thumbColor,
value: active,
onChanged: enabled ? (_) { } : null,
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch(enabled: false, active: true));
final Color expectedThumbColor = Color.alphaBlend(activeDisabledThumbColor, theme.colorScheme.surface);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: Colors.black12,
rrect: RRect.fromLTRBR(13.0, 17.0, 46.0, 31.0, const Radius.circular(7.0)),
)
..rrect(color: const Color(0x00000000))
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: expectedThumbColor),
reason: 'Active disabled thumb color should be blended on top of surface color',
);
});
testWidgets('Material3 - Switch thumb color is blended against surface color', (WidgetTester tester) async {
final Color activeDisabledThumbColor = Colors.blue.withOpacity(.60);
final ThemeData theme = ThemeData(useMaterial3: true);
final ColorScheme colors = theme.colorScheme;
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return activeDisabledThumbColor;
}
return Colors.black;
}
final MaterialStateProperty<Color> thumbColor =
MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitch({required bool enabled, required bool active}) {
return Directionality(
textDirection: TextDirection.rtl,
child: Theme(
data: theme,
child: Material(
child: Center(
child: Switch(
thumbColor: thumbColor,
value: active,
onChanged: enabled ? (_) { } : null,
),
),
),
),
);
}
await tester.pumpWidget(buildSwitch(enabled: false, active: true));
final Color expectedThumbColor = Color.alphaBlend(activeDisabledThumbColor, theme.colorScheme.surface);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(
color: colors.onSurface.withOpacity(0.12),
rrect: RRect.fromLTRBR(4.0, 8.0, 56.0, 40.0, const Radius.circular(16.0)),
)
..rrect()
..rrect(color: expectedThumbColor),
reason: 'Active disabled thumb color should be blended on top of surface color',
);
});
testWidgets('Switch overlay color resolves in active/pressed/focused/hovered states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color activeThumbColor = Color(0xFF000000);
const Color inactiveThumbColor = Color(0xFF000010);
const Color activePressedOverlayColor = Color(0xFF000001);
const Color inactivePressedOverlayColor = Color(0xFF000002);
const Color hoverOverlayColor = Color(0xFF000003);
const Color focusOverlayColor = Color(0xFF000004);
const Color hoverColor = Color(0xFF000005);
const Color focusColor = Color(0xFF000006);
Color? getOverlayColor(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
if (states.contains(MaterialState.selected)) {
return activePressedOverlayColor;
}
return inactivePressedOverlayColor;
}
if (states.contains(MaterialState.hovered)) {
return hoverOverlayColor;
}
if (states.contains(MaterialState.focused)) {
return focusOverlayColor;
}
return null;
}
const double splashRadius = 24.0;
Widget buildSwitch({bool active = false, bool focused = false, bool useOverlay = true}) {
return MaterialApp(
theme: theme,
home: Scaffold(
body: Switch(
focusNode: focusNode,
autofocus: focused,
value: active,
onChanged: (_) { },
thumbColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return activeThumbColor;
}
return inactiveThumbColor;
}),
overlayColor: useOverlay ? MaterialStateProperty.resolveWith(getOverlayColor) : null,
hoverColor: hoverColor,
focusColor: focusColor,
splashRadius: splashRadius,
),
),
);
}
// test inactive Switch, and overlayColor is set to null.
await tester.pumpWidget(buildSwitch(useOverlay: false));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: inactiveThumbColor.withAlpha(kRadialReactionAlpha),
radius: splashRadius,
),
reason: 'Default inactive pressed Switch should have overlay color from thumbColor',
);
// test active Switch, and overlayColor is set to null.
await tester.pumpWidget(buildSwitch(active: true, useOverlay: false));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: activeThumbColor.withAlpha(kRadialReactionAlpha),
radius: splashRadius,
),
reason: 'Default active pressed Switch should have overlay color from thumbColor',
);
// test inactive Switch with an overlayColor
await tester.pumpWidget(buildSwitch());
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: inactivePressedOverlayColor,
radius: splashRadius,
),
reason: 'Inactive pressed Switch should have overlay color: $inactivePressedOverlayColor',
);
// test active Switch with an overlayColor
await tester.pumpWidget(buildSwitch(active: true));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: activePressedOverlayColor,
radius: splashRadius,
),
reason: 'Active pressed Switch should have overlay color: $activePressedOverlayColor',
);
await tester.pumpWidget(buildSwitch(focused: true));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: focusOverlayColor,
radius: splashRadius,
),
reason: 'Focused Switch should use overlay color $focusOverlayColor over $focusColor',
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: hoverOverlayColor,
radius: splashRadius,
),
reason: 'Hovered Switch should use overlay color $hoverOverlayColor over $hoverColor',
);
focusNode.dispose();
});
testWidgets('Do not crash when widget disappears while pointer is down', (WidgetTester tester) async {
Widget buildSwitch(bool show) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: show ? Switch(value: true, onChanged: (_) { }) : Container(),
),
),
);
}
await tester.pumpWidget(buildSwitch(true));
final Offset center = tester.getCenter(find.byType(Switch));
// Put a pointer down on the screen.
final TestGesture gesture = await tester.startGesture(center);
await tester.pump();
// While the pointer is down, the widget disappears.
await tester.pumpWidget(buildSwitch(false));
expect(find.byType(Switch), findsNothing);
// Release pointer after widget disappeared.
await gesture.up();
});
testWidgets('disabled switch shows tooltip', (WidgetTester tester) async {
const String longPressTooltip = 'long press tooltip';
const String tapTooltip = 'tap tooltip';
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Tooltip(
message: longPressTooltip,
child: Switch(
onChanged: null,
value: true,
),
),
),
)
);
// Default tooltip shows up after long pressed.
final Finder tooltip0 = find.byType(Tooltip);
expect(find.text(longPressTooltip), findsNothing);
await tester.tap(tooltip0);
await tester.pump(const Duration(milliseconds: 10));
expect(find.text(longPressTooltip), findsNothing);
final TestGesture gestureLongPress = await tester.startGesture(tester.getCenter(tooltip0));
await tester.pump();
await tester.pump(kLongPressTimeout);
await gestureLongPress.up();
await tester.pump();
expect(find.text(longPressTooltip), findsOneWidget);
// Tooltip shows up after tapping when set triggerMode to TooltipTriggerMode.tap.
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Tooltip(
triggerMode: TooltipTriggerMode.tap,
message: tapTooltip,
child: Switch(
onChanged: null,
value: true,
),
),
),
)
);
await tester.pump(const Duration(days: 1));
await tester.pumpAndSettle();
expect(find.text(tapTooltip), findsNothing);
expect(find.text(longPressTooltip), findsNothing);
final Finder tooltip1 = find.byType(Tooltip);
await tester.tap(tooltip1);
await tester.pump(const Duration(milliseconds: 10));
expect(find.text(tapTooltip), findsOneWidget);
});
group('with image', () {
late ui.Image image;
setUp(() async {
image = await createTestImage(width: 100, height: 100);
});
testWidgets('thumb image shows up', (WidgetTester tester) async {
imageCache.clear();
final _TestImageProvider provider1 = _TestImageProvider();
final _TestImageProvider provider2 = _TestImageProvider();
expect(provider1.loadCallCount, 0);
expect(provider2.loadCallCount, 0);
bool value1 = true;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Switch(
activeThumbImage: provider1,
inactiveThumbImage: provider2,
value: value1,
onChanged: (bool val) {
setState(() {
value1 = val;
});
},
),
);
}
)
)
);
expect(provider1.loadCallCount, 1);
expect(provider2.loadCallCount, 0);
expect(imageCache.liveImageCount, 1);
await tester.tap(find.byType(Switch));
await tester.pumpAndSettle();
expect(provider1.loadCallCount, 1);
expect(provider2.loadCallCount, 1);
expect(imageCache.liveImageCount, 2);
});
testWidgets('do not crash when imageProvider completes after Switch is disposed', (WidgetTester tester) async {
final DelayedImageProvider imageProvider = DelayedImageProvider(image);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Switch(
value: true,
onChanged: null,
inactiveThumbImage: imageProvider,
),
),
),
),
);
expect(find.byType(Switch), findsOneWidget);
// Dispose the switch by taking down the tree.
await tester.pumpWidget(Container());
expect(find.byType(Switch), findsNothing);
imageProvider.complete();
expect(tester.takeException(), isNull);
});
testWidgets('do not crash when previous imageProvider completes after Switch is disposed', (WidgetTester tester) async {
final DelayedImageProvider imageProvider1 = DelayedImageProvider(image);
final DelayedImageProvider imageProvider2 = DelayedImageProvider(image);
Future<void> buildSwitch(ImageProvider imageProvider) {
return tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Switch(
value: true,
onChanged: null,
inactiveThumbImage: imageProvider,
),
),
),
),
);
}
await buildSwitch(imageProvider1);
expect(find.byType(Switch), findsOneWidget);
// Replace the ImageProvider.
await buildSwitch(imageProvider2);
expect(find.byType(Switch), findsOneWidget);
// Dispose the switch by taking down the tree.
await tester.pumpWidget(Container());
expect(find.byType(Switch), findsNothing);
// Completing the replaced ImageProvider shouldn't crash.
imageProvider1.complete();
expect(tester.takeException(), isNull);
imageProvider2.complete();
expect(tester.takeException(), isNull);
});
});
group('Switch M3 only tests', () {
testWidgets('M3 Switch has a 300-millisecond animation in total', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(value, isFalse);
final Rect switchRect = tester.getRect(find.byType(Switch));
final TestGesture gesture = await tester.startGesture(switchRect.centerLeft);
await tester.pump();
await gesture.up();
await tester.pump();
await tester.pump(const Duration(milliseconds: 200)); // M2 animation duration
expect(tester.hasRunningAnimations, true);
await tester.pump(const Duration(milliseconds: 101));
expect(tester.hasRunningAnimations, false);
});
testWidgets('M3 Switch has a stadium shape in the middle of the track', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true, colorSchemeSeed: Colors.deepPurple);
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(value, isFalse);
final Rect switchRect = tester.getRect(find.byType(Switch));
final TestGesture gesture = await tester.startGesture(switchRect.centerLeft);
await tester.pump();
await gesture.up();
await tester.pump();
// After 33 milliseconds, the switch thumb moves to the middle
// and has a stadium shape with a size of (34x22).
await tester.pump(const Duration(milliseconds: 33));
expect(tester.hasRunningAnimations, true);
await expectLater(
find.byType(Switch),
matchesGoldenFile('switch_test.m3.transition.png'),
);
});
testWidgets('M3 Switch thumb bounces in the end of the animation', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
bool value = false;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: Switch(
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
expect(value, isFalse);
final Rect switchRect = tester.getRect(find.byType(Switch));
final TestGesture gesture = await tester.startGesture(switchRect.centerLeft);
await tester.pump();
await gesture.up();
await tester.pump();
// The value on y axis is greater than 1 when t > 0.375
// 300 * 0.375 = 112.5
await tester.pump(const Duration(milliseconds: 113));
final ToggleableStateMixin state = tester.state<ToggleableStateMixin>(
find.descendant(
of: find.byType(Switch),
matching: find.byWidgetPredicate(
(Widget widget) => widget.runtimeType.toString() == '_MaterialSwitch',
),
),
);
expect(tester.hasRunningAnimations, true);
expect(state.position.value, greaterThan(1));
});
testWidgets('Switch thumb shows correct pressed color - M3', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
final ColorScheme colors = themeData.colorScheme;
Widget buildApp({bool enabled = true, bool value = true}) {
return MaterialApp(
theme: themeData,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Switch(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(Material.of(tester.element(find.byType(Switch))),
paints..rrect(
color: colors.primary, // track color
style: PaintingStyle.fill,
)..rrect(
color: Colors.transparent, // track outline color
style: PaintingStyle.stroke,
)..rrect(color: colors.primaryContainer, rrect: RRect.fromLTRBR(26.0, 10.0, 54.0, 38.0, const Radius.circular(14.0))),
);
await tester.pumpWidget(Container());
await tester.pumpWidget(buildApp(value: false));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(Material.of(tester.element(find.byType(Switch))),
paints..rrect(
color: colors.surfaceContainerHighest, // track color
style: PaintingStyle.fill
)..rrect(
color: colors.outline, // track outline color
style: PaintingStyle.stroke,
)..rrect(color: colors.onSurfaceVariant),
);
await tester.pumpWidget(Container());
await tester.pumpWidget(buildApp(enabled: false));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(Material.of(tester.element(find.byType(Switch))),
paints..rrect(
color: colors.onSurface.withOpacity(0.12), // track color
style: PaintingStyle.fill,
)..rrect(
color: Colors.transparent, // track outline color
style: PaintingStyle.stroke,
)..rrect(color: colors.surface.withOpacity(1.0)),
);
await tester.pumpWidget(Container());
await tester.pumpWidget(buildApp(enabled: false, value: false));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(Material.of(tester.element(find.byType(Switch))),
paints..rrect(
color: colors.surfaceContainerHighest.withOpacity(0.12), // track color
style: PaintingStyle.fill,
)..rrect(
color: colors.onSurface.withOpacity(0.12), // track outline color
style: PaintingStyle.stroke,
)..rrect(color: Color.alphaBlend(colors.onSurface.withOpacity(0.38), colors.surface)),
);
}, variant: TargetPlatformVariant.mobile());
testWidgets('Track outline color resolves in active/enabled states', (WidgetTester tester) async {
const Color activeEnabledTrackOutlineColor = Color(0xFF000001);
const Color activeDisabledTrackOutlineColor = Color(0xFF000002);
const Color inactiveEnabledTrackOutlineColor = Color(0xFF000003);
const Color inactiveDisabledTrackOutlineColor = Color(0xFF000004);
Color getTrackOutlineColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledTrackOutlineColor;
}
return inactiveDisabledTrackOutlineColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledTrackOutlineColor;
}
return inactiveEnabledTrackOutlineColor;
}
final MaterialStateProperty<Color> trackOutlineColor = MaterialStateColor.resolveWith(getTrackOutlineColor);
Widget buildSwitch({required bool enabled, required bool active}) {
return Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
trackOutlineColor: trackOutlineColor,
value: active,
onChanged: enabled ? (_) { } : null,
),
),
),
);
}
await tester.pumpWidget(buildSwitch(enabled: false, active: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: inactiveDisabledTrackOutlineColor, style: PaintingStyle.stroke),
reason: 'Inactive disabled switch track outline should use this value',
);
await tester.pumpWidget(buildSwitch(enabled: false, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: activeDisabledTrackOutlineColor, style: PaintingStyle.stroke),
reason: 'Active disabled switch track outline should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: inactiveEnabledTrackOutlineColor),
reason: 'Inactive enabled switch track outline should match these colors',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: activeEnabledTrackOutlineColor),
reason: 'Active enabled switch track outline should match these colors',
);
});
testWidgets('Switch track outline color resolves in hovered/focused states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredTrackOutlineColor = Color(0xFF000001);
const Color focusedTrackOutlineColor = Color(0xFF000002);
Color getTrackOutlineColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredTrackOutlineColor;
}
if (states.contains(MaterialState.focused)) {
return focusedTrackOutlineColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> trackOutlineColor = MaterialStateColor.resolveWith(getTrackOutlineColor);
Widget buildSwitch() {
return Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Center(
child: Switch(
focusNode: focusNode,
autofocus: true,
value: true,
trackOutlineColor: trackOutlineColor,
onChanged: (_) { },
),
),
),
);
}
await tester.pumpWidget(buildSwitch());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: focusedTrackOutlineColor, style: PaintingStyle.stroke),
reason: 'Active enabled switch track outline should match this color',
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: hoveredTrackOutlineColor, style: PaintingStyle.stroke),
reason: 'Active enabled switch track outline should match this color',
);
focusNode.dispose();
});
testWidgets('Track outline width resolves in active/enabled states', (WidgetTester tester) async {
const double activeEnabledTrackOutlineWidth = 1.0;
const double activeDisabledTrackOutlineWidth = 2.0;
const double inactiveEnabledTrackOutlineWidth = 3.0;
const double inactiveDisabledTrackOutlineWidth = 4.0;
double getTrackOutlineWidth(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledTrackOutlineWidth;
}
return inactiveDisabledTrackOutlineWidth;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledTrackOutlineWidth;
}
return inactiveEnabledTrackOutlineWidth;
}
final MaterialStateProperty<double> trackOutlineWidth = MaterialStateProperty.resolveWith(getTrackOutlineWidth);
Widget buildSwitch({required bool enabled, required bool active}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Material(
child: Center(
child: Switch(
trackOutlineWidth: trackOutlineWidth,
value: active,
onChanged: enabled ? (_) { } : null,
),
),
),
);
}
await tester.pumpWidget(buildSwitch(enabled: false, active: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(strokeWidth: inactiveDisabledTrackOutlineWidth, style: PaintingStyle.stroke),
reason: 'Inactive disabled switch track outline width should be 4.0',
);
await tester.pumpWidget(buildSwitch(enabled: false, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(strokeWidth: activeDisabledTrackOutlineWidth, style: PaintingStyle.stroke),
reason: 'Active disabled switch track outline width should be 2.0',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(strokeWidth: inactiveEnabledTrackOutlineWidth, style: PaintingStyle.stroke),
reason: 'Inactive enabled switch track outline width should be 3.0',
);
await tester.pumpWidget(buildSwitch(enabled: true, active: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(strokeWidth: activeEnabledTrackOutlineWidth, style: PaintingStyle.stroke),
reason: 'Active enabled switch track outline width should be 1.0',
);
});
testWidgets('Switch track outline width resolves in hovered/focused states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const double hoveredTrackOutlineWidth = 4.0;
const double focusedTrackOutlineWidth = 6.0;
double getTrackOutlineWidth(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredTrackOutlineWidth;
}
if (states.contains(MaterialState.focused)) {
return focusedTrackOutlineWidth;
}
return 8.0;
}
final MaterialStateProperty<double> trackOutlineWidth = MaterialStateProperty.resolveWith(getTrackOutlineWidth);
Widget buildSwitch() {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Material(
child: Center(
child: Switch(
focusNode: focusNode,
autofocus: true,
value: true,
trackOutlineWidth: trackOutlineWidth,
onChanged: (_) { },
),
),
),
);
}
await tester.pumpWidget(buildSwitch());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(strokeWidth: focusedTrackOutlineWidth, style: PaintingStyle.stroke),
reason: 'Active enabled switch track outline width should be 6.0',
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(strokeWidth: hoveredTrackOutlineWidth, style: PaintingStyle.stroke),
reason: 'Active enabled switch track outline width should be 4.0',
);
focusNode.dispose();
});
testWidgets('Switch can set icon - M3', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(
useMaterial3: true,
colorSchemeSeed: const Color(0xff6750a4),
brightness: Brightness.light);
MaterialStateProperty<Icon?> thumbIcon(Icon? activeIcon, Icon? inactiveIcon) {
return MaterialStateProperty.resolveWith<Icon?>((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return activeIcon;
}
return inactiveIcon;
});
}
Widget buildSwitch({required bool enabled, required bool active, Icon? activeIcon, Icon? inactiveIcon}) {
return Theme(
data: themeData,
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Switch(
thumbIcon: thumbIcon(activeIcon, inactiveIcon),
value: active,
onChanged: enabled ? (_) {} : null,
),
),
),
),
);
}
// active icon shows when switch is on.
await tester.pumpWidget(buildSwitch(enabled: true, active: true, activeIcon: const Icon(Icons.close)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()
..paragraph(offset: const Offset(32.0, 16.0)),
);
// inactive icon shows when switch is off.
await tester.pumpWidget(buildSwitch(enabled: true, active: false, inactiveIcon: const Icon(Icons.close)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()
..rrect()
..paragraph(offset: const Offset(12.0, 16.0)),
);
// active icon doesn't show when switch is off.
await tester.pumpWidget(buildSwitch(enabled: true, active: false, activeIcon: const Icon(Icons.check)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()..rrect()
);
// inactive icon doesn't show when switch is on.
await tester.pumpWidget(buildSwitch(enabled: true, active: true, inactiveIcon: const Icon(Icons.check)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()..restore(),
);
// without icon
await tester.pumpWidget(buildSwitch(enabled: true, active: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()..rrect()..restore(),
);
});
});
testWidgets('Switch.adaptive(Cupertino) is focusable and has correct focus color', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch.adaptive');
addTearDown(focusNode.dispose);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool value = true;
const Color focusColor = Color(0xffff0000);
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: ThemeData(platform: TargetPlatform.iOS),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: Switch.adaptive(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
focusColor: focusColor,
focusNode: focusNode,
autofocus: true,
),
);
},
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
find.byType(Switch),
paints
..rrect(color: const Color(0xff34c759))
..rrect(color: const Color(0x00000000))
..rrect(color: focusColor)
..clipRRect()
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000))
..rrect(color: const Color(0xffffffff)),
);
// Check the false value.
value = false;
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
find.byType(Switch),
paints
..rrect(color: const Color(0x28787880))
..rrect(color: const Color(0x00000000))
..rrect(color: focusColor)
..clipRRect()
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000))
..rrect(color: const Color(0xffffffff)),
);
// Check what happens when disabled.
value = false;
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expect(
find.byType(Switch),
paints
..rrect(color: const Color(0x28787880))
..clipRRect()
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000))
..rrect(color: const Color(0xffffffff)),
);
});
testWidgets('Switch.onFocusChange callback', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Switch');
bool focused = false;
await tester.pumpWidget(MaterialApp(
home: Material(
child: Center(
child: Switch(
value: true,
focusNode: focusNode,
onFocusChange: (bool value) {
focused = value;
},
onChanged:(bool newValue) {},
),
),
),
));
focusNode.requestFocus();
await tester.pump();
expect(focused, isTrue);
expect(focusNode.hasFocus, isTrue);
focusNode.unfocus();
await tester.pump();
expect(focused, isFalse);
expect(focusNode.hasFocus, isFalse);
focusNode.dispose();
});
}
class DelayedImageProvider extends ImageProvider<DelayedImageProvider> {
DelayedImageProvider(this.image);
final ui.Image image;
final Completer<ImageInfo> _completer = Completer<ImageInfo>();
@override
Future<DelayedImageProvider> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<DelayedImageProvider>(this);
}
@override
ImageStreamCompleter loadImage(DelayedImageProvider key, ImageDecoderCallback decode) {
return OneFrameImageStreamCompleter(_completer.future);
}
Future<void> complete() async {
_completer.complete(ImageInfo(image: image));
}
@override
String toString() => '${describeIdentity(this)}()';
}
class _TestImageProvider extends ImageProvider<Object> {
_TestImageProvider({ImageStreamCompleter? streamCompleter}) {
_streamCompleter = streamCompleter
?? OneFrameImageStreamCompleter(_completer.future);
}
final Completer<ImageInfo> _completer = Completer<ImageInfo>();
late ImageStreamCompleter _streamCompleter;
bool get loadCalled => _loadCallCount > 0;
int get loadCallCount => _loadCallCount;
int _loadCallCount = 0;
@override
Future<Object> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<_TestImageProvider>(this);
}
@override
void resolveStreamForKey(ImageConfiguration configuration, ImageStream stream, Object key, ImageErrorListener handleError) {
super.resolveStreamForKey(configuration, stream, key, handleError);
}
@override
ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) {
_loadCallCount += 1;
return _streamCompleter;
}
void complete(ui.Image image) {
_completer.complete(ImageInfo(image: image));
}
void fail(Object exception, StackTrace? stackTrace) {
_completer.completeError(exception, stackTrace);
}
@override
String toString() => '${describeIdentity(this)}()';
}
Widget buildAdaptiveSwitch({
required TargetPlatform platform,
bool enabled = true,
bool value = true,
bool autofocus = false,
FocusNode? focusNode,
Color? focusColor,
SwitchThemeData? overallSwitchThemeData,
SwitchThemeData? switchThemeData,
Adaptation<SwitchThemeData>? switchThemeAdaptation,
}) {
final Widget adaptiveSwitch = Switch.adaptive(
focusNode: focusNode,
autofocus: autofocus,
focusColor: focusColor,
value: value,
onChanged: enabled ? (_) {} : null,
);
return MaterialApp(
theme: ThemeData(
platform: platform,
switchTheme: overallSwitchThemeData,
adaptations: switchThemeAdaptation == null ? null : <Adaptation<Object>>[
switchThemeAdaptation
],
),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: switchThemeData == null
? adaptiveSwitch
: SwitchTheme(
data: switchThemeData,
child: adaptiveSwitch,
),
),
);
},
),
);
}
class _SwitchThemeAdaptation extends Adaptation<SwitchThemeData> {
const _SwitchThemeAdaptation();
@override
SwitchThemeData adapt(ThemeData theme, SwitchThemeData defaultValue) {
switch (theme.platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.windows:
case TargetPlatform.linux:
return defaultValue;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return const SwitchThemeData(
thumbColor: MaterialStatePropertyAll<Color>(Colors.lightGreen),
trackColor: MaterialStatePropertyAll<Color>(Colors.deepPurple),
);
}
}
}
| flutter/packages/flutter/test/material/switch_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/switch_test.dart",
"repo_id": "flutter",
"token_count": 63328
} | 659 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/clipboard_utils.dart';
import '../widgets/editable_text_utils.dart' show findRenderEditable, globalize, textOffsetToPosition;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final MockClipboard mockClipboard = MockClipboard();
setUp(() async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform,
mockClipboard.handleMethodCall,
);
// Fill the clipboard so that the Paste option is available in the text
// selection menu.
await Clipboard.setData(const ClipboardData(text: 'clipboard data'));
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
);
});
group('canSelectAll', () {
Widget createEditableText({
required Key key,
String? text,
TextSelection? selection,
}) {
final TextEditingController controller = TextEditingController(text: text)
..selection = selection ?? const TextSelection.collapsed(offset: -1);
addTearDown(controller.dispose);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
return MaterialApp(
home: EditableText(
key: key,
controller: controller,
focusNode: focusNode,
style: const TextStyle(),
cursorColor: Colors.black,
backgroundCursorColor: Colors.black,
),
);
}
testWidgets('should return false when there is no text', (WidgetTester tester) async {
final GlobalKey<EditableTextState> key = GlobalKey();
await tester.pumpWidget(createEditableText(key: key));
expect(materialTextSelectionControls.canSelectAll(key.currentState!), false);
});
testWidgets('should return true when there is text and collapsed selection', (WidgetTester tester) async {
final GlobalKey<EditableTextState> key = GlobalKey();
await tester.pumpWidget(createEditableText(
key: key,
text: '123',
));
expect(materialTextSelectionControls.canSelectAll(key.currentState!), true);
});
testWidgets('should return true when there is text and partial uncollapsed selection', (WidgetTester tester) async {
final GlobalKey<EditableTextState> key = GlobalKey();
await tester.pumpWidget(createEditableText(
key: key,
text: '123',
selection: const TextSelection(baseOffset: 1, extentOffset: 2),
));
expect(materialTextSelectionControls.canSelectAll(key.currentState!), true);
});
testWidgets('should return false when there is text and full selection', (WidgetTester tester) async {
final GlobalKey<EditableTextState> key = GlobalKey();
await tester.pumpWidget(createEditableText(
key: key,
text: '123',
selection: const TextSelection(baseOffset: 0, extentOffset: 3),
));
expect(materialTextSelectionControls.canSelectAll(key.currentState!), false);
});
});
group('Text selection menu overflow (Android)', () {
testWidgets('All menu items show when they fit.', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(text: 'abc def ghi');
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(size: Size(800.0, 600.0)),
child: Center(
child: Material(
child: TextField(
controller: controller,
),
),
),
),
),
));
// Initially, the menu isn't shown at all.
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing);
// Tap to place the cursor in the field, then tap the handle to show the
// selection menu.
await tester.tap(find.byType(TextField));
await tester.pumpAndSettle();
final RenderEditable renderEditable = findRenderEditable(tester);
final List<TextSelectionPoint> endpoints = globalize(
renderEditable.getEndpointsForSelection(controller.selection),
renderEditable,
);
expect(endpoints.length, 1);
final Offset handlePos = endpoints[0].point + const Offset(0.0, 1.0);
await tester.tapAt(handlePos, pointer: 7);
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsNothing);
// Long press to select a word and show the full selection menu.
final Offset textOffset = textOffsetToPosition(tester, 1);
await tester.longPressAt(textOffset);
await tester.pump();
await tester.pump();
// The full menu is shown without the more button.
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsNothing);
},
skip: isBrowser, // [intended] We do not use Flutter-rendered context menu on the Web.
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
);
testWidgets("When menu items don't fit, an overflow menu is used.", (WidgetTester tester) async {
// Set the screen size to more narrow, so that Select all can't fit.
tester.view.physicalSize = const Size(1000, 800);
addTearDown(tester.view.reset);
final TextEditingController controller = TextEditingController(text: 'abc def ghi');
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(size: Size(800.0, 600.0)),
child: Center(
child: Material(
child: TextField(
controller: controller,
),
),
),
),
),
));
// Initially, the menu isn't shown at all.
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing);
// Long press to show the menu.
final Offset textOffset = textOffsetToPosition(tester, 1);
await tester.longPressAt(textOffset);
await tester.pumpAndSettle();
// The last button is missing, and a more button is shown.
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget);
final Offset cutOffset = tester.getTopLeft(find.text('Cut'));
// Tapping the button shows the overflow menu.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsOneWidget);
// The back button is at the bottom of the overflow menu.
final Offset selectAllOffset = tester.getTopLeft(find.text('Select all'));
final Offset moreOffset = tester.getTopLeft(find.byType(IconButton));
expect(moreOffset.dy, greaterThan(selectAllOffset.dy));
// The overflow menu grows upward.
expect(selectAllOffset.dy, lessThan(cutOffset.dy));
// Tapping the back button shows the selection menu again.
expect(find.byType(IconButton), findsOneWidget);
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget);
},
skip: isBrowser, // [intended] We do not use Flutter-rendered context menu on the Web.
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
);
testWidgets('A smaller menu bumps more items to the overflow menu.', (WidgetTester tester) async {
// Set the screen size so narrow that only Cut and Copy can fit.
tester.view.physicalSize = const Size(800, 800);
addTearDown(tester.view.reset);
final TextEditingController controller = TextEditingController(text: 'abc def ghi');
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(size: Size(800.0, 600.0)),
child: Center(
child: Material(
child: TextField(
controller: controller,
),
),
),
),
),
));
// Initially, the menu isn't shown at all.
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing);
// Long press to show the menu.
final Offset textOffset = textOffsetToPosition(tester, 1);
await tester.longPressAt(textOffset);
await tester.pumpAndSettle();
// The last two buttons are missing, and a more button is shown.
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget);
// Tapping the button shows the overflow menu, which contains both buttons
// missing from the main menu, and a back button.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsOneWidget);
// Tapping the back button shows the selection menu again.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget);
},
skip: isBrowser, // [intended] We do not use Flutter-rendered context menu on the Web.
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
);
testWidgets('When the menu renders below the text, the overflow menu back button is at the top.', (WidgetTester tester) async {
// Set the screen size to more narrow, so that Select all can't fit.
tester.view.physicalSize = const Size(1000, 800);
addTearDown(tester.view.reset);
final TextEditingController controller = TextEditingController(text: 'abc def ghi');
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(size: Size(800.0, 600.0)),
child: Align(
alignment: Alignment.topLeft,
child: Material(
child: TextField(
controller: controller,
),
),
),
),
),
));
// Initially, the menu isn't shown at all.
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing);
// Long press to show the menu.
final Offset textOffset = textOffsetToPosition(tester, 1);
await tester.longPressAt(textOffset);
await tester.pumpAndSettle();
// The last button is missing, and a more button is shown.
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget);
final Offset cutOffset = tester.getTopLeft(find.text('Cut'));
// Tapping the button shows the overflow menu.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsOneWidget);
// The back button is at the top of the overflow menu.
final Offset selectAllOffset = tester.getTopLeft(find.text('Select all'));
final Offset moreOffset = tester.getTopLeft(find.byType(IconButton));
expect(moreOffset.dy, lessThan(selectAllOffset.dy));
// The overflow menu grows downward.
expect(selectAllOffset.dy, greaterThan(cutOffset.dy));
// Tapping the back button shows the selection menu again.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget);
},
skip: isBrowser, // [intended] We do not use Flutter-rendered context menu on the Web.
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
);
testWidgets('When the menu items change, the menu is closed and _closedWidth reset.', (WidgetTester tester) async {
// Set the screen size to more narrow, so that Select all can't fit.
tester.view.physicalSize = const Size(1000, 800);
addTearDown(tester.view.reset);
final TextEditingController controller = TextEditingController(text: 'abc def ghi');
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false),
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(size: Size(800.0, 600.0)),
child: Align(
alignment: Alignment.topLeft,
child: Material(
child: TextField(
controller: controller,
),
),
),
),
),
));
// Initially, the menu isn't shown at all.
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Share'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing); // 'More' button.
// Tap to place the cursor and tap again to show the menu without a
// selection.
await tester.tapAt(textOffsetToPosition(tester, 0));
await tester.pumpAndSettle();
final RenderEditable renderEditable = findRenderEditable(tester);
final List<TextSelectionPoint> endpoints = globalize(
renderEditable.getEndpointsForSelection(controller.selection),
renderEditable,
);
expect(endpoints.length, 1);
final Offset handlePos = endpoints[0].point + const Offset(0.0, 1.0);
await tester.tapAt(handlePos, pointer: 7);
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share'), findsNothing);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsNothing);
// Tap Select all and measure the usual position of Cut, without
// _closedWidth having been used yet.
await tester.tap(find.text('Select all'));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget); // 'More' button.
final Offset cutOffset = tester.getTopLeft(find.text('Cut'));
// Tap to clear the selection.
await tester.tapAt(textOffsetToPosition(tester, 0));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing); // 'More' button.
// Long press to show the menu.
await tester.longPressAt(textOffsetToPosition(tester, 1));
await tester.pumpAndSettle();
// The last buttons (share and select all) are missing, and a more button is shown.
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget); // 'More' button.
// Tapping the more button shows the overflow menu.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Share'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsOneWidget); // Back button.
// Tapping 'Select all' closes the overflow menu.
await tester.tap(find.text('Select all'));
await tester.pumpAndSettle();
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsOneWidget); // 'More' button.
final Offset newCutOffset = tester.getTopLeft(find.text('Cut'));
expect(newCutOffset, equals(cutOffset));
},
skip: isBrowser, // [intended] We do not use Flutter-rendered context menu on the Web.
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
);
});
group('menu position', () {
testWidgets('When renders below a block of text, menu appears below bottom endpoint', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(text: 'abc\ndef\nghi\njkl\nmno\npqr');
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(size: Size(800.0, 600.0)),
child: Align(
alignment: Alignment.topLeft,
child: Material(
child: TextField(
controller: controller,
),
),
),
),
),
));
// Initially, the menu isn't shown at all.
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing);
// Tap to place the cursor in the field, then tap the handle to show the
// selection menu.
await tester.tap(find.byType(TextField));
await tester.pumpAndSettle();
RenderEditable renderEditable = findRenderEditable(tester);
List<TextSelectionPoint> endpoints = globalize(
renderEditable.getEndpointsForSelection(controller.selection),
renderEditable,
);
expect(endpoints.length, 1);
final Offset handlePos = endpoints[0].point + const Offset(0.0, 1.0);
await tester.tapAt(handlePos, pointer: 7);
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsNothing);
// Tap to select all.
await tester.tap(find.text('Select all'));
await tester.pumpAndSettle();
// Only Cut, Copy, and Paste are shown.
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing);
// The menu appears below the bottom handle.
renderEditable = findRenderEditable(tester);
endpoints = globalize(
renderEditable.getEndpointsForSelection(controller.selection),
renderEditable,
);
expect(endpoints.length, 2);
final Offset bottomHandlePos = endpoints[1].point;
final Offset cutOffset = tester.getTopLeft(find.text('Cut'));
expect(cutOffset.dy, greaterThan(bottomHandlePos.dy));
},
skip: isBrowser, // [intended] We do not use Flutter-rendered context menu on the Web.
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
);
testWidgets(
'When selecting multiple lines over max lines',
(WidgetTester tester) async {
final TextEditingController controller =
TextEditingController(text: 'abc\ndef\nghi\njkl\nmno\npqr');
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(size: Size(800.0, 600.0)),
child: Align(
alignment: Alignment.bottomCenter,
child: Material(
child: TextField(
decoration: const InputDecoration(contentPadding: EdgeInsets.all(8.0)),
style: const TextStyle(fontSize: 32, height: 1),
maxLines: 2,
controller: controller,
),
),
),
),
),
));
// Initially, the menu isn't shown at all.
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing);
// Tap to place the cursor in the field, then tap the handle to show the
// selection menu.
await tester.tap(find.byType(TextField));
await tester.pumpAndSettle();
final RenderEditable renderEditable = findRenderEditable(tester);
final List<TextSelectionPoint> endpoints = globalize(
renderEditable.getEndpointsForSelection(controller.selection),
renderEditable,
);
expect(endpoints.length, 1);
final Offset handlePos = endpoints[0].point + const Offset(0.0, 1.0);
await tester.tapAt(handlePos, pointer: 7);
await tester.pumpAndSettle();
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
expect(find.byType(IconButton), findsNothing);
// Tap to select all.
await tester.tap(find.text('Select all'));
await tester.pumpAndSettle();
// Only Cut, Copy, and Paste are shown.
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsNothing);
expect(find.byType(IconButton), findsNothing);
// The menu appears at the top of the visible selection.
final Offset selectionOffset = tester
.getTopLeft(find.byType(TextSelectionToolbarTextButton).first);
final Offset textFieldOffset =
tester.getTopLeft(find.byType(TextField));
// 44.0 + 8.0 - 8.0 = _kToolbarHeight + _kToolbarContentDistance - contentPadding
expect(selectionOffset.dy + 44.0 + 8.0 - 8.0, equals(textFieldOffset.dy));
},
skip: isBrowser, // [intended] the selection menu isn't required by web
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
);
});
group('material handles', () {
testWidgets('draws transparent handle correctly', (WidgetTester tester) async {
await tester.pumpWidget(RepaintBoundary(
child: Theme(
data: ThemeData(
textSelectionTheme: const TextSelectionThemeData(
selectionHandleColor: Color(0x550000AA),
),
),
child: Builder(
builder: (BuildContext context) {
return Container(
color: Colors.white,
height: 800,
width: 800,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 250),
child: FittedBox(
child: materialTextSelectionControls.buildHandle(
context, TextSelectionHandleType.right, 10.0,
),
),
),
);
},
),
),
));
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('transparent_handle.png'),
);
});
testWidgets('works with 3 positional parameters', (WidgetTester tester) async {
await tester.pumpWidget(Theme(
data: ThemeData(
textSelectionTheme: const TextSelectionThemeData(
selectionHandleColor: Color(0x550000AA),
),
),
child: Builder(
builder: (BuildContext context) {
return Container(
color: Colors.white,
height: 800,
width: 800,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 250),
child: FittedBox(
child: materialTextSelectionControls.buildHandle(
context, TextSelectionHandleType.right, 10.0,
),
),
),
);
},
),
));
// No expect here as this should simply compile / not throw any
// exceptions while building. The test will fail if this either does
// not compile or if the tester catches an exception, which we do
// not take here.
});
});
testWidgets('Paste only appears when clipboard has contents', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(
text: 'Atwater Peel Sherbrooke Bonaventure',
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
TextField(
controller: controller,
),
],
),
),
),
);
// Make sure the clipboard is empty to start.
await Clipboard.setData(const ClipboardData(text: ''));
// Double tap to select the first word.
const int index = 4;
await tester.tapAt(textOffsetToPosition(tester, index));
await tester.pump(const Duration(milliseconds: 50));
await tester.tapAt(textOffsetToPosition(tester, index));
await tester.pumpAndSettle();
// No Paste yet, because nothing has been copied.
expect(find.text('Paste'), findsNothing);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
// Tap copy to add something to the clipboard and close the menu.
await tester.tapAt(tester.getCenter(find.text('Copy')));
await tester.pumpAndSettle();
expect(find.text('Copy'), findsNothing);
expect(find.text('Cut'), findsNothing);
expect(find.text('Select all'), findsNothing);
// Double tap to show the menu again.
await tester.tapAt(textOffsetToPosition(tester, index));
await tester.pump(const Duration(milliseconds: 50));
await tester.tapAt(textOffsetToPosition(tester, index));
await tester.pumpAndSettle();
// Paste now shows.
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
},
skip: isBrowser, // [intended] we don't supply the cut/copy/paste buttons on the web.
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android })
);
}
| flutter/packages/flutter/test/material/text_selection_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/text_selection_test.dart",
"repo_id": "flutter",
"token_count": 12307
} | 660 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Typography is defined for all target platforms', () {
for (final TargetPlatform platform in TargetPlatform.values) {
final Typography typography = Typography.material2018(platform: platform);
expect(typography, isNotNull, reason: 'null typography for $platform');
expect(typography.black, isNotNull, reason: 'null black typography for $platform');
expect(typography.white, isNotNull, reason: 'null white typography for $platform');
}
});
test('Typography lerp special cases', () {
final Typography typography = Typography();
expect(identical(Typography.lerp(typography, typography, 0.5), typography), true);
});
test('Typography on non-Apple platforms defaults to the correct font', () {
expect(Typography.material2018().black.titleLarge!.fontFamily, 'Roboto');
expect(Typography.material2018(platform: TargetPlatform.fuchsia).black.titleLarge!.fontFamily, 'Roboto');
expect(Typography.material2018(platform: TargetPlatform.linux).black.titleLarge!.fontFamily, 'Roboto');
expect(Typography.material2018(platform: TargetPlatform.linux).black.titleLarge!.fontFamilyFallback, <String>['Ubuntu', 'Cantarell', 'DejaVu Sans', 'Liberation Sans', 'Arial']);
expect(Typography.material2018(platform: TargetPlatform.windows).black.titleLarge!.fontFamily, 'Segoe UI');
expect(Typography.material2018().white.titleLarge!.fontFamily, 'Roboto');
expect(Typography.material2018(platform: TargetPlatform.fuchsia).white.titleLarge!.fontFamily, 'Roboto');
expect(Typography.material2018(platform: TargetPlatform.linux).white.titleLarge!.fontFamily, 'Roboto');
expect(Typography.material2018(platform: TargetPlatform.linux).white.titleLarge!.fontFamilyFallback, <String>['Ubuntu', 'Cantarell', 'DejaVu Sans', 'Liberation Sans', 'Arial']);
expect(Typography.material2018(platform: TargetPlatform.windows).white.titleLarge!.fontFamily, 'Segoe UI');
});
// Ref: https://developer.apple.com/design/human-interface-guidelines/typography/
final Matcher isSanFranciscoDisplayFont = predicate((TextStyle s) {
return s.fontFamily == 'CupertinoSystemDisplay';
}, 'Uses SF Display font');
final Matcher isSanFranciscoTextFont = predicate((TextStyle s) {
return s.fontFamily == 'CupertinoSystemText';
}, 'Uses SF Text font');
final Matcher isMacOSSanFranciscoMetaFont = predicate((TextStyle s) {
return s.fontFamily == '.AppleSystemUIFont';
}, 'Uses macOS system meta-font');
test('Typography on iOS defaults to the correct SF font family based on size', () {
final Typography typography = Typography.material2018(platform: TargetPlatform.iOS);
for (final TextTheme textTheme in <TextTheme>[typography.black, typography.white]) {
expect(textTheme.displayLarge, isSanFranciscoDisplayFont);
expect(textTheme.displayMedium, isSanFranciscoDisplayFont);
expect(textTheme.displaySmall, isSanFranciscoDisplayFont);
expect(textTheme.headlineLarge, isSanFranciscoDisplayFont);
expect(textTheme.headlineMedium, isSanFranciscoDisplayFont);
expect(textTheme.headlineSmall, isSanFranciscoDisplayFont);
expect(textTheme.titleLarge, isSanFranciscoDisplayFont);
expect(textTheme.titleMedium, isSanFranciscoTextFont);
expect(textTheme.titleSmall, isSanFranciscoTextFont);
expect(textTheme.bodyLarge, isSanFranciscoTextFont);
expect(textTheme.bodyMedium, isSanFranciscoTextFont);
expect(textTheme.bodySmall, isSanFranciscoTextFont);
expect(textTheme.labelLarge, isSanFranciscoTextFont);
expect(textTheme.labelMedium, isSanFranciscoTextFont);
expect(textTheme.labelSmall, isSanFranciscoTextFont);
}
});
test('Typography on macOS defaults to the system UI meta-font', () {
final Typography typography = Typography.material2018(platform: TargetPlatform.macOS);
for (final TextTheme textTheme in <TextTheme>[typography.black, typography.white]) {
expect(textTheme.displayLarge, isMacOSSanFranciscoMetaFont);
expect(textTheme.displayMedium, isMacOSSanFranciscoMetaFont);
expect(textTheme.displaySmall, isMacOSSanFranciscoMetaFont);
expect(textTheme.headlineLarge, isMacOSSanFranciscoMetaFont);
expect(textTheme.headlineMedium, isMacOSSanFranciscoMetaFont);
expect(textTheme.headlineSmall, isMacOSSanFranciscoMetaFont);
expect(textTheme.titleLarge, isMacOSSanFranciscoMetaFont);
expect(textTheme.titleMedium, isMacOSSanFranciscoMetaFont);
expect(textTheme.titleSmall, isMacOSSanFranciscoMetaFont);
expect(textTheme.bodyLarge, isMacOSSanFranciscoMetaFont);
expect(textTheme.bodyMedium, isMacOSSanFranciscoMetaFont);
expect(textTheme.bodySmall, isMacOSSanFranciscoMetaFont);
expect(textTheme.labelLarge, isMacOSSanFranciscoMetaFont);
expect(textTheme.labelMedium, isMacOSSanFranciscoMetaFont);
expect(textTheme.labelSmall, isMacOSSanFranciscoMetaFont);
}
});
testWidgets('Typography implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
Typography.material2014(
black: Typography.blackCupertino,
white: Typography.whiteCupertino,
englishLike: Typography.englishLike2018,
dense: Typography.dense2018,
tall: Typography.tall2018,
).debugFillProperties(builder);
final List<String> nonDefaultPropertyNames = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.name!).toList();
expect(nonDefaultPropertyNames, <String>['black', 'white', 'englishLike', 'dense', 'tall']);
});
test('Can lerp between different typographies', () {
final List<Typography> all = <Typography>[
for (final TargetPlatform platform in TargetPlatform.values) Typography.material2014(platform: platform),
for (final TargetPlatform platform in TargetPlatform.values) Typography.material2018(platform: platform),
for (final TargetPlatform platform in TargetPlatform.values) Typography.material2021(platform: platform),
];
for (final Typography fromTypography in all) {
for (final Typography toTypography in all) {
Object? error;
try {
Typography.lerp(fromTypography, toTypography, 0.5);
} catch (e) {
error = e;
}
expect(error, isNull);
}
}
});
test('englishLike2018 TextTheme matches Material Design spec', () {
// Check the default material text theme against the style values
// shown https://material.io/design/typography/#type-scale.
final TextTheme theme = Typography.englishLike2018.merge(Typography.blackMountainView);
const FontWeight light = FontWeight.w300;
const FontWeight regular = FontWeight.w400;
const FontWeight medium = FontWeight.w500;
// H1 Roboto light 96 -1.5
expect(theme.displayLarge!.fontFamily, 'Roboto');
expect(theme.displayLarge!.fontWeight, light);
expect(theme.displayLarge!.fontSize, 96);
expect(theme.displayLarge!.letterSpacing, -1.5);
// H2 Roboto light 60 -0.5
expect(theme.displayMedium!.fontFamily, 'Roboto');
expect(theme.displayMedium!.fontWeight, light);
expect(theme.displayMedium!.fontSize, 60);
expect(theme.displayMedium!.letterSpacing, -0.5);
// H3 Roboto regular 48 0
expect(theme.displaySmall!.fontFamily, 'Roboto');
expect(theme.displaySmall!.fontWeight, regular);
expect(theme.displaySmall!.fontSize, 48);
expect(theme.displaySmall!.letterSpacing, 0);
// Headline Large (from Material 3 for backwards compatibility) Roboto regular 40 0.25
expect(theme.headlineLarge!.fontFamily, 'Roboto');
expect(theme.headlineLarge!.fontWeight, regular);
expect(theme.headlineLarge!.fontSize, 40);
expect(theme.headlineLarge!.letterSpacing, 0.25);
// H4 Roboto regular 34 0.25
expect(theme.headlineMedium!.fontFamily, 'Roboto');
expect(theme.headlineMedium!.fontWeight, regular);
expect(theme.headlineMedium!.fontSize, 34);
expect(theme.headlineMedium!.letterSpacing, 0.25);
// H5 Roboto regular 24 0
expect(theme.headlineSmall!.fontFamily, 'Roboto');
expect(theme.headlineSmall!.fontWeight, regular);
expect(theme.headlineSmall!.fontSize, 24);
expect(theme.headlineSmall!.letterSpacing, 0);
// H6 Roboto medium 20 0.15
expect(theme.titleLarge!.fontFamily, 'Roboto');
expect(theme.titleLarge!.fontWeight, medium);
expect(theme.titleLarge!.fontSize, 20);
expect(theme.titleLarge!.letterSpacing, 0.15);
// Subtitle1 Roboto regular 16 0.15
expect(theme.titleMedium!.fontFamily, 'Roboto');
expect(theme.titleMedium!.fontWeight, regular);
expect(theme.titleMedium!.fontSize, 16);
expect(theme.titleMedium!.letterSpacing, 0.15);
// Subtitle2 Roboto medium 14 0.1
expect(theme.titleSmall!.fontFamily, 'Roboto');
expect(theme.titleSmall!.fontWeight, medium);
expect(theme.titleSmall!.fontSize, 14);
expect(theme.titleSmall!.letterSpacing, 0.1);
// Body1 Roboto regular 16 0.5
expect(theme.bodyLarge!.fontFamily, 'Roboto');
expect(theme.bodyLarge!.fontWeight, regular);
expect(theme.bodyLarge!.fontSize, 16);
expect(theme.bodyLarge!.letterSpacing, 0.5);
// Body2 Roboto regular 14 0.25
expect(theme.bodyMedium!.fontFamily, 'Roboto');
expect(theme.bodyMedium!.fontWeight, regular);
expect(theme.bodyMedium!.fontSize, 14);
expect(theme.bodyMedium!.letterSpacing, 0.25);
// Caption Roboto regular 12 0.4
expect(theme.bodySmall!.fontFamily, 'Roboto');
expect(theme.bodySmall!.fontWeight, regular);
expect(theme.bodySmall!.fontSize, 12);
expect(theme.bodySmall!.letterSpacing, 0.4);
// BUTTON Roboto medium 14 1.25
expect(theme.labelLarge!.fontFamily, 'Roboto');
expect(theme.labelLarge!.fontWeight, medium);
expect(theme.labelLarge!.fontSize, 14);
expect(theme.labelLarge!.letterSpacing, 1.25);
// Label Medium (from Material 3 for backwards compatibility) Roboto regular 11 1.5
expect(theme.labelMedium!.fontFamily, 'Roboto');
expect(theme.labelMedium!.fontWeight, regular);
expect(theme.labelMedium!.fontSize, 11);
expect(theme.labelMedium!.letterSpacing, 1.5);
// OVERLINE Roboto regular 10 1.5
expect(theme.labelSmall!.fontFamily, 'Roboto');
expect(theme.labelSmall!.fontWeight, regular);
expect(theme.labelSmall!.fontSize, 10);
expect(theme.labelSmall!.letterSpacing, 1.5);
});
test('englishLike2021 TextTheme matches Material Design 3 spec', () {
// Check the default material text theme against the style values
// shown https://m3.material.io/styles/typography/tokens.
//
// This may need to be updated if the token values change.
final TextTheme theme = Typography.englishLike2021.merge(Typography.blackMountainView);
// Display large
expect(theme.displayLarge!.fontFamily, 'Roboto');
expect(theme.displayLarge!.fontSize, 57.0);
expect(theme.displayLarge!.fontWeight, FontWeight.w400);
expect(theme.displayLarge!.letterSpacing, -0.25);
expect(theme.displayLarge!.height, 1.12);
expect(theme.displayLarge!.textBaseline, TextBaseline.alphabetic);
expect(theme.displayLarge!.leadingDistribution, TextLeadingDistribution.even);
// Display medium
expect(theme.displayMedium!.fontFamily, 'Roboto');
expect(theme.displayMedium!.fontSize, 45.0);
expect(theme.displayMedium!.fontWeight, FontWeight.w400);
expect(theme.displayMedium!.letterSpacing, 0.0);
expect(theme.displayMedium!.height, 1.16);
expect(theme.displayMedium!.textBaseline, TextBaseline.alphabetic);
expect(theme.displayMedium!.leadingDistribution, TextLeadingDistribution.even);
// Display small
expect(theme.displaySmall!.fontFamily, 'Roboto');
expect(theme.displaySmall!.fontSize, 36.0);
expect(theme.displaySmall!.fontWeight, FontWeight.w400);
expect(theme.displaySmall!.letterSpacing, 0.0);
expect(theme.displaySmall!.height, 1.22);
expect(theme.displaySmall!.textBaseline, TextBaseline.alphabetic);
expect(theme.displaySmall!.leadingDistribution, TextLeadingDistribution.even);
// Headline large
expect(theme.headlineLarge!.fontFamily, 'Roboto');
expect(theme.headlineLarge!.fontSize, 32.0);
expect(theme.headlineLarge!.fontWeight, FontWeight.w400);
expect(theme.headlineLarge!.letterSpacing, 0.0);
expect(theme.headlineLarge!.height, 1.25);
expect(theme.headlineLarge!.textBaseline, TextBaseline.alphabetic);
expect(theme.headlineLarge!.leadingDistribution, TextLeadingDistribution.even);
// Headline medium
expect(theme.headlineMedium!.fontFamily, 'Roboto');
expect(theme.headlineMedium!.fontSize, 28.0);
expect(theme.headlineMedium!.fontWeight, FontWeight.w400);
expect(theme.headlineMedium!.letterSpacing, 0.0);
expect(theme.headlineMedium!.height, 1.29);
expect(theme.headlineMedium!.textBaseline, TextBaseline.alphabetic);
expect(theme.headlineMedium!.leadingDistribution, TextLeadingDistribution.even);
// Headline small
expect(theme.headlineSmall!.fontFamily, 'Roboto');
expect(theme.headlineSmall!.fontSize, 24.0);
expect(theme.headlineSmall!.fontWeight, FontWeight.w400);
expect(theme.headlineSmall!.letterSpacing, 0.0);
expect(theme.headlineSmall!.height, 1.33);
expect(theme.headlineSmall!.textBaseline, TextBaseline.alphabetic);
expect(theme.headlineSmall!.leadingDistribution, TextLeadingDistribution.even);
// Title large
expect(theme.titleLarge!.fontFamily, 'Roboto');
expect(theme.titleLarge!.fontSize, 22.0);
expect(theme.titleLarge!.fontWeight, FontWeight.w400);
expect(theme.titleLarge!.letterSpacing, 0.0);
expect(theme.titleLarge!.height, 1.27);
expect(theme.titleLarge!.textBaseline, TextBaseline.alphabetic);
expect(theme.titleLarge!.leadingDistribution, TextLeadingDistribution.even);
// Title medium
expect(theme.titleMedium!.fontFamily, 'Roboto');
expect(theme.titleMedium!.fontSize, 16.0);
expect(theme.titleMedium!.fontWeight, FontWeight.w500);
expect(theme.titleMedium!.letterSpacing, 0.15);
expect(theme.titleMedium!.height, 1.50);
expect(theme.titleMedium!.textBaseline, TextBaseline.alphabetic);
expect(theme.titleMedium!.leadingDistribution, TextLeadingDistribution.even);
// Title small
expect(theme.titleSmall!.fontFamily, 'Roboto');
expect(theme.titleSmall!.fontSize, 14.0);
expect(theme.titleSmall!.fontWeight, FontWeight.w500);
expect(theme.titleSmall!.letterSpacing, 0.1);
expect(theme.titleSmall!.height, 1.43);
expect(theme.titleSmall!.textBaseline, TextBaseline.alphabetic);
expect(theme.titleSmall!.leadingDistribution, TextLeadingDistribution.even);
// Label large
expect(theme.labelLarge!.fontFamily, 'Roboto');
expect(theme.labelLarge!.fontSize, 14.0);
expect(theme.labelLarge!.fontWeight, FontWeight.w500);
expect(theme.labelLarge!.letterSpacing, 0.1);
expect(theme.labelLarge!.height, 1.43);
expect(theme.labelLarge!.textBaseline, TextBaseline.alphabetic);
expect(theme.labelLarge!.leadingDistribution, TextLeadingDistribution.even);
// Label medium
expect(theme.labelMedium!.fontFamily, 'Roboto');
expect(theme.labelMedium!.fontSize, 12.0);
expect(theme.labelMedium!.fontWeight, FontWeight.w500);
expect(theme.labelMedium!.letterSpacing, 0.5);
expect(theme.labelMedium!.height, 1.33);
expect(theme.labelMedium!.textBaseline, TextBaseline.alphabetic);
expect(theme.labelMedium!.leadingDistribution, TextLeadingDistribution.even);
// Label small
expect(theme.labelSmall!.fontFamily, 'Roboto');
expect(theme.labelSmall!.fontSize, 11.0);
expect(theme.labelSmall!.fontWeight, FontWeight.w500);
expect(theme.labelSmall!.letterSpacing, 0.5);
expect(theme.labelSmall!.height, 1.45);
expect(theme.labelSmall!.textBaseline, TextBaseline.alphabetic);
expect(theme.labelSmall!.leadingDistribution, TextLeadingDistribution.even);
// Body large
expect(theme.bodyLarge!.fontFamily, 'Roboto');
expect(theme.bodyLarge!.fontSize, 16.0);
expect(theme.bodyLarge!.fontWeight, FontWeight.w400);
expect(theme.bodyLarge!.letterSpacing, 0.5);
expect(theme.bodyLarge!.height, 1.50);
expect(theme.bodyLarge!.textBaseline, TextBaseline.alphabetic);
expect(theme.bodyLarge!.leadingDistribution, TextLeadingDistribution.even);
// Body medium
expect(theme.bodyMedium!.fontFamily, 'Roboto');
expect(theme.bodyMedium!.fontSize, 14.0);
expect(theme.bodyMedium!.fontWeight, FontWeight.w400);
expect(theme.bodyMedium!.letterSpacing, 0.25);
expect(theme.bodyMedium!.height, 1.43);
expect(theme.bodyMedium!.textBaseline, TextBaseline.alphabetic);
expect(theme.bodyMedium!.leadingDistribution, TextLeadingDistribution.even);
// Body small
expect(theme.bodySmall!.fontFamily, 'Roboto');
expect(theme.bodySmall!.fontSize, 12.0);
expect(theme.bodySmall!.fontWeight, FontWeight.w400);
expect(theme.bodySmall!.letterSpacing, 0.4);
expect(theme.bodySmall!.height, 1.33);
expect(theme.bodySmall!.textBaseline, TextBaseline.alphabetic);
expect(theme.bodySmall!.leadingDistribution, TextLeadingDistribution.even);
});
test('Default M3 light textTheme styles all use onSurface', () {
final ThemeData theme = ThemeData(useMaterial3: true);
final TextTheme textTheme = theme.textTheme;
final Color dark = theme.colorScheme.onSurface;
expect(textTheme.displayLarge!.color, dark);
expect(textTheme.displayMedium!.color, dark);
expect(textTheme.displaySmall!.color, dark);
expect(textTheme.headlineLarge!.color, dark);
expect(textTheme.headlineMedium!.color, dark);
expect(textTheme.headlineSmall!.color, dark);
expect(textTheme.titleLarge!.color, dark);
expect(textTheme.titleMedium!.color, dark);
expect(textTheme.titleSmall!.color, dark);
expect(textTheme.bodyLarge!.color, dark);
expect(textTheme.bodyMedium!.color, dark);
expect(textTheme.bodySmall!.color, dark);
expect(textTheme.labelLarge!.color, dark);
expect(textTheme.labelMedium!.color, dark);
expect(textTheme.labelSmall!.color, dark);
});
test('Default M3 dark textTheme styles all use onSurface', () {
final ThemeData theme = ThemeData(useMaterial3: true, brightness: Brightness.dark);
final TextTheme textTheme = theme.textTheme;
final Color light = theme.colorScheme.onSurface;
expect(textTheme.displayLarge!.color, light);
expect(textTheme.displayMedium!.color, light);
expect(textTheme.displaySmall!.color, light);
expect(textTheme.headlineLarge!.color, light);
expect(textTheme.headlineMedium!.color, light);
expect(textTheme.headlineSmall!.color, light);
expect(textTheme.titleLarge!.color, light);
expect(textTheme.titleMedium!.color, light);
expect(textTheme.titleSmall!.color, light);
expect(textTheme.bodyLarge!.color, light);
expect(textTheme.bodyMedium!.color, light);
expect(textTheme.bodySmall!.color, light);
expect(textTheme.labelLarge!.color, light);
expect(textTheme.labelMedium!.color, light);
expect(textTheme.labelSmall!.color, light);
});
}
| flutter/packages/flutter/test/material/typography_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/typography_test.dart",
"repo_id": "flutter",
"token_count": 6518
} | 661 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
tearDown(() {
debugDisableShadows = true;
});
test('BorderSide control test', () {
const BorderSide side1 = BorderSide();
final BorderSide side2 = side1.copyWith(
color: const Color(0xFF00FFFF),
width: 2.0,
style: BorderStyle.solid,
);
expect(side1, hasOneLineDescription);
expect(side1.hashCode, isNot(equals(side2.hashCode)));
expect(side2.color, equals(const Color(0xFF00FFFF)));
expect(side2.width, equals(2.0));
expect(side2.style, equals(BorderStyle.solid));
expect(BorderSide.lerp(side1, side2, 0.0), equals(side1));
expect(BorderSide.lerp(side1, side2, 1.0), equals(side2));
expect(BorderSide.lerp(side1, side2, 0.5), equals(BorderSide(
color: Color.lerp(const Color(0xFF000000), const Color(0xFF00FFFF), 0.5)!,
width: 1.5,
)));
final BorderSide side3 = side2.copyWith(style: BorderStyle.none);
BorderSide interpolated = BorderSide.lerp(side2, side3, 0.2);
expect(interpolated.style, equals(BorderStyle.solid));
expect(interpolated.color, equals(side2.color.withOpacity(0.8)));
interpolated = BorderSide.lerp(side3, side2, 0.2);
expect(interpolated.style, equals(BorderStyle.solid));
expect(interpolated.color, equals(side2.color.withOpacity(0.2)));
});
test('BorderSide toString test', () {
const BorderSide side1 = BorderSide();
final BorderSide side2 = side1.copyWith(
color: const Color(0xFF00FFFF),
width: 2.0,
style: BorderStyle.solid,
);
expect(side1.toString(), equals('BorderSide'));
expect(side2.toString(), equals('BorderSide(color: Color(0xff00ffff), width: 2.0)'));
});
test('Border control test', () {
final Border border1 = Border.all(width: 4.0);
final Border border2 = Border.lerp(null, border1, 0.25)!;
final Border border3 = Border.lerp(border1, null, 0.25)!;
expect(border1, hasOneLineDescription);
expect(border1.hashCode, isNot(equals(border2.hashCode)));
expect(border2.top.width, equals(1.0));
expect(border3.bottom.width, equals(3.0));
final Border border4 = Border.lerp(border2, border3, 0.5)!;
expect(border4.left.width, equals(2.0));
});
test('Border toString test', () {
expect(
Border.all(width: 4.0).toString(),
equals('Border.all(BorderSide(width: 4.0))'),
);
expect(
const Border(
top: BorderSide(width: 3.0),
right: BorderSide(width: 3.0),
bottom: BorderSide(width: 3.0),
left: BorderSide(width: 3.0),
).toString(),
equals('Border.all(BorderSide(width: 3.0))'),
);
});
test('BoxShadow control test', () {
const BoxShadow shadow1 = BoxShadow(blurRadius: 4.0);
final BoxShadow shadow2 = BoxShadow.lerp(null, shadow1, 0.25)!;
final BoxShadow shadow3 = BoxShadow.lerp(shadow1, null, 0.25)!;
expect(shadow1, hasOneLineDescription);
expect(shadow1.hashCode, isNot(equals(shadow2.hashCode)));
expect(shadow1, equals(const BoxShadow(blurRadius: 4.0)));
expect(shadow2.blurRadius, equals(1.0));
expect(shadow3.blurRadius, equals(3.0));
final BoxShadow shadow4 = BoxShadow.lerp(shadow2, shadow3, 0.5)!;
expect(shadow4.blurRadius, equals(2.0));
List<BoxShadow> shadowList = BoxShadow.lerpList(<BoxShadow>[shadow2, shadow1], <BoxShadow>[shadow3], 0.5)!;
expect(shadowList, equals(<BoxShadow>[shadow4, shadow1.scale(0.5)]));
shadowList = BoxShadow.lerpList(<BoxShadow>[shadow2], <BoxShadow>[shadow3, shadow1], 0.5)!;
expect(shadowList, equals(<BoxShadow>[shadow4, shadow1.scale(0.5)]));
});
test('BoxShadow.lerp identical a,b', () {
expect(BoxShadow.lerp(null, null, 0), null);
const BoxShadow border = BoxShadow();
expect(identical(BoxShadow.lerp(border, border, 0.5), border), true);
});
test('BoxShadowList.lerp identical a,b', () {
expect(BoxShadow.lerpList(null, null, 0), null);
const List<BoxShadow> border = <BoxShadow>[BoxShadow()];
expect(identical(BoxShadow.lerpList(border, border, 0.5), border), true);
});
test('BoxShadow BlurStyle test', () {
const BoxShadow shadow1 = BoxShadow(blurRadius: 4.0);
const BoxShadow shadow2 = BoxShadow(blurRadius: 4.0, blurStyle: BlurStyle.outer);
final BoxShadow shadow3 = BoxShadow.lerp(shadow1, null, 0.25)!;
final BoxShadow shadow4 = BoxShadow.lerp(null, shadow1, 0.25)!;
final BoxShadow shadow5 = BoxShadow.lerp(shadow1, shadow2, 0.25)!;
final BoxShadow shadow6 = BoxShadow.lerp(const BoxShadow(blurStyle: BlurStyle.solid), shadow2, 0.25)!;
expect(shadow1.blurStyle, equals(BlurStyle.normal));
expect(shadow2.blurStyle, equals(BlurStyle.outer));
expect(shadow3.blurStyle, equals(BlurStyle.normal));
expect(shadow4.blurStyle, equals(BlurStyle.normal));
expect(shadow5.blurStyle, equals(BlurStyle.outer));
expect(shadow6.blurStyle, equals(BlurStyle.solid));
List<BoxShadow> shadowList = BoxShadow.lerpList(<BoxShadow>[shadow2, shadow1], <BoxShadow>[shadow3], 0.5)!;
expect(shadowList[0].blurStyle, equals(BlurStyle.outer));
expect(shadowList[1].blurStyle, equals(BlurStyle.normal));
shadowList = BoxShadow.lerpList(<BoxShadow>[shadow6], <BoxShadow>[shadow3, shadow1], 0.5)!;
expect(shadowList[0].blurStyle, equals(BlurStyle.solid));
expect(shadowList[1].blurStyle, equals(BlurStyle.normal));
shadowList = BoxShadow.lerpList(<BoxShadow>[shadow3], <BoxShadow>[shadow6, shadow1], 0.5)!;
expect(shadowList[0].blurStyle, equals(BlurStyle.solid));
expect(shadowList[1].blurStyle, equals(BlurStyle.normal));
shadowList = BoxShadow.lerpList(<BoxShadow>[shadow3], <BoxShadow>[shadow2, shadow1], 0.5)!;
expect(shadowList[0].blurStyle, equals(BlurStyle.outer));
expect(shadowList[1].blurStyle, equals(BlurStyle.normal));
});
test('BoxShadow toString test', () {
expect(const BoxShadow(blurRadius: 4.0).toString(), equals('BoxShadow(Color(0xff000000), Offset(0.0, 0.0), 4.0, 0.0, BlurStyle.normal)'));
expect(const BoxShadow(blurRadius: 4.0, blurStyle: BlurStyle.solid).toString(), equals('BoxShadow(Color(0xff000000), Offset(0.0, 0.0), 4.0, 0.0, BlurStyle.solid)'));
});
testWidgets('BoxShadow BoxStyle.solid', (WidgetTester tester) async {
final Key key = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: Container(
color: Colors.white,
width: 50,
height: 50,
child: Center(
child: Container(
decoration: const BoxDecoration(
boxShadow: <BoxShadow>[BoxShadow(blurRadius: 3.0, blurStyle: BlurStyle.solid)],
),
width: 10,
height: 10,
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('boxShadow.boxStyle.solid.0.0.png'),
);
debugDisableShadows = true;
});
testWidgets('BoxShadow BoxStyle.outer', (WidgetTester tester) async {
final Key key = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: Container(
color: Colors.white,
width: 50,
height: 50,
child: Center(
child: Container(
decoration: const BoxDecoration(
boxShadow: <BoxShadow>[BoxShadow(blurRadius: 8.0, blurStyle: BlurStyle.outer)],
),
width: 20,
height: 20,
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('boxShadow.boxStyle.outer.0.0.png'),
);
debugDisableShadows = true;
});
testWidgets('BoxShadow BoxStyle.inner', (WidgetTester tester) async {
final Key key = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: Container(
color: Colors.white,
width: 50,
height: 50,
child: Center(
child: Container(
decoration: const BoxDecoration(
boxShadow: <BoxShadow>[BoxShadow(blurRadius: 4.0, blurStyle: BlurStyle.inner)],
),
width: 20,
height: 20,
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('boxShadow.boxStyle.inner.0.0.png'),
);
debugDisableShadows = true;
});
testWidgets('BoxShadow BoxStyle.normal', (WidgetTester tester) async {
final Key key = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: Container(
color: Colors.white,
width: 50,
height: 50,
child: Center(
child: Container(
decoration: const BoxDecoration(
boxShadow: <BoxShadow>[BoxShadow(blurRadius: 4.0)],
),
width: 20,
height: 20,
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('boxShadow.boxStyle.normal.0.0.png'),
);
debugDisableShadows = true;
});
testWidgets('BoxShadow BoxStyle.normal.wide_radius', (WidgetTester tester) async {
final Key key = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: Container(
color: Colors.amber,
width: 128,
height: 128,
child: Center(
child: Container(
decoration: const BoxDecoration(
color: Colors.black,
boxShadow: <BoxShadow>[BoxShadow(blurRadius: 16.0, offset: Offset(4, 4), color: Colors.green, spreadRadius: 2)],
),
width: 64,
height: 64,
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('boxShadow.boxStyle.normal.wide_radius.0.0.png'),
);
debugDisableShadows = true;
});
testWidgets('BoxShadow BoxStyle.outer.wide_radius', (WidgetTester tester) async {
final Key key = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: Container(
color: Colors.amber,
width: 128,
height: 128,
child: Center(
child: Container(
decoration: const BoxDecoration(
color: Colors.black,
boxShadow: <BoxShadow>[BoxShadow(blurRadius: 16.0, offset: Offset(4, 4), blurStyle: BlurStyle.outer, color: Colors.red, spreadRadius: 2)],
),
width: 64,
height: 64,
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('boxShadow.boxStyle.outer.wide_radius.0.0.png'),
);
debugDisableShadows = true;
});
testWidgets('BoxShadow BoxStyle.solid.wide_radius', (WidgetTester tester) async {
final Key key = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: Container(
color: Colors.grey,
width: 128,
height: 128,
child: Center(
child: Container(
decoration: const BoxDecoration(
color: Colors.black,
boxShadow: <BoxShadow>[BoxShadow(blurRadius: 16.0, offset: Offset(4, 4), blurStyle: BlurStyle.solid, color: Colors.purple, spreadRadius: 2)],
),
width: 64,
height: 64,
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('boxShadow.boxStyle.solid.wide_radius.0.0.png'),
);
debugDisableShadows = true;
});
testWidgets('BoxShadow BoxStyle.inner.wide_radius', (WidgetTester tester) async {
final Key key = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: Container(
color: Colors.green,
width: 128,
height: 128,
child: Center(
child: Container(
decoration: const BoxDecoration(
color: Colors.black,
boxShadow: <BoxShadow>[BoxShadow(blurRadius: 16.0, offset: Offset(4, 4), blurStyle: BlurStyle.inner, color: Colors.amber, spreadRadius: 2)],
),
width: 64,
height: 64,
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('boxShadow.boxStyle.inner.wide_radius.0.0.png'),
);
debugDisableShadows = true;
});
}
| flutter/packages/flutter/test/painting/box_painter_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/box_painter_test.dart",
"repo_id": "flutter",
"token_count": 6238
} | 662 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import '../rendering/rendering_tester.dart';
import 'mocks_for_image_cache.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
tearDown(() {
imageCache
..clear()
..maximumSize = 1000
..maximumSizeBytes = 10485760;
});
test('Image cache resizing based on count', () async {
imageCache.maximumSize = 2;
final TestImageInfo a = await extractOneFrame(TestImageProvider(1, 1, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo;
final TestImageInfo b = await extractOneFrame(TestImageProvider(2, 2, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo;
final TestImageInfo c = await extractOneFrame(TestImageProvider(3, 3, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo;
final TestImageInfo d = await extractOneFrame(TestImageProvider(1, 4, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(a.value, equals(1));
expect(b.value, equals(2));
expect(c.value, equals(3));
expect(d.value, equals(4));
imageCache.maximumSize = 0;
final TestImageInfo e = await extractOneFrame(TestImageProvider(1, 5, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(e.value, equals(5));
final TestImageInfo f = await extractOneFrame(TestImageProvider(1, 6, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(f.value, equals(6));
imageCache.maximumSize = 3;
final TestImageInfo g = await extractOneFrame(TestImageProvider(1, 7, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(g.value, equals(7));
final TestImageInfo h = await extractOneFrame(TestImageProvider(1, 8, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(h.value, equals(7));
});
test('Image cache resizing based on size', () async {
final ui.Image testImage = await createTestImage(width: 8, height: 8); // 256 B.
imageCache.maximumSizeBytes = 256 * 2;
final TestImageInfo a = await extractOneFrame(TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo;
final TestImageInfo b = await extractOneFrame(TestImageProvider(2, 2, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo;
final TestImageInfo c = await extractOneFrame(TestImageProvider(3, 3, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo;
final TestImageInfo d = await extractOneFrame(TestImageProvider(1, 4, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(a.value, equals(1));
expect(b.value, equals(2));
expect(c.value, equals(3));
expect(d.value, equals(4));
imageCache.maximumSizeBytes = 0;
final TestImageInfo e = await extractOneFrame(TestImageProvider(1, 5, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(e.value, equals(5));
final TestImageInfo f = await extractOneFrame(TestImageProvider(1, 6, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(f.value, equals(6));
imageCache.maximumSizeBytes = 256 * 3;
final TestImageInfo g = await extractOneFrame(TestImageProvider(1, 7, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(g.value, equals(7));
final TestImageInfo h = await extractOneFrame(TestImageProvider(1, 8, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo;
expect(h.value, equals(7));
});
}
| flutter/packages/flutter/test/painting/image_cache_resize_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/image_cache_resize_test.dart",
"repo_id": "flutter",
"token_count": 1242
} | 663 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('OvalBorder defaults', () {
const OvalBorder border = OvalBorder();
expect(border.side, BorderSide.none);
});
test('OvalBorder copyWith, ==, hashCode', () {
expect(const OvalBorder(), const OvalBorder().copyWith());
expect(const OvalBorder().hashCode, const OvalBorder().copyWith().hashCode);
const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456));
expect(const OvalBorder().copyWith(side: side), const OvalBorder(side: side));
});
test('OvalBorder', () {
const OvalBorder c10 = OvalBorder(side: BorderSide(width: 10.0));
const OvalBorder c15 = OvalBorder(side: BorderSide(width: 15.0));
const OvalBorder c20 = OvalBorder(side: BorderSide(width: 20.0));
expect(c10.dimensions, const EdgeInsets.all(10.0));
expect(c10.scale(2.0), c20);
expect(c20.scale(0.5), c10);
expect(ShapeBorder.lerp(c10, c20, 0.0), c10);
expect(ShapeBorder.lerp(c10, c20, 0.5), c15);
expect(ShapeBorder.lerp(c10, c20, 1.0), c20);
expect(
c10.getInnerPath(const Rect.fromLTWH(0, 0, 100, 40)),
isPathThat(
includes: const <Offset>[ Offset(12, 19), Offset(50, 10), Offset(88, 19), Offset(50, 29) ],
excludes: const <Offset>[ Offset(17, 26), Offset(15, 15), Offset(74, 10), Offset(76, 28) ],
),
);
expect(
c10.getOuterPath(const Rect.fromLTWH(0, 0, 100, 20)),
isPathThat(
includes: const <Offset>[ Offset(2, 9), Offset(50, 0), Offset(98, 9), Offset(50, 19) ],
excludes: const <Offset>[ Offset(7, 16), Offset(10, 2), Offset(84, 1), Offset(86, 18) ],
),
);
});
}
| flutter/packages/flutter/test/painting/oval_border_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/oval_border_test.dart",
"repo_id": "flutter",
"token_count": 740
} | 664 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/physics.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Clamped simulation 1', () {
final GravitySimulation gravity = GravitySimulation(9.81, 10.0, 0.0, 0.0);
final ClampedSimulation clamped = ClampedSimulation(gravity, xMin: 20.0, xMax: 100.0, dxMin: 7.0, dxMax: 11.0);
expect(clamped.x(0.0), equals(20.0));
expect(clamped.dx(0.0), equals(7.0));
expect(clamped.x(100.0), equals(100.0));
expect(clamped.dx(100.0), equals(11.0));
});
test('Clamped simulation 2', () {
final GravitySimulation gravity = GravitySimulation(-10, 0.0, 6.0, 10.0);
final ClampedSimulation clamped = ClampedSimulation(gravity, xMin: 0.0, xMax: 2.5, dxMin: -1.0, dxMax: 1.0);
expect(clamped.x(0.0), equals(0.0));
expect(clamped.dx(0.0), equals(1.0));
expect(clamped.isDone(0.0), isFalse);
expect(clamped.x(1.0), equals(2.5));
expect(clamped.dx(1.0), equals(0.0));
expect(clamped.isDone(0.2), isFalse);
expect(clamped.x(2.0), equals(0.0));
expect(clamped.dx(2.0), equals(-1.0));
expect(clamped.isDone(2.0), isFalse);
expect(clamped.x(3.0), equals(0.0));
expect(clamped.dx(3.0), equals(-1.0));
expect(clamped.isDone(3.0), isTrue);
});
}
| flutter/packages/flutter/test/physics/clamped_simulation_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/physics/clamped_simulation_test.dart",
"repo_id": "flutter",
"token_count": 591
} | 665 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
class RenderTestBox extends RenderBox {
late Size boxSize;
int calls = 0;
double value = 0.0;
double next() {
value += 1.0;
return value;
}
@override
double computeMinIntrinsicWidth(double height) => next();
@override
double computeMaxIntrinsicWidth(double height) => next();
@override
double computeMinIntrinsicHeight(double width) => next();
@override
double computeMaxIntrinsicHeight(double width) => next();
@override
void performLayout() {
size = constraints.biggest;
boxSize = size;
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
calls += 1;
return boxSize.height / 2.0;
}
}
class RenderDryBaselineTestBox extends RenderTestBox {
double? baselineOverride;
@override
double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) {
calls += 1;
return baselineOverride ?? constraints.biggest.height / 2.0;
}
}
class RenderBadDryBaselineTestBox extends RenderTestBox {
@override
double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) {
return size.height / 2.0;
}
}
class RenderCannotComputeDryBaselineTestBox extends RenderTestBox {
bool shouldAssert = true;
@override
double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) {
if (shouldAssert) {
assert(debugCannotComputeDryLayout(reason: 'no dry baseline for you'));
}
return null;
}
}
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('Intrinsics cache', () {
final RenderBox test = RenderTestBox();
expect(test.getMinIntrinsicWidth(0.0), equals(1.0));
expect(test.getMinIntrinsicWidth(100.0), equals(2.0));
expect(test.getMinIntrinsicWidth(200.0), equals(3.0));
expect(test.getMinIntrinsicWidth(0.0), equals(1.0));
expect(test.getMinIntrinsicWidth(100.0), equals(2.0));
expect(test.getMinIntrinsicWidth(200.0), equals(3.0));
expect(test.getMaxIntrinsicWidth(0.0), equals(4.0));
expect(test.getMaxIntrinsicWidth(100.0), equals(5.0));
expect(test.getMaxIntrinsicWidth(200.0), equals(6.0));
expect(test.getMaxIntrinsicWidth(0.0), equals(4.0));
expect(test.getMaxIntrinsicWidth(100.0), equals(5.0));
expect(test.getMaxIntrinsicWidth(200.0), equals(6.0));
expect(test.getMinIntrinsicHeight(0.0), equals(7.0));
expect(test.getMinIntrinsicHeight(100.0), equals(8.0));
expect(test.getMinIntrinsicHeight(200.0), equals(9.0));
expect(test.getMinIntrinsicHeight(0.0), equals(7.0));
expect(test.getMinIntrinsicHeight(100.0), equals(8.0));
expect(test.getMinIntrinsicHeight(200.0), equals(9.0));
expect(test.getMaxIntrinsicHeight(0.0), equals(10.0));
expect(test.getMaxIntrinsicHeight(100.0), equals(11.0));
expect(test.getMaxIntrinsicHeight(200.0), equals(12.0));
expect(test.getMaxIntrinsicHeight(0.0), equals(10.0));
expect(test.getMaxIntrinsicHeight(100.0), equals(11.0));
expect(test.getMaxIntrinsicHeight(200.0), equals(12.0));
// now read them all again backwards
expect(test.getMaxIntrinsicHeight(200.0), equals(12.0));
expect(test.getMaxIntrinsicHeight(100.0), equals(11.0));
expect(test.getMaxIntrinsicHeight(0.0), equals(10.0));
expect(test.getMinIntrinsicHeight(200.0), equals(9.0));
expect(test.getMinIntrinsicHeight(100.0), equals(8.0));
expect(test.getMinIntrinsicHeight(0.0), equals(7.0));
expect(test.getMaxIntrinsicWidth(200.0), equals(6.0));
expect(test.getMaxIntrinsicWidth(100.0), equals(5.0));
expect(test.getMaxIntrinsicWidth(0.0), equals(4.0));
expect(test.getMinIntrinsicWidth(200.0), equals(3.0));
expect(test.getMinIntrinsicWidth(100.0), equals(2.0));
expect(test.getMinIntrinsicWidth(0.0), equals(1.0));
});
// Regression test for https://github.com/flutter/flutter/issues/101179
test('Cached baselines should be cleared if its parent re-layout', () {
double viewHeight = 200.0;
final RenderTestBox test = RenderTestBox();
final RenderBox baseline = RenderBaseline(
baseline: 0.0,
baselineType: TextBaseline.alphabetic,
child: test,
);
final RenderConstrainedBox root = RenderConstrainedBox(
additionalConstraints: BoxConstraints.tightFor(width: 200.0, height: viewHeight),
child: baseline,
);
layout(RenderPositionedBox(
child: root,
));
BoxParentData? parentData = test.parentData as BoxParentData?;
expect(parentData!.offset.dy, -(viewHeight / 2.0));
expect(test.calls, 1);
// Trigger the root render re-layout.
viewHeight = 300.0;
root.additionalConstraints = BoxConstraints.tightFor(width: 200.0, height: viewHeight);
pumpFrame();
parentData = test.parentData as BoxParentData?;
expect(parentData!.offset.dy, -(viewHeight / 2.0));
expect(test.calls, 2); // The layout constraints change will clear the cached data.
final RenderObject parent = test.parent!;
expect(parent.debugNeedsLayout, false);
// Do not forget notify parent dirty after the cached data be cleared by `layout()`
test.markNeedsLayout();
expect(parent.debugNeedsLayout, true);
pumpFrame();
expect(parent.debugNeedsLayout, false);
expect(test.calls, 3); // Self dirty will clear the cached data.
parent.markNeedsLayout();
pumpFrame();
expect(test.calls, 3); // Use the cached data if the layout constraints do not change.
});
group('Dry baseline', () {
test('computeDryBaseline results are cached and shared with computeDistanceToActualBaseline', () {
const double viewHeight = 200.0;
const BoxConstraints constraints = BoxConstraints.tightFor(width: 200.0, height: viewHeight);
final RenderDryBaselineTestBox test = RenderDryBaselineTestBox();
final RenderBox baseline = RenderBaseline(
baseline: 0.0,
baselineType: TextBaseline.alphabetic,
child: test,
);
final RenderConstrainedBox root = RenderConstrainedBox(
additionalConstraints: constraints,
child: baseline,
);
layout(RenderPositionedBox(child: root));
expect(test.calls, 1);
// The baseline widget loosens the input constraints when passing on to child.
expect(test.getDryBaseline(constraints.loosen(), TextBaseline.alphabetic), test.boxSize.height / 2);
// There's cache for the constraints so this should be 1, but we always evaluate
// computeDryBaseline in debug mode in case it asserts even if the baseline
// cache hits.
expect(test.calls, 2);
const BoxConstraints newConstraints = BoxConstraints.tightFor(width: 10.0, height: 10.0);
expect(test.getDryBaseline(newConstraints.loosen(), TextBaseline.alphabetic), 5.0);
// Should be 3 but there's an additional computeDryBaseline call in getDryBaseline,
// in an assert.
expect(test.calls, 4);
root.additionalConstraints = newConstraints;
pumpFrame();
expect(test.calls, 4);
});
test('Asserts when a RenderBox cannot compute dry baseline', () {
final RenderCannotComputeDryBaselineTestBox test = RenderCannotComputeDryBaselineTestBox();
layout(RenderBaseline(baseline: 0.0, baselineType: TextBaseline.alphabetic, child: test));
final BoxConstraints incomingConstraints = test.constraints;
assert(incomingConstraints != const BoxConstraints());
expect(
() => test.getDryBaseline(const BoxConstraints(), TextBaseline.alphabetic),
throwsA(isA<AssertionError>().having((AssertionError e) => e.message, 'message', contains('no dry baseline for you'))),
);
// Still throws when there is cache.
expect(
() => test.getDryBaseline(incomingConstraints, TextBaseline.alphabetic),
throwsA(isA<AssertionError>().having((AssertionError e) => e.message, 'message', contains('no dry baseline for you'))),
);
});
test('Cactches inconsistencies between computeDryBaseline and computeDistanceToActualBaseline', () {
final RenderDryBaselineTestBox test = RenderDryBaselineTestBox();
layout(test, phase: EnginePhase.composite);
FlutterErrorDetails? error;
test.markNeedsLayout();
test.baselineOverride = 123;
pumpFrame(phase: EnginePhase.composite, onErrors: () {
error = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails();
});
expect(error?.exceptionAsString(), contains('differs from the baseline location computed by computeDryBaseline'));
});
test('Accessing RenderBox.size in computeDryBaseline is not allowed', () {
final RenderBadDryBaselineTestBox test = RenderBadDryBaselineTestBox();
FlutterErrorDetails? error;
layout(test, phase: EnginePhase.composite, onErrors: () {
error = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails();
});
expect(error?.exceptionAsString(), contains('RenderBox.size accessed in RenderBadDryBaselineTestBox.computeDryBaseline.'));
});
test('debug baseline checks do not freak out when debugCannotComputeDryLayout is called', () {
FlutterErrorDetails? error;
void onErrors() {
error = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails();
}
final RenderCannotComputeDryBaselineTestBox test = RenderCannotComputeDryBaselineTestBox();
layout(test, phase: EnginePhase.composite, onErrors: onErrors);
expect(error, isNull);
test.shouldAssert = false;
test.markNeedsLayout();
pumpFrame(phase: EnginePhase.composite, onErrors: onErrors);
expect(error?.exceptionAsString(), contains('differs from the baseline location computed by computeDryBaseline'));
});
});
}
| flutter/packages/flutter/test/rendering/cached_intrinsics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/cached_intrinsics_test.dart",
"repo_id": "flutter",
"token_count": 3667
} | 666 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('non-painted layers are detached', () {
RenderObject boundary, inner;
final RenderOpacity root = RenderOpacity(
child: boundary = RenderRepaintBoundary(
child: inner = RenderDecoratedBox(
decoration: const BoxDecoration(),
),
),
);
layout(root, phase: EnginePhase.paint);
expect(inner.isRepaintBoundary, isFalse);
expect(inner.debugLayer, null);
expect(boundary.isRepaintBoundary, isTrue);
expect(boundary.debugLayer, isNotNull);
expect(boundary.debugLayer!.attached, isTrue); // this time it painted...
root.opacity = 0.0;
pumpFrame(phase: EnginePhase.paint);
expect(inner.isRepaintBoundary, isFalse);
expect(inner.debugLayer, null);
expect(boundary.isRepaintBoundary, isTrue);
expect(boundary.debugLayer, isNotNull);
expect(boundary.debugLayer!.attached, isFalse); // this time it did not.
root.opacity = 0.5;
pumpFrame(phase: EnginePhase.paint);
expect(inner.isRepaintBoundary, isFalse);
expect(inner.debugLayer, null);
expect(boundary.isRepaintBoundary, isTrue);
expect(boundary.debugLayer, isNotNull);
expect(boundary.debugLayer!.attached, isTrue); // this time it did again!
});
test('updateSubtreeNeedsAddToScene propagates Layer.alwaysNeedsAddToScene up the tree', () {
final ContainerLayer a = ContainerLayer();
final ContainerLayer b = ContainerLayer();
final ContainerLayer c = ContainerLayer();
final _TestAlwaysNeedsAddToSceneLayer d = _TestAlwaysNeedsAddToSceneLayer();
final ContainerLayer e = ContainerLayer();
final ContainerLayer f = ContainerLayer();
// Tree structure:
// a
// / \
// b c
// / \
// (x)d e
// /
// f
a.append(b);
a.append(c);
b.append(d);
b.append(e);
d.append(f);
a.debugMarkClean();
b.debugMarkClean();
c.debugMarkClean();
d.debugMarkClean();
e.debugMarkClean();
f.debugMarkClean();
expect(a.debugSubtreeNeedsAddToScene, false);
expect(b.debugSubtreeNeedsAddToScene, false);
expect(c.debugSubtreeNeedsAddToScene, false);
expect(d.debugSubtreeNeedsAddToScene, false);
expect(e.debugSubtreeNeedsAddToScene, false);
expect(f.debugSubtreeNeedsAddToScene, false);
a.updateSubtreeNeedsAddToScene();
expect(a.debugSubtreeNeedsAddToScene, true);
expect(b.debugSubtreeNeedsAddToScene, true);
expect(c.debugSubtreeNeedsAddToScene, false);
expect(d.debugSubtreeNeedsAddToScene, true);
expect(e.debugSubtreeNeedsAddToScene, false);
expect(f.debugSubtreeNeedsAddToScene, false);
});
test('updateSubtreeNeedsAddToScene propagates Layer._needsAddToScene up the tree', () {
final ContainerLayer a = ContainerLayer();
final ContainerLayer b = ContainerLayer();
final ContainerLayer c = ContainerLayer();
final ContainerLayer d = ContainerLayer();
final ContainerLayer e = ContainerLayer();
final ContainerLayer f = ContainerLayer();
final ContainerLayer g = ContainerLayer();
final List<ContainerLayer> allLayers = <ContainerLayer>[a, b, c, d, e, f, g];
// The tree is like the following where b and j are dirty:
// a____
// / \
// (x)b___ c
// / \ \ |
// d e f g(x)
a.append(b);
a.append(c);
b.append(d);
b.append(e);
b.append(f);
c.append(g);
for (final ContainerLayer layer in allLayers) {
expect(layer.debugSubtreeNeedsAddToScene, true);
}
for (final ContainerLayer layer in allLayers) {
layer.debugMarkClean();
}
for (final ContainerLayer layer in allLayers) {
expect(layer.debugSubtreeNeedsAddToScene, false);
}
b.markNeedsAddToScene();
a.updateSubtreeNeedsAddToScene();
expect(a.debugSubtreeNeedsAddToScene, true);
expect(b.debugSubtreeNeedsAddToScene, true);
expect(c.debugSubtreeNeedsAddToScene, false);
expect(d.debugSubtreeNeedsAddToScene, false);
expect(e.debugSubtreeNeedsAddToScene, false);
expect(f.debugSubtreeNeedsAddToScene, false);
expect(g.debugSubtreeNeedsAddToScene, false);
g.markNeedsAddToScene();
a.updateSubtreeNeedsAddToScene();
expect(a.debugSubtreeNeedsAddToScene, true);
expect(b.debugSubtreeNeedsAddToScene, true);
expect(c.debugSubtreeNeedsAddToScene, true);
expect(d.debugSubtreeNeedsAddToScene, false);
expect(e.debugSubtreeNeedsAddToScene, false);
expect(f.debugSubtreeNeedsAddToScene, false);
expect(g.debugSubtreeNeedsAddToScene, true);
a.buildScene(SceneBuilder());
for (final ContainerLayer layer in allLayers) {
expect(layer.debugSubtreeNeedsAddToScene, false);
}
});
test('follower layers are always dirty', () {
final LayerLink link = LayerLink();
final LeaderLayer leaderLayer = LeaderLayer(link: link);
final FollowerLayer followerLayer = FollowerLayer(link: link);
leaderLayer.debugMarkClean();
followerLayer.debugMarkClean();
leaderLayer.updateSubtreeNeedsAddToScene();
followerLayer.updateSubtreeNeedsAddToScene();
expect(followerLayer.debugSubtreeNeedsAddToScene, true);
});
test('switching layer link of an attached leader layer should not crash', () {
final LayerLink link = LayerLink();
final LeaderLayer leaderLayer = LeaderLayer(link: link);
final FlutterView flutterView = RendererBinding.instance.platformDispatcher.views.single;
final RenderView view = RenderView(configuration: ViewConfiguration.fromView(flutterView), view: flutterView);
leaderLayer.attach(view);
final LayerLink link2 = LayerLink();
leaderLayer.link = link2;
// This should not crash.
leaderLayer.detach();
expect(leaderLayer.link, link2);
});
test('layer link attach/detach order should not crash app.', () {
final LayerLink link = LayerLink();
final LeaderLayer leaderLayer1 = LeaderLayer(link: link);
final LeaderLayer leaderLayer2 = LeaderLayer(link: link);
final FlutterView flutterView = RendererBinding.instance.platformDispatcher.views.single;
final RenderView view = RenderView(configuration: ViewConfiguration.fromView(flutterView), view: flutterView);
leaderLayer1.attach(view);
leaderLayer2.attach(view);
leaderLayer2.detach();
leaderLayer1.detach();
expect(link.leader, isNull);
});
test('leader layers not dirty when connected to follower layer', () {
final ContainerLayer root = ContainerLayer()..attach(Object());
final LayerLink link = LayerLink();
final LeaderLayer leaderLayer = LeaderLayer(link: link);
final FollowerLayer followerLayer = FollowerLayer(link: link);
root.append(leaderLayer);
root.append(followerLayer);
leaderLayer.debugMarkClean();
followerLayer.debugMarkClean();
leaderLayer.updateSubtreeNeedsAddToScene();
followerLayer.updateSubtreeNeedsAddToScene();
expect(leaderLayer.debugSubtreeNeedsAddToScene, false);
});
test('leader layers are not dirty when all followers disconnects', () {
final ContainerLayer root = ContainerLayer()..attach(Object());
final LayerLink link = LayerLink();
final LeaderLayer leaderLayer = LeaderLayer(link: link);
root.append(leaderLayer);
// Does not need add to scene when nothing is connected to link.
leaderLayer.debugMarkClean();
leaderLayer.updateSubtreeNeedsAddToScene();
expect(leaderLayer.debugSubtreeNeedsAddToScene, false);
// Connecting a follower does not require adding to scene
final FollowerLayer follower1 = FollowerLayer(link: link);
root.append(follower1);
leaderLayer.debugMarkClean();
leaderLayer.updateSubtreeNeedsAddToScene();
expect(leaderLayer.debugSubtreeNeedsAddToScene, false);
final FollowerLayer follower2 = FollowerLayer(link: link);
root.append(follower2);
leaderLayer.debugMarkClean();
leaderLayer.updateSubtreeNeedsAddToScene();
expect(leaderLayer.debugSubtreeNeedsAddToScene, false);
// Disconnecting one follower, still does not needs add to scene.
follower2.remove();
leaderLayer.debugMarkClean();
leaderLayer.updateSubtreeNeedsAddToScene();
expect(leaderLayer.debugSubtreeNeedsAddToScene, false);
// Disconnecting all followers goes back to not requiring add to scene.
follower1.remove();
leaderLayer.debugMarkClean();
leaderLayer.updateSubtreeNeedsAddToScene();
expect(leaderLayer.debugSubtreeNeedsAddToScene, false);
});
test('LeaderLayer.applyTransform can be called after retained rendering', () {
void expectTransform(RenderObject leader) {
final LeaderLayer leaderLayer = leader.debugLayer! as LeaderLayer;
final Matrix4 expected = Matrix4.identity()
..translate(leaderLayer.offset.dx, leaderLayer.offset.dy);
final Matrix4 transformed = Matrix4.identity();
leaderLayer.applyTransform(null, transformed);
expect(transformed, expected);
}
final LayerLink link = LayerLink();
late RenderLeaderLayer leader;
final RenderRepaintBoundary root = RenderRepaintBoundary(
child:RenderRepaintBoundary(
child: leader = RenderLeaderLayer(link: link),
),
);
layout(root, phase: EnginePhase.composite);
expectTransform(leader);
// Causes a repaint, but the LeaderLayer of RenderLeaderLayer will be added
// as retained and LeaderLayer.addChildrenToScene will not be called.
root.markNeedsPaint();
pumpFrame(phase: EnginePhase.composite);
// The LeaderLayer.applyTransform call shouldn't crash.
expectTransform(leader);
});
test('depthFirstIterateChildren', () {
final ContainerLayer a = ContainerLayer();
final ContainerLayer b = ContainerLayer();
final ContainerLayer c = ContainerLayer();
final ContainerLayer d = ContainerLayer();
final ContainerLayer e = ContainerLayer();
final ContainerLayer f = ContainerLayer();
final ContainerLayer g = ContainerLayer();
final PictureLayer h = PictureLayer(Rect.zero);
final PictureLayer i = PictureLayer(Rect.zero);
final PictureLayer j = PictureLayer(Rect.zero);
// The tree is like the following:
// a____
// / \
// b___ c
// / \ \ |
// d e f g
// / \ |
// h i j
a.append(b);
a.append(c);
b.append(d);
b.append(e);
b.append(f);
d.append(h);
d.append(i);
c.append(g);
g.append(j);
expect(
a.depthFirstIterateChildren(),
<Layer>[b, d, h, i, e, f, c, g, j],
);
d.remove();
// a____
// / \
// b___ c
// \ \ |
// e f g
// |
// j
expect(
a.depthFirstIterateChildren(),
<Layer>[b, e, f, c, g, j],
);
});
void checkNeedsAddToScene(Layer layer, void Function() mutateCallback) {
layer.debugMarkClean();
layer.updateSubtreeNeedsAddToScene();
expect(layer.debugSubtreeNeedsAddToScene, false);
mutateCallback();
layer.updateSubtreeNeedsAddToScene();
expect(layer.debugSubtreeNeedsAddToScene, true);
}
List<String> getDebugInfo(Layer layer) {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
layer.debugFillProperties(builder);
return builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
}
test('ClipRectLayer prints clipBehavior in debug info', () {
expect(getDebugInfo(ClipRectLayer()), contains('clipBehavior: Clip.hardEdge'));
expect(
getDebugInfo(ClipRectLayer(clipBehavior: Clip.antiAliasWithSaveLayer)),
contains('clipBehavior: Clip.antiAliasWithSaveLayer'),
);
});
test('ClipRRectLayer prints clipBehavior in debug info', () {
expect(getDebugInfo(ClipRRectLayer()), contains('clipBehavior: Clip.antiAlias'));
expect(
getDebugInfo(ClipRRectLayer(clipBehavior: Clip.antiAliasWithSaveLayer)),
contains('clipBehavior: Clip.antiAliasWithSaveLayer'),
);
});
test('ClipPathLayer prints clipBehavior in debug info', () {
expect(getDebugInfo(ClipPathLayer()), contains('clipBehavior: Clip.antiAlias'));
expect(
getDebugInfo(ClipPathLayer(clipBehavior: Clip.antiAliasWithSaveLayer)),
contains('clipBehavior: Clip.antiAliasWithSaveLayer'),
);
});
test('BackdropFilterLayer prints filter and blendMode in debug info', () {
final ImageFilter filter = ImageFilter.blur(sigmaX: 1.0, sigmaY: 1.0, tileMode: TileMode.repeated);
final BackdropFilterLayer layer = BackdropFilterLayer(filter: filter, blendMode: BlendMode.clear);
final List<String> info = getDebugInfo(layer);
expect(
info,
contains('filter: ImageFilter.blur(${1.0}, ${1.0}, repeated)'),
);
expect(info, contains('blendMode: clear'));
});
test('PictureLayer prints picture, raster cache hints in debug info', () {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPaint(Paint());
final Picture picture = recorder.endRecording();
final PictureLayer layer = PictureLayer(const Rect.fromLTRB(0, 0, 1, 1));
layer.picture = picture;
layer.isComplexHint = true;
layer.willChangeHint = false;
final List<String> info = getDebugInfo(layer);
expect(info, contains('picture: ${describeIdentity(picture)}'));
expect(info, isNot(contains('engine layer: ${describeIdentity(null)}')));
expect(info, contains('raster cache hints: isComplex = true, willChange = false'));
});
test('Layer prints engineLayer if it is not null in debug info', () {
final ConcreteLayer layer = ConcreteLayer();
List<String> info = getDebugInfo(layer);
expect(info, isNot(contains('engine layer: ${describeIdentity(null)}')));
layer.engineLayer = FakeEngineLayer();
info = getDebugInfo(layer);
expect(info, contains('engine layer: ${describeIdentity(layer.engineLayer)}'));
});
test('mutating PictureLayer fields triggers needsAddToScene', () {
final PictureLayer pictureLayer = PictureLayer(Rect.zero);
checkNeedsAddToScene(pictureLayer, () {
final PictureRecorder recorder = PictureRecorder();
Canvas(recorder);
pictureLayer.picture = recorder.endRecording();
});
pictureLayer.isComplexHint = false;
checkNeedsAddToScene(pictureLayer, () {
pictureLayer.isComplexHint = true;
});
pictureLayer.willChangeHint = false;
checkNeedsAddToScene(pictureLayer, () {
pictureLayer.willChangeHint = true;
});
});
const Rect unitRect = Rect.fromLTRB(0, 0, 1, 1);
test('mutating PerformanceOverlayLayer fields triggers needsAddToScene', () {
final PerformanceOverlayLayer layer = PerformanceOverlayLayer(
overlayRect: Rect.zero,
optionsMask: 0,
rasterizerThreshold: 0,
checkerboardRasterCacheImages: false,
checkerboardOffscreenLayers: false,
);
checkNeedsAddToScene(layer, () {
layer.overlayRect = unitRect;
});
});
test('mutating OffsetLayer fields triggers needsAddToScene', () {
final OffsetLayer layer = OffsetLayer();
checkNeedsAddToScene(layer, () {
layer.offset = const Offset(1, 1);
});
});
test('mutating ClipRectLayer fields triggers needsAddToScene', () {
final ClipRectLayer layer = ClipRectLayer(clipRect: Rect.zero);
checkNeedsAddToScene(layer, () {
layer.clipRect = unitRect;
});
checkNeedsAddToScene(layer, () {
layer.clipBehavior = Clip.antiAliasWithSaveLayer;
});
});
test('mutating ClipRRectLayer fields triggers needsAddToScene', () {
final ClipRRectLayer layer = ClipRRectLayer(clipRRect: RRect.zero);
checkNeedsAddToScene(layer, () {
layer.clipRRect = RRect.fromRectAndRadius(unitRect, Radius.zero);
});
checkNeedsAddToScene(layer, () {
layer.clipBehavior = Clip.antiAliasWithSaveLayer;
});
});
test('mutating ClipPath fields triggers needsAddToScene', () {
final ClipPathLayer layer = ClipPathLayer(clipPath: Path());
checkNeedsAddToScene(layer, () {
final Path newPath = Path();
newPath.addRect(unitRect);
layer.clipPath = newPath;
});
checkNeedsAddToScene(layer, () {
layer.clipBehavior = Clip.antiAliasWithSaveLayer;
});
});
test('mutating OpacityLayer fields triggers needsAddToScene', () {
final OpacityLayer layer = OpacityLayer(alpha: 0);
checkNeedsAddToScene(layer, () {
layer.alpha = 1;
});
checkNeedsAddToScene(layer, () {
layer.offset = const Offset(1, 1);
});
});
test('mutating ColorFilterLayer fields triggers needsAddToScene', () {
final ColorFilterLayer layer = ColorFilterLayer(
colorFilter: const ColorFilter.mode(Color(0xFFFF0000), BlendMode.color),
);
checkNeedsAddToScene(layer, () {
layer.colorFilter = const ColorFilter.mode(Color(0xFF00FF00), BlendMode.color);
});
});
test('mutating ShaderMaskLayer fields triggers needsAddToScene', () {
const Gradient gradient = RadialGradient(colors: <Color>[Color(0x00000000), Color(0x00000001)]);
final Shader shader = gradient.createShader(Rect.zero);
final ShaderMaskLayer layer = ShaderMaskLayer(shader: shader, maskRect: Rect.zero, blendMode: BlendMode.clear);
checkNeedsAddToScene(layer, () {
layer.maskRect = unitRect;
});
checkNeedsAddToScene(layer, () {
layer.blendMode = BlendMode.color;
});
checkNeedsAddToScene(layer, () {
layer.shader = gradient.createShader(unitRect);
});
});
test('mutating BackdropFilterLayer fields triggers needsAddToScene', () {
final BackdropFilterLayer layer = BackdropFilterLayer(filter: ImageFilter.blur());
checkNeedsAddToScene(layer, () {
layer.filter = ImageFilter.blur(sigmaX: 1.0);
});
});
test('ContainerLayer.toImage can render interior layer', () {
final OffsetLayer parent = OffsetLayer();
final OffsetLayer child = OffsetLayer();
final OffsetLayer grandChild = OffsetLayer();
child.append(grandChild);
parent.append(child);
// This renders the layers and generates engine layers.
parent.buildScene(SceneBuilder());
// Causes grandChild to pass its engine layer as `oldLayer`
grandChild.toImage(const Rect.fromLTRB(0, 0, 10, 10));
// Ensure we can render the same scene again after rendering an interior
// layer.
parent.buildScene(SceneBuilder());
}, skip: isBrowser && !isCanvasKit); // TODO(yjbanov): `toImage` doesn't work in HTML: https://github.com/flutter/flutter/issues/49857
test('ContainerLayer.toImageSync can render interior layer', () {
final OffsetLayer parent = OffsetLayer();
final OffsetLayer child = OffsetLayer();
final OffsetLayer grandChild = OffsetLayer();
child.append(grandChild);
parent.append(child);
// This renders the layers and generates engine layers.
parent.buildScene(SceneBuilder());
// Causes grandChild to pass its engine layer as `oldLayer`
grandChild.toImageSync(const Rect.fromLTRB(0, 0, 10, 10));
// Ensure we can render the same scene again after rendering an interior
// layer.
parent.buildScene(SceneBuilder());
}, skip: isBrowser && !isCanvasKit); // TODO(yjbanov): `toImage` doesn't work in HTML: https://github.com/flutter/flutter/issues/49857
test('PictureLayer does not let you call dispose unless refcount is 0', () {
PictureLayer layer = PictureLayer(Rect.zero);
expect(layer.debugHandleCount, 0);
layer.dispose();
expect(layer.debugDisposed, true);
layer = PictureLayer(Rect.zero);
final LayerHandle<PictureLayer> handle = LayerHandle<PictureLayer>(layer);
expect(layer.debugHandleCount, 1);
expect(() => layer.dispose(), throwsAssertionError);
handle.layer = null;
expect(layer.debugHandleCount, 0);
expect(layer.debugDisposed, true);
expect(() => layer.dispose(), throwsAssertionError); // already disposed.
});
test('Layer append/remove increases/decreases handle count', () {
final PictureLayer layer = PictureLayer(Rect.zero);
final ContainerLayer parent = ContainerLayer();
expect(layer.debugHandleCount, 0);
expect(layer.debugDisposed, false);
parent.append(layer);
expect(layer.debugHandleCount, 1);
expect(layer.debugDisposed, false);
layer.remove();
expect(layer.debugHandleCount, 0);
expect(layer.debugDisposed, true);
});
test('Layer.dispose disposes the engineLayer', () {
final Layer layer = ConcreteLayer();
final FakeEngineLayer engineLayer = FakeEngineLayer();
layer.engineLayer = engineLayer;
expect(engineLayer.disposed, false);
layer.dispose();
expect(engineLayer.disposed, true);
expect(layer.engineLayer, null);
});
test('Layer.engineLayer (set) disposes the engineLayer', () {
final Layer layer = ConcreteLayer();
final FakeEngineLayer engineLayer = FakeEngineLayer();
layer.engineLayer = engineLayer;
expect(engineLayer.disposed, false);
layer.engineLayer = null;
expect(engineLayer.disposed, true);
});
test('PictureLayer.picture (set) disposes the picture', () {
final PictureLayer layer = PictureLayer(Rect.zero);
final FakePicture picture = FakePicture();
layer.picture = picture;
expect(picture.disposed, false);
layer.picture = null;
expect(picture.disposed, true);
});
test('PictureLayer disposes the picture', () {
final PictureLayer layer = PictureLayer(Rect.zero);
final FakePicture picture = FakePicture();
layer.picture = picture;
expect(picture.disposed, false);
layer.dispose();
expect(picture.disposed, true);
});
test('LayerHandle disposes the layer', () {
final ConcreteLayer layer = ConcreteLayer();
final ConcreteLayer layer2 = ConcreteLayer();
expect(layer.debugHandleCount, 0);
expect(layer2.debugHandleCount, 0);
final LayerHandle<ConcreteLayer> holder = LayerHandle<ConcreteLayer>(layer);
expect(layer.debugHandleCount, 1);
expect(layer.debugDisposed, false);
expect(layer2.debugHandleCount, 0);
expect(layer2.debugDisposed, false);
holder.layer = layer;
expect(layer.debugHandleCount, 1);
expect(layer.debugDisposed, false);
expect(layer2.debugHandleCount, 0);
expect(layer2.debugDisposed, false);
holder.layer = layer2;
expect(layer.debugHandleCount, 0);
expect(layer.debugDisposed, true);
expect(layer2.debugHandleCount, 1);
expect(layer2.debugDisposed, false);
holder.layer = null;
expect(layer.debugHandleCount, 0);
expect(layer.debugDisposed, true);
expect(layer2.debugHandleCount, 0);
expect(layer2.debugDisposed, true);
expect(() => holder.layer = layer, throwsAssertionError);
});
test('OpacityLayer does not push an OffsetLayer if there are no children', () {
final OpacityLayer layer = OpacityLayer(alpha: 128);
final FakeSceneBuilder builder = FakeSceneBuilder();
layer.addToScene(builder);
expect(builder.pushedOpacity, false);
expect(builder.pushedOffset, false);
expect(builder.addedPicture, false);
expect(layer.engineLayer, null);
layer.append(PictureLayer(Rect.largest)..picture = FakePicture());
builder.reset();
layer.addToScene(builder);
expect(builder.pushedOpacity, true);
expect(builder.pushedOffset, false);
expect(builder.addedPicture, true);
expect(layer.engineLayer, isA<FakeOpacityEngineLayer>());
builder.reset();
layer.alpha = 200;
expect(layer.engineLayer, isA<FakeOpacityEngineLayer>());
layer.alpha = 255;
expect(layer.engineLayer, null);
builder.reset();
layer.addToScene(builder);
expect(builder.pushedOpacity, false);
expect(builder.pushedOffset, true);
expect(builder.addedPicture, true);
expect(layer.engineLayer, isA<FakeOffsetEngineLayer>());
layer.alpha = 200;
expect(layer.engineLayer, null);
builder.reset();
layer.addToScene(builder);
expect(builder.pushedOpacity, true);
expect(builder.pushedOffset, false);
expect(builder.addedPicture, true);
expect(layer.engineLayer, isA<FakeOpacityEngineLayer>());
});
test('OpacityLayer dispose its engineLayer if there are no children', () {
final OpacityLayer layer = OpacityLayer(alpha: 128);
final FakeSceneBuilder builder = FakeSceneBuilder();
layer.addToScene(builder);
expect(layer.engineLayer, null);
layer.append(PictureLayer(Rect.largest)..picture = FakePicture());
layer.addToScene(builder);
expect(layer.engineLayer, isA<FakeOpacityEngineLayer>());
layer.removeAllChildren();
layer.addToScene(builder);
expect(layer.engineLayer, null);
});
test('Layers describe clip bounds', () {
ContainerLayer layer = ContainerLayer();
expect(layer.describeClipBounds(), null);
const Rect bounds = Rect.fromLTRB(10, 10, 20, 20);
final RRect rbounds = RRect.fromRectXY(bounds, 2, 2);
layer = ClipRectLayer(clipRect: bounds);
expect(layer.describeClipBounds(), bounds);
layer = ClipRRectLayer(clipRRect: rbounds);
expect(layer.describeClipBounds(), rbounds.outerRect);
layer = ClipPathLayer(clipPath: Path()..addRect(bounds));
expect(layer.describeClipBounds(), bounds);
});
test('Subtree has composition callbacks', () {
final ContainerLayer root = ContainerLayer();
expect(root.subtreeHasCompositionCallbacks, false);
final List<VoidCallback> cancellationCallbacks = <VoidCallback>[];
cancellationCallbacks.add(root.addCompositionCallback((_) {}));
expect(root.subtreeHasCompositionCallbacks, true);
final ContainerLayer a1 = ContainerLayer();
final ContainerLayer a2 = ContainerLayer();
final ContainerLayer b1 = ContainerLayer();
root.append(a1);
root.append(a2);
a1.append(b1);
expect(root.subtreeHasCompositionCallbacks, true);
expect(a1.subtreeHasCompositionCallbacks, false);
expect(a2.subtreeHasCompositionCallbacks, false);
expect(b1.subtreeHasCompositionCallbacks, false);
cancellationCallbacks.add(b1.addCompositionCallback((_) {}));
expect(root.subtreeHasCompositionCallbacks, true);
expect(a1.subtreeHasCompositionCallbacks, true);
expect(a2.subtreeHasCompositionCallbacks, false);
expect(b1.subtreeHasCompositionCallbacks, true);
cancellationCallbacks.removeAt(0)();
expect(root.subtreeHasCompositionCallbacks, true);
expect(a1.subtreeHasCompositionCallbacks, true);
expect(a2.subtreeHasCompositionCallbacks, false);
expect(b1.subtreeHasCompositionCallbacks, true);
cancellationCallbacks.removeAt(0)();
expect(root.subtreeHasCompositionCallbacks, false);
expect(a1.subtreeHasCompositionCallbacks, false);
expect(a2.subtreeHasCompositionCallbacks, false);
expect(b1.subtreeHasCompositionCallbacks, false);
});
test('Subtree has composition callbacks - removeChild', () {
final ContainerLayer root = ContainerLayer();
expect(root.subtreeHasCompositionCallbacks, false);
final ContainerLayer a1 = ContainerLayer();
final ContainerLayer a2 = ContainerLayer();
final ContainerLayer b1 = ContainerLayer();
root.append(a1);
root.append(a2);
a1.append(b1);
expect(b1.subtreeHasCompositionCallbacks, false);
expect(a1.subtreeHasCompositionCallbacks, false);
expect(root.subtreeHasCompositionCallbacks, false);
expect(a2.subtreeHasCompositionCallbacks, false);
b1.addCompositionCallback((_) { });
expect(b1.subtreeHasCompositionCallbacks, true);
expect(a1.subtreeHasCompositionCallbacks, true);
expect(root.subtreeHasCompositionCallbacks, true);
expect(a2.subtreeHasCompositionCallbacks, false);
b1.remove();
expect(b1.subtreeHasCompositionCallbacks, true);
expect(a1.subtreeHasCompositionCallbacks, false);
expect(root.subtreeHasCompositionCallbacks, false);
expect(a2.subtreeHasCompositionCallbacks, false);
});
test('No callback if removed', () {
final ContainerLayer root = ContainerLayer();
final ContainerLayer a1 = ContainerLayer();
final ContainerLayer a2 = ContainerLayer();
final ContainerLayer b1 = ContainerLayer();
root.append(a1);
root.append(a2);
a1.append(b1);
// Add and immediately remove the callback.
b1.addCompositionCallback((Layer layer) {
fail('Should not have called back');
})();
root.buildScene(SceneBuilder()).dispose();
});
test('Observe layer tree composition - not retained', () {
final ContainerLayer root = ContainerLayer();
final ContainerLayer a1 = ContainerLayer();
final ContainerLayer a2 = ContainerLayer();
final ContainerLayer b1 = ContainerLayer();
root.append(a1);
root.append(a2);
a1.append(b1);
bool compositedB1 = false;
b1.addCompositionCallback((Layer layer) {
expect(layer, b1);
compositedB1 = true;
});
expect(compositedB1, false);
root.buildScene(SceneBuilder()).dispose();
expect(compositedB1, true);
});
test('Observe layer tree composition - retained', () {
final ContainerLayer root = ContainerLayer();
final ContainerLayer a1 = ContainerLayer();
final ContainerLayer a2 = ContainerLayer();
final ContainerLayer b1 = ContainerLayer();
root.append(a1);
root.append(a2);
a1.append(b1);
// Actually build the retained layer so that the engine sees it as real and
// reusable.
SceneBuilder builder = SceneBuilder();
b1.engineLayer = builder.pushOffset(0, 0);
builder.build().dispose();
builder = SceneBuilder();
// Force the layer to appear clean and have an engine layer for retained
// rendering.
expect(b1.engineLayer, isNotNull);
b1.debugMarkClean();
expect(b1.debugSubtreeNeedsAddToScene, false);
bool compositedB1 = false;
b1.addCompositionCallback((Layer layer) {
expect(layer, b1);
compositedB1 = true;
});
expect(compositedB1, false);
root.buildScene(builder).dispose();
expect(compositedB1, true);
});
test('Observe layer tree composition - asserts on mutation', () {
final ContainerLayer root = ContainerLayer();
final ContainerLayer a1 = ContainerLayer();
final ContainerLayer a2 = ContainerLayer();
final ContainerLayer b1 = ContainerLayer();
root.append(a1);
root.append(a2);
a1.append(b1);
bool compositedB1 = false;
b1.addCompositionCallback((Layer layer) {
expect(layer, b1);
expect(() => layer.remove(), throwsAssertionError);
expect(() => layer.dispose(), throwsAssertionError);
expect(() => layer.markNeedsAddToScene(), throwsAssertionError);
expect(() => layer.debugMarkClean(), throwsAssertionError);
expect(() => layer.updateSubtreeNeedsAddToScene(), throwsAssertionError);
expect(() => layer.remove(), throwsAssertionError);
expect(() => (layer as ContainerLayer).append(ContainerLayer()), throwsAssertionError);
expect(() => layer.engineLayer = null, throwsAssertionError);
compositedB1 = true;
});
expect(compositedB1, false);
root.buildScene(SceneBuilder()).dispose();
expect(compositedB1, true);
});
test('Observe layer tree composition - detach triggers callback', () {
final ContainerLayer root = ContainerLayer();
final ContainerLayer a1 = ContainerLayer();
final ContainerLayer a2 = ContainerLayer();
final ContainerLayer b1 = ContainerLayer();
root.append(a1);
root.append(a2);
a1.append(b1);
bool compositedB1 = false;
b1.addCompositionCallback((Layer layer) {
expect(layer, b1);
compositedB1 = true;
});
root.attach(Object());
expect(compositedB1, false);
root.detach();
expect(compositedB1, true);
});
test('Observe layer tree composition - observer count correctly maintained', () {
final ContainerLayer root = ContainerLayer();
final ContainerLayer a1 = ContainerLayer();
root.append(a1);
expect(root.subtreeHasCompositionCallbacks, false);
expect(a1.subtreeHasCompositionCallbacks, false);
final VoidCallback remover1 = a1.addCompositionCallback((_) { });
final VoidCallback remover2 = a1.addCompositionCallback((_) { });
expect(root.subtreeHasCompositionCallbacks, true);
expect(a1.subtreeHasCompositionCallbacks, true);
remover1();
expect(root.subtreeHasCompositionCallbacks, true);
expect(a1.subtreeHasCompositionCallbacks, true);
remover2();
expect(root.subtreeHasCompositionCallbacks, false);
expect(a1.subtreeHasCompositionCallbacks, false);
});
test('Double removing a observe callback throws', () {
final ContainerLayer root = ContainerLayer();
final VoidCallback callback = root.addCompositionCallback((_) { });
callback();
expect(() => callback(), throwsAssertionError);
});
test('Removing an observe callback on a disposed layer does not throw', () {
final ContainerLayer root = ContainerLayer();
final VoidCallback callback = root.addCompositionCallback((_) { });
root.dispose();
expect(() => callback(), returnsNormally);
});
test('Layer types that support rasterization', () {
// Supported.
final OffsetLayer offsetLayer = OffsetLayer();
final OpacityLayer opacityLayer = OpacityLayer();
final ClipRectLayer clipRectLayer = ClipRectLayer();
final ClipRRectLayer clipRRectLayer = ClipRRectLayer();
final ImageFilterLayer imageFilterLayer = ImageFilterLayer();
final BackdropFilterLayer backdropFilterLayer = BackdropFilterLayer();
final ColorFilterLayer colorFilterLayer = ColorFilterLayer();
final ShaderMaskLayer shaderMaskLayer = ShaderMaskLayer();
final TextureLayer textureLayer = TextureLayer(rect: Rect.zero, textureId: 1);
expect(offsetLayer.supportsRasterization(), true);
expect(opacityLayer.supportsRasterization(), true);
expect(clipRectLayer.supportsRasterization(), true);
expect(clipRRectLayer.supportsRasterization(), true);
expect(imageFilterLayer.supportsRasterization(), true);
expect(backdropFilterLayer.supportsRasterization(), true);
expect(colorFilterLayer.supportsRasterization(), true);
expect(shaderMaskLayer.supportsRasterization(), true);
expect(textureLayer.supportsRasterization(), true);
// Unsupported.
final PlatformViewLayer platformViewLayer = PlatformViewLayer(rect: Rect.zero, viewId: 1);
expect(platformViewLayer.supportsRasterization(), false);
});
}
class FakeEngineLayer extends Fake implements EngineLayer {
bool disposed = false;
@override
void dispose() {
assert(!disposed);
disposed = true;
}
}
class FakePicture extends Fake implements Picture {
bool disposed = false;
@override
void dispose() {
assert(!disposed);
disposed = true;
}
}
class ConcreteLayer extends Layer {
@override
void addToScene(SceneBuilder builder) {}
}
class _TestAlwaysNeedsAddToSceneLayer extends ContainerLayer {
@override
bool get alwaysNeedsAddToScene => true;
}
class FakeSceneBuilder extends Fake implements SceneBuilder {
void reset() {
pushedOpacity = false;
pushedOffset = false;
addedPicture = false;
}
bool pushedOpacity = false;
bool pushedOffset = false;
bool addedPicture = false;
@override
dynamic noSuchMethod(Invocation invocation) {
// Use noSuchMethod forwarding instead of override these methods to make it easier
// for these methods to add new optional arguments in the future.
switch (invocation.memberName) {
case #pushOpacity:
pushedOpacity = true;
return FakeOpacityEngineLayer();
case #pushOffset:
pushedOffset = true;
return FakeOffsetEngineLayer();
case #addPicture:
addedPicture = true;
return;
case #pop:
return;
}
super.noSuchMethod(invocation);
}
}
class FakeOpacityEngineLayer extends FakeEngineLayer implements OpacityEngineLayer {}
class FakeOffsetEngineLayer extends FakeEngineLayer implements OffsetEngineLayer {}
| flutter/packages/flutter/test/rendering/layers_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/layers_test.dart",
"repo_id": "flutter",
"token_count": 12479
} | 667 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('list body and paragraph intrinsics', () {
final RenderParagraph paragraph = RenderParagraph(
const TextSpan(
style: TextStyle(height: 1.0),
text: 'Hello World',
),
textDirection: TextDirection.ltr,
);
final RenderListBody testBlock = RenderListBody(
children: <RenderBox>[
paragraph,
],
);
final double textWidth = paragraph.getMaxIntrinsicWidth(double.infinity);
final double oneLineTextHeight = paragraph.getMinIntrinsicHeight(double.infinity);
final double constrainedWidth = textWidth * 0.9;
final double wrappedTextWidth = paragraph.getMinIntrinsicWidth(double.infinity);
final double twoLinesTextHeight = paragraph.getMinIntrinsicHeight(constrainedWidth);
final double manyLinesTextHeight = paragraph.getMinIntrinsicHeight(0.0);
// paragraph
expect(wrappedTextWidth, greaterThan(0.0));
expect(wrappedTextWidth, lessThan(textWidth));
expect(oneLineTextHeight, lessThan(twoLinesTextHeight));
expect(twoLinesTextHeight, lessThan(oneLineTextHeight * 3.0));
expect(manyLinesTextHeight, greaterThan(twoLinesTextHeight));
expect(paragraph.getMaxIntrinsicHeight(double.infinity), equals(oneLineTextHeight));
expect(paragraph.getMaxIntrinsicHeight(constrainedWidth), equals(twoLinesTextHeight));
expect(paragraph.getMaxIntrinsicHeight(0.0), equals(manyLinesTextHeight));
// vertical block (same expectations)
expect(testBlock.getMinIntrinsicWidth(double.infinity), equals(wrappedTextWidth));
expect(testBlock.getMaxIntrinsicWidth(double.infinity), equals(textWidth));
expect(testBlock.getMinIntrinsicHeight(double.infinity), equals(oneLineTextHeight));
expect(testBlock.getMinIntrinsicHeight(constrainedWidth), equals(twoLinesTextHeight));
expect(testBlock.getMaxIntrinsicHeight(double.infinity), equals(oneLineTextHeight));
expect(testBlock.getMaxIntrinsicHeight(constrainedWidth), equals(twoLinesTextHeight));
expect(testBlock.getMinIntrinsicWidth(0.0), equals(wrappedTextWidth));
expect(testBlock.getMaxIntrinsicWidth(0.0), equals(textWidth));
expect(testBlock.getMinIntrinsicHeight(wrappedTextWidth), equals(twoLinesTextHeight));
expect(testBlock.getMaxIntrinsicHeight(wrappedTextWidth), equals(twoLinesTextHeight));
expect(testBlock.getMinIntrinsicHeight(0.0), equals(manyLinesTextHeight));
expect(testBlock.getMaxIntrinsicHeight(0.0), equals(manyLinesTextHeight));
// horizontal block (same expectations again)
testBlock.axisDirection = AxisDirection.right;
expect(testBlock.getMinIntrinsicWidth(double.infinity), equals(wrappedTextWidth));
expect(testBlock.getMaxIntrinsicWidth(double.infinity), equals(textWidth));
expect(testBlock.getMinIntrinsicHeight(double.infinity), equals(oneLineTextHeight));
expect(testBlock.getMinIntrinsicHeight(constrainedWidth), equals(twoLinesTextHeight));
expect(testBlock.getMaxIntrinsicHeight(double.infinity), equals(oneLineTextHeight));
expect(testBlock.getMaxIntrinsicHeight(constrainedWidth), equals(twoLinesTextHeight));
expect(testBlock.getMinIntrinsicWidth(0.0), equals(wrappedTextWidth));
expect(testBlock.getMaxIntrinsicWidth(0.0), equals(textWidth));
expect(testBlock.getMinIntrinsicHeight(wrappedTextWidth), equals(twoLinesTextHeight));
expect(testBlock.getMaxIntrinsicHeight(wrappedTextWidth), equals(twoLinesTextHeight));
expect(testBlock.getMinIntrinsicHeight(0.0), equals(manyLinesTextHeight));
expect(testBlock.getMaxIntrinsicHeight(0.0), equals(manyLinesTextHeight));
});
test('textScaler affects intrinsics', () {
final RenderParagraph paragraph = RenderParagraph(
const TextSpan(
style: TextStyle(fontSize: 10),
text: 'Hello World',
),
textDirection: TextDirection.ltr,
);
expect(paragraph.getMaxIntrinsicWidth(double.infinity), 110);
paragraph.textScaler = const TextScaler.linear(2);
expect(paragraph.getMaxIntrinsicWidth(double.infinity), 220);
});
test('maxLines affects intrinsics', () {
final RenderParagraph paragraph = RenderParagraph(
TextSpan(
style: const TextStyle(fontSize: 10),
text: List<String>.filled(5, 'A').join('\n'),
),
textDirection: TextDirection.ltr,
);
expect(paragraph.getMaxIntrinsicHeight(double.infinity), 50);
paragraph.maxLines = 1;
expect(paragraph.getMaxIntrinsicHeight(double.infinity), 10);
});
test('strutStyle affects intrinsics', () {
final RenderParagraph paragraph = RenderParagraph(
const TextSpan(
style: TextStyle(fontSize: 10),
text: 'Hello World',
),
textDirection: TextDirection.ltr,
);
expect(paragraph.getMaxIntrinsicHeight(double.infinity), 10);
paragraph.strutStyle = const StrutStyle(fontSize: 100, forceStrutHeight: true);
expect(paragraph.getMaxIntrinsicHeight(double.infinity), 100);
}, skip: kIsWeb && !isCanvasKit); // [intended] strut spport for HTML renderer https://github.com/flutter/flutter/issues/32243.
}
| flutter/packages/flutter/test/rendering/paragraph_intrinsics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/paragraph_intrinsics_test.dart",
"repo_id": "flutter",
"token_count": 1874
} | 668 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('only send semantics update if semantics have changed', () {
final TestRender testRender = TestRender()
..properties = const SemanticsProperties(label: 'hello')
..textDirection = TextDirection.ltr;
final RenderConstrainedBox tree = RenderConstrainedBox(
additionalConstraints: const BoxConstraints.tightFor(height: 20.0, width: 20.0),
child: testRender,
);
int semanticsUpdateCount = 0;
final SemanticsHandle semanticsHandle = TestRenderingFlutterBinding.instance.pipelineOwner.ensureSemantics(
listener: () {
++semanticsUpdateCount;
},
);
layout(tree, phase: EnginePhase.flushSemantics);
// Initial render does semantics.
expect(semanticsUpdateCount, 1);
expect(testRender.describeSemanticsConfigurationCallCount, isPositive);
testRender.describeSemanticsConfigurationCallCount = 0;
semanticsUpdateCount = 0;
// Request semantics update even though nothing changed.
testRender.markNeedsSemanticsUpdate();
pumpFrame(phase: EnginePhase.flushSemantics);
// Object is asked for semantics, but no update is sent.
expect(semanticsUpdateCount, 0);
expect(testRender.describeSemanticsConfigurationCallCount, isPositive);
testRender.describeSemanticsConfigurationCallCount = 0;
semanticsUpdateCount = 0;
// Change semantics and request update.
testRender.properties = const SemanticsProperties(label: 'bye');
testRender.markNeedsSemanticsUpdate();
pumpFrame(phase: EnginePhase.flushSemantics);
// Object is asked for semantics, and update is sent.
expect(semanticsUpdateCount, 1);
expect(testRender.describeSemanticsConfigurationCallCount, isPositive);
semanticsHandle.dispose();
});
}
class TestRender extends RenderSemanticsAnnotations {
TestRender() : super(properties: const SemanticsProperties());
int describeSemanticsConfigurationCallCount = 0;
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
describeSemanticsConfigurationCallCount += 1;
}
}
| flutter/packages/flutter/test/rendering/simple_semantics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/simple_semantics_test.dart",
"repo_id": "flutter",
"token_count": 745
} | 669 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
// Create non-const instances, otherwise tests pass even if the
// operator override is incorrect.
ViewConfiguration createViewConfiguration({
Size size = const Size(20, 20),
double devicePixelRatio = 2.0,
}) {
final BoxConstraints constraints = BoxConstraints.tight(size);
return ViewConfiguration(
logicalConstraints: constraints,
physicalConstraints: constraints * devicePixelRatio,
devicePixelRatio: devicePixelRatio,
);
}
group('RenderView', () {
test('accounts for device pixel ratio in paintBounds', () {
layout(RenderAspectRatio(aspectRatio: 1.0));
pumpFrame();
final Size logicalSize = TestRenderingFlutterBinding.instance.renderView.size;
final double devicePixelRatio = TestRenderingFlutterBinding.instance.renderView.configuration.devicePixelRatio;
final Size physicalSize = logicalSize * devicePixelRatio;
expect(TestRenderingFlutterBinding.instance.renderView.paintBounds, Offset.zero & physicalSize);
});
test('does not replace the root layer unnecessarily', () {
final RenderView view = RenderView(
configuration: createViewConfiguration(),
view: RendererBinding.instance.platformDispatcher.views.single,
);
final PipelineOwner owner = PipelineOwner();
view.attach(owner);
view.prepareInitialFrame();
final ContainerLayer firstLayer = view.debugLayer!;
view.configuration = createViewConfiguration();
expect(identical(view.debugLayer, firstLayer), true);
view.configuration = createViewConfiguration(devicePixelRatio: 5.0);
expect(identical(view.debugLayer, firstLayer), false);
});
test('does not replace the root layer unnecessarily when view resizes', () {
final RenderView view = RenderView(
configuration: createViewConfiguration(size: const Size(100.0, 100.0)),
view: RendererBinding.instance.platformDispatcher.views.single,
);
final PipelineOwner owner = PipelineOwner();
view.attach(owner);
view.prepareInitialFrame();
final ContainerLayer firstLayer = view.debugLayer!;
view.configuration = createViewConfiguration(size: const Size(100.0, 1117.0));
expect(identical(view.debugLayer, firstLayer), true);
});
});
test('ViewConfiguration == and hashCode', () {
final ViewConfiguration viewConfigurationA = createViewConfiguration();
final ViewConfiguration viewConfigurationB = createViewConfiguration();
final ViewConfiguration viewConfigurationC = createViewConfiguration(devicePixelRatio: 3.0);
expect(viewConfigurationA == viewConfigurationB, true);
expect(viewConfigurationA != viewConfigurationC, true);
expect(viewConfigurationA.hashCode, viewConfigurationB.hashCode);
expect(viewConfigurationA.hashCode != viewConfigurationC.hashCode, true);
});
test('invokes DebugPaintCallback', () {
final PaintPattern paintsOrangeRect = paints..rect(
color: orange,
rect: orangeRect,
);
final PaintPattern paintsGreenRect = paints..rect(
color: green,
rect: greenRect,
);
final PaintPattern paintOrangeAndGreenRect = paints
..rect(
color: orange,
rect: orangeRect,
)
..rect(
color: green,
rect: greenRect,
);
void paintCallback(PaintingContext context, Offset offset, RenderView renderView) {
context.canvas.drawRect(
greenRect,
Paint()..color = green,
);
}
layout(TestRenderObject());
expect(
TestRenderingFlutterBinding.instance.renderView,
paintsOrangeRect,
);
expect(
TestRenderingFlutterBinding.instance.renderView,
isNot(paintsGreenRect),
);
RenderView.debugAddPaintCallback(paintCallback);
expect(
TestRenderingFlutterBinding.instance.renderView,
paintOrangeAndGreenRect,
);
RenderView.debugRemovePaintCallback(paintCallback);
expect(
TestRenderingFlutterBinding.instance.renderView,
paintsOrangeRect,
);
expect(
TestRenderingFlutterBinding.instance.renderView,
isNot(paintsGreenRect),
);
});
test('Config can be set and changed after instantiation without calling prepareInitialFrame first', () {
final RenderView view = RenderView(
view: RendererBinding.instance.platformDispatcher.views.single,
);
view.configuration = ViewConfiguration(logicalConstraints: BoxConstraints.tight(const Size(100, 200)), devicePixelRatio: 3.0);
view.configuration = ViewConfiguration(logicalConstraints: BoxConstraints.tight(const Size(200, 300)), devicePixelRatio: 2.0);
PipelineOwner().rootNode = view;
view.prepareInitialFrame();
});
test('Constraints are derived from configuration', () {
const BoxConstraints constraints = BoxConstraints(minWidth: 1, maxWidth: 2, minHeight: 3, maxHeight: 4);
const double devicePixelRatio = 3.0;
final ViewConfiguration config = ViewConfiguration(
logicalConstraints: constraints,
physicalConstraints: constraints * devicePixelRatio,
devicePixelRatio: devicePixelRatio,
);
// Configuration set via setter.
final RenderView view = RenderView(
view: RendererBinding.instance.platformDispatcher.views.single,
);
expect(() => view.constraints, throwsA(isA<StateError>().having(
(StateError e) => e.message,
'message',
contains('RenderView has not been given a configuration yet'),
)));
view.configuration = config;
expect(view.constraints, constraints);
// Configuration set in constructor.
final RenderView view2 = RenderView(
view: RendererBinding.instance.platformDispatcher.views.single,
configuration: config,
);
expect(view2.constraints, constraints);
});
}
const Color orange = Color(0xFFFF9000);
const Color green = Color(0xFF0FF900);
const Rect orangeRect = Rect.fromLTWH(10, 10, 50, 75);
const Rect greenRect = Rect.fromLTWH(20, 20, 100, 150);
class TestRenderObject extends RenderBox {
@override
void performLayout() {
size = constraints.biggest;
}
@override
void paint(PaintingContext context, Offset offset) {
context.canvas.drawRect(
orangeRect,
Paint()..color = orange,
);
}
}
| flutter/packages/flutter/test/rendering/view_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/view_test.dart",
"repo_id": "flutter",
"token_count": 2238
} | 670 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
testWidgets('SemanticsNodes overlapping in z', (WidgetTester tester) async {
// Cards are semantic boundaries that always own their own SemanticNode,
// PhysicalModels merge their semantics information into parent.
//
// Side view of the widget tree:
//
// Card('abs. elevation: 30') ---------------
// | 8 ----------- Card('abs. elevation 25')
// Card('abs. elevation: 22') --------------- |
// | 7 |
// PhysicalModel('abs. elevation: 15') --------------- | 15
// | 5 |
// --------------------------------------- Card('abs. elevation: 10')
// | 10
// |
// --------------------------------------- 'ground'
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(const MaterialApp(
home: Column(
children: <Widget>[
Text('ground'),
Card(
elevation: 10.0,
child: Column(
children: <Widget>[
Text('absolute elevation: 10'),
PhysicalModel(
elevation: 5.0,
color: Colors.black,
child: Column(
children: <Widget>[
Text('absolute elevation: 15'),
Card(
elevation: 7.0,
child: Column(
children: <Widget>[
Text('absolute elevation: 22'),
Card(
elevation: 8.0,
child: Text('absolute elevation: 30'),
),
],
),
),
],
),
),
Card(
elevation: 15.0,
child: Text('absolute elevation: 25'),
),
],
),
),
],
),
));
final SemanticsNode ground = tester.getSemantics(find.text('ground'));
expect(ground.thickness, 0.0);
expect(ground.elevation, 0.0);
expect(ground.label, 'ground');
final SemanticsNode elevation10 = tester.getSemantics(find.text('absolute elevation: 10'));
final SemanticsNode elevation15 = tester.getSemantics(find.text('absolute elevation: 15'));
expect(elevation10, same(elevation15)); // configs got merged into each other.
expect(elevation10.thickness, 15.0);
expect(elevation10.elevation, 0.0);
expect(elevation10.label, 'absolute elevation: 10\nabsolute elevation: 15');
final SemanticsNode elevation22 = tester.getSemantics(find.text('absolute elevation: 22'));
expect(elevation22.thickness, 7.0);
expect(elevation22.elevation, 15.0);
expect(elevation22.label, 'absolute elevation: 22');
final SemanticsNode elevation25 = tester.getSemantics(find.text('absolute elevation: 25'));
expect(elevation25.thickness, 15.0);
expect(elevation25.elevation, 10.0);
expect(elevation22.label, 'absolute elevation: 22');
final SemanticsNode elevation30 = tester.getSemantics(find.text('absolute elevation: 30'));
expect(elevation30.thickness, 8.0);
expect(elevation30.elevation, 7.0);
expect(elevation30.label, 'absolute elevation: 30');
semantics.dispose();
});
testWidgets('SemanticsNodes overlapping in z with switched children', (WidgetTester tester) async {
// Same as 'SemanticsNodes overlapping in z', but the order of children
// is reversed
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(const MaterialApp(
home: Column(
children: <Widget>[
Text('ground'),
Card(
elevation: 10.0,
child: Column(
children: <Widget>[
Card(
elevation: 15.0,
child: Text('absolute elevation: 25'),
),
PhysicalModel(
elevation: 5.0,
color: Colors.black,
child: Column(
children: <Widget>[
Text('absolute elevation: 15'),
Card(
elevation: 7.0,
child: Column(
children: <Widget>[
Text('absolute elevation: 22'),
Card(
elevation: 8.0,
child: Text('absolute elevation: 30'),
),
],
),
),
],
),
),
Text('absolute elevation: 10'),
],
),
),
],
),
));
final SemanticsNode ground = tester.getSemantics(find.text('ground'));
expect(ground.thickness, 0.0);
expect(ground.elevation, 0.0);
expect(ground.label, 'ground');
final SemanticsNode elevation10 = tester.getSemantics(find.text('absolute elevation: 10'));
final SemanticsNode elevation15 = tester.getSemantics(find.text('absolute elevation: 15'));
expect(elevation10, same(elevation15)); // configs got merged into each other.
expect(elevation10.thickness, 15.0);
expect(elevation10.elevation, 0.0);
expect(elevation10.label, 'absolute elevation: 15\nabsolute elevation: 10');
final SemanticsNode elevation22 = tester.getSemantics(find.text('absolute elevation: 22'));
expect(elevation22.thickness, 7.0);
expect(elevation22.elevation, 15.0);
expect(elevation22.label, 'absolute elevation: 22');
final SemanticsNode elevation25 = tester.getSemantics(find.text('absolute elevation: 25'));
expect(elevation25.thickness, 15.0);
expect(elevation25.elevation, 10.0);
expect(elevation22.label, 'absolute elevation: 22');
final SemanticsNode elevation30 = tester.getSemantics(find.text('absolute elevation: 30'));
expect(elevation30.thickness, 8.0);
expect(elevation30.elevation, 7.0);
expect(elevation30.label, 'absolute elevation: 30');
semantics.dispose();
});
testWidgets('single node thickness', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(const MaterialApp(
home: Center(
child: Material(
elevation: 24.0,
child: Text('Hello'),
),
),
));
final SemanticsNode node = tester.getSemantics(find.text('Hello'));
expect(node.thickness, 0.0);
expect(node.elevation, 24.0);
expect(node.label, 'Hello');
semantics.dispose();
});
testWidgets('force-merge', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(MaterialApp(
home: Card(
elevation: 10.0,
child: Column(
children: <Widget>[
const Text('abs. elevation: 10.0'),
MergeSemantics(
child: Semantics(
explicitChildNodes: true, // just to be sure that it's going to be an explicit merge
child: const Column(
children: <Widget>[
Card(
elevation: 15.0,
child: Text('abs. elevation 25.0'),
),
Card(
elevation: 5.0,
child: Text('abs. elevation 15.0'),
),
],
),
),
),
],
),
),
));
final SemanticsNode elevation10 = tester.getSemantics(find.text('abs. elevation: 10.0'));
expect(elevation10.thickness, 10.0);
expect(elevation10.elevation, 0.0);
expect(elevation10.label, 'abs. elevation: 10.0');
expect(elevation10.childrenCount, 1);
// TODO(goderbauer): remove awkward workaround when accessing force-merged
// SemanticsData becomes easier, https://github.com/flutter/flutter/issues/25669
SemanticsData? mergedChildData;
elevation10.visitChildren((SemanticsNode child) {
expect(mergedChildData, isNull);
mergedChildData = child.getSemanticsData();
return true;
});
expect(mergedChildData!.thickness, 15.0);
expect(mergedChildData!.elevation, 10.0);
expect(mergedChildData!.label, 'abs. elevation 25.0\nabs. elevation 15.0');
semantics.dispose();
});
testWidgets('force-merge with inversed children', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(MaterialApp(
home: Card(
elevation: 10.0,
child: Column(
children: <Widget>[
const Text('abs. elevation: 10.0'),
MergeSemantics(
child: Semantics(
explicitChildNodes: true, // just to be sure that it's going to be an explicit merge
child: const Column(
children: <Widget>[
Card(
elevation: 5.0,
child: Text('abs. elevation 15.0'),
),
Card(
elevation: 15.0,
child: Text('abs. elevation 25.0'),
),
],
),
),
),
],
),
),
));
final SemanticsNode elevation10 = tester.getSemantics(find.text('abs. elevation: 10.0'));
expect(elevation10.thickness, 10.0);
expect(elevation10.elevation, 0.0);
expect(elevation10.label, 'abs. elevation: 10.0');
expect(elevation10.childrenCount, 1);
// TODO(goderbauer): remove awkward workaround when accessing force-merged
// SemanticsData becomes easier, https://github.com/flutter/flutter/issues/25669
SemanticsData? mergedChildData;
elevation10.visitChildren((SemanticsNode child) {
expect(mergedChildData, isNull);
mergedChildData = child.getSemanticsData();
return true;
});
expect(mergedChildData!.thickness, 15.0);
expect(mergedChildData!.elevation, 10.0);
expect(mergedChildData!.label, 'abs. elevation 15.0\nabs. elevation 25.0');
semantics.dispose();
});
}
| flutter/packages/flutter/test/semantics/semantics_elevation_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/semantics/semantics_elevation_test.dart",
"repo_id": "flutter",
"token_count": 5593
} | 671 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' show jsonDecode;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'text_input_utils.dart';
void main() {
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
group('DeltaTextInputClient', () {
late FakeTextChannel fakeTextChannel;
setUp(() {
fakeTextChannel = FakeTextChannel((MethodCall call) async {});
TextInput.setChannel(fakeTextChannel);
});
tearDown(() {
TextInputConnection.debugResetId();
TextInput.setChannel(SystemChannels.textInput);
});
test(
'DeltaTextInputClient send the correct configuration to the platform and responds to updateEditingValueWithDeltas method correctly',
() async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeDeltaTextInputClient client = FakeDeltaTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration(enableDeltaModel: true);
TextInput.attach(client, configuration);
expect(client.configuration.enableDeltaModel, true);
expect(client.latestMethodCall, isEmpty);
const String jsonDelta = '{'
'"oldText": "",'
' "deltaText": "let there be text",'
' "deltaStart": 0,'
' "deltaEnd": 0,'
' "selectionBase": 17,'
' "selectionExtent": 17,'
' "selectionAffinity" : "TextAffinity.downstream" ,'
' "selectionIsDirectional": false,'
' "composingBase": -1,'
' "composingExtent": -1}';
// Send updateEditingValueWithDeltas message.
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
jsonDecode('{"deltas": [$jsonDelta]}'),
],
'method': 'TextInputClient.updateEditingStateWithDeltas',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'updateEditingValueWithDeltas');
},
);
test('Invalid TextRange fails loudly when being converted to JSON - NonTextUpdate', () async {
final List<FlutterErrorDetails> record = <FlutterErrorDetails>[];
FlutterError.onError = (FlutterErrorDetails details) {
record.add(details);
};
final FakeDeltaTextInputClient client = FakeDeltaTextInputClient(const TextEditingValue(text: '1'));
const TextInputConfiguration configuration = TextInputConfiguration(enableDeltaModel: true);
TextInput.attach(client, configuration);
const String jsonDelta = '{'
'"oldText": "1",'
' "deltaText": "",'
' "deltaStart": -1,'
' "deltaEnd": -1,'
' "selectionBase": 3,'
' "selectionExtent": 3,'
' "selectionAffinity" : "TextAffinity.downstream" ,'
' "selectionIsDirectional": false,'
' "composingBase": -1,'
' "composingExtent": -1}';
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'method': 'TextInputClient.updateEditingStateWithDeltas',
'args': <dynamic>[-1, jsonDecode('{"deltas": [$jsonDelta]}')],
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(record.length, 1);
// Verify the error message in parts because Web formats the message
// differently from others.
expect(record[0].exception.toString(), matches(RegExp(r'\bThe selection range: TextSelection.collapsed\(offset: 3, affinity: TextAffinity.downstream, isDirectional: false\)(?!\w)')));
expect(record[0].exception.toString(), matches(RegExp(r'\bis not within the bounds of text: 1 of length: 1\b')));
});
test('Invalid TextRange fails loudly when being converted to JSON - Faulty deltaStart and deltaEnd', () async {
final List<FlutterErrorDetails> record = <FlutterErrorDetails>[];
FlutterError.onError = (FlutterErrorDetails details) {
record.add(details);
};
final FakeDeltaTextInputClient client = FakeDeltaTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration(enableDeltaModel: true);
TextInput.attach(client, configuration);
const String jsonDelta = '{'
'"oldText": "",'
' "deltaText": "hello",'
' "deltaStart": 0,'
' "deltaEnd": 1,'
' "selectionBase": 5,'
' "selectionExtent": 5,'
' "selectionAffinity" : "TextAffinity.downstream" ,'
' "selectionIsDirectional": false,'
' "composingBase": -1,'
' "composingExtent": -1}';
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'method': 'TextInputClient.updateEditingStateWithDeltas',
'args': <dynamic>[-1, jsonDecode('{"deltas": [$jsonDelta]}')],
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(record.length, 1);
// Verify the error message in parts because Web formats the message
// differently from others.
expect(record[0].exception.toString(), matches(RegExp(r'\bThe delta range: TextRange\(start: 0, end: 5\)(?!\w)')));
expect(record[0].exception.toString(), matches(RegExp(r'\bis not within the bounds of text: of length: 0\b')));
});
test('Invalid TextRange fails loudly when being converted to JSON - Faulty Selection', () async {
final List<FlutterErrorDetails> record = <FlutterErrorDetails>[];
FlutterError.onError = (FlutterErrorDetails details) {
record.add(details);
};
final FakeDeltaTextInputClient client = FakeDeltaTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration(enableDeltaModel: true);
TextInput.attach(client, configuration);
const String jsonDelta = '{'
'"oldText": "",'
' "deltaText": "hello",'
' "deltaStart": 0,'
' "deltaEnd": 0,'
' "selectionBase": 6,'
' "selectionExtent": 6,'
' "selectionAffinity" : "TextAffinity.downstream" ,'
' "selectionIsDirectional": false,'
' "composingBase": -1,'
' "composingExtent": -1}';
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'method': 'TextInputClient.updateEditingStateWithDeltas',
'args': <dynamic>[-1, jsonDecode('{"deltas": [$jsonDelta]}')],
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(record.length, 1);
// Verify the error message in parts because Web formats the message
// differently from others.
expect(record[0].exception.toString(), matches(RegExp(r'\bThe selection range: TextSelection.collapsed\(offset: 6, affinity: TextAffinity.downstream, isDirectional: false\)(?!\w)')));
expect(record[0].exception.toString(), matches(RegExp(r'\bis not within the bounds of text: hello of length: 5\b')));
});
test('Invalid TextRange fails loudly when being converted to JSON - Faulty Composing Region', () async {
final List<FlutterErrorDetails> record = <FlutterErrorDetails>[];
FlutterError.onError = (FlutterErrorDetails details) {
record.add(details);
};
final FakeDeltaTextInputClient client = FakeDeltaTextInputClient(const TextEditingValue(text: 'worl'));
const TextInputConfiguration configuration = TextInputConfiguration(enableDeltaModel: true);
TextInput.attach(client, configuration);
const String jsonDelta = '{'
'"oldText": "worl",'
' "deltaText": "world",'
' "deltaStart": 0,'
' "deltaEnd": 4,'
' "selectionBase": 5,'
' "selectionExtent": 5,'
' "selectionAffinity" : "TextAffinity.downstream" ,'
' "selectionIsDirectional": false,'
' "composingBase": 0,'
' "composingExtent": 6}';
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'method': 'TextInputClient.updateEditingStateWithDeltas',
'args': <dynamic>[-1, jsonDecode('{"deltas": [$jsonDelta]}')],
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(record.length, 1);
// Verify the error message in parts because Web formats the message
// differently from others.
expect(record[0].exception.toString(), matches(RegExp(r'\bThe composing range: TextRange\(start: 0, end: 6\)(?!\w)')));
expect(record[0].exception.toString(), matches(RegExp(r'\bis not within the bounds of text: world of length: 5\b')));
});
});
}
class FakeDeltaTextInputClient implements DeltaTextInputClient {
FakeDeltaTextInputClient(this.currentTextEditingValue);
String latestMethodCall = '';
@override
TextEditingValue currentTextEditingValue;
@override
AutofillScope? get currentAutofillScope => null;
@override
void performAction(TextInputAction action) {
latestMethodCall = 'performAction';
}
@override
void performPrivateCommand(String action, Map<String, dynamic> data) {
latestMethodCall = 'performPrivateCommand';
}
@override
void insertContent(KeyboardInsertedContent content) {
latestMethodCall = 'commitContent';
}
@override
void updateEditingValue(TextEditingValue value) {
latestMethodCall = 'updateEditingValue';
}
@override
void updateEditingValueWithDeltas(List<TextEditingDelta> textEditingDeltas) {
latestMethodCall = 'updateEditingValueWithDeltas';
}
@override
void updateFloatingCursor(RawFloatingCursorPoint point) {
latestMethodCall = 'updateFloatingCursor';
}
@override
void connectionClosed() {
latestMethodCall = 'connectionClosed';
}
@override
void showAutocorrectionPromptRect(int start, int end) {
latestMethodCall = 'showAutocorrectionPromptRect';
}
@override
void insertTextPlaceholder(Size size) {
latestMethodCall = 'insertTextPlaceholder';
}
@override
void removeTextPlaceholder() {
latestMethodCall = 'removeTextPlaceholder';
}
@override
void showToolbar() {
latestMethodCall = 'showToolbar';
}
@override
void performSelector(String selectorName) {
latestMethodCall = 'performSelector';
}
TextInputConfiguration get configuration => const TextInputConfiguration(enableDeltaModel: true);
@override
void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
latestMethodCall = 'didChangeInputControl';
}
}
| flutter/packages/flutter/test/services/delta_text_input_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/delta_text_input_test.dart",
"repo_id": "flutter",
"token_count": 4274
} | 672 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class _ModifierCheck {
const _ModifierCheck(this.key, this.side);
final ModifierKey key;
final KeyboardSide side;
}
void main() {
group('RawKeyboard', () {
testWidgets('The correct character is produced', (WidgetTester tester) async {
for (final String platform in <String>['linux', 'android', 'macos', 'fuchsia', 'windows', 'ios']) {
String character = '';
void handleKey(RawKeyEvent event) {
expect(event.character, equals(character), reason: 'on $platform');
}
RawKeyboard.instance.addListener(handleKey);
character = 'a';
await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform);
character = '`';
await simulateKeyDownEvent(LogicalKeyboardKey.backquote, platform: platform);
RawKeyboard.instance.removeListener(handleKey);
}
}, variant: KeySimulatorTransitModeVariant.rawKeyData());
testWidgets('No character is produced for non-printables', (WidgetTester tester) async {
for (final String platform in <String>['linux', 'android', 'macos', 'fuchsia', 'windows', 'web', 'ios']) {
void handleKey(RawKeyEvent event) {
expect(event.character, isNull, reason: 'on $platform');
}
RawKeyboard.instance.addListener(handleKey);
await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform);
RawKeyboard.instance.removeListener(handleKey);
}
}, variant: KeySimulatorTransitModeVariant.rawKeyData());
testWidgets('keysPressed is maintained', (WidgetTester tester) async {
for (final String platform in <String>['linux', 'android', 'macos', 'fuchsia', 'windows', 'ios']) {
RawKeyboard.instance.clearKeysPressed();
expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform');
await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{ LogicalKeyboardKey.shiftLeft,
// Linux doesn't have a concept of left/right keys, so they're all
// shown as down when either is pressed.
if (platform == 'linux') LogicalKeyboardKey.shiftRight,
},
),
reason: 'on $platform',
);
await simulateKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
if (platform == 'linux') LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.controlLeft,
if (platform == 'linux') LogicalKeyboardKey.controlRight,
},
),
reason: 'on $platform',
);
await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
if (platform == 'linux') LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.controlLeft,
if (platform == 'linux') LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.keyA,
},
),
reason: 'on $platform',
);
await simulateKeyUpEvent(LogicalKeyboardKey.keyA, platform: platform);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
if (platform == 'linux') LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.controlLeft,
if (platform == 'linux') LogicalKeyboardKey.controlRight,
},
),
reason: 'on $platform',
);
await simulateKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
if (platform == 'linux') LogicalKeyboardKey.shiftRight,
},
),
reason: 'on $platform',
);
await simulateKeyUpEvent(LogicalKeyboardKey.shiftLeft, platform: platform);
expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform');
// The Fn key isn't mapped on linux or Windows.
if (platform != 'linux' && platform != 'windows' && platform != 'ios') {
await simulateKeyDownEvent(LogicalKeyboardKey.fn, platform: platform);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
if (platform != 'macos') LogicalKeyboardKey.fn,
},
),
reason: 'on $platform',
);
await simulateKeyDownEvent(LogicalKeyboardKey.f12, platform: platform);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
if (platform != 'macos') LogicalKeyboardKey.fn,
LogicalKeyboardKey.f12,
},
),
reason: 'on $platform',
);
await simulateKeyUpEvent(LogicalKeyboardKey.fn, platform: platform);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{ LogicalKeyboardKey.f12 },
),
reason: 'on $platform',
);
await simulateKeyUpEvent(LogicalKeyboardKey.f12, platform: platform);
expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform');
}
}
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // https://github.com/flutter/flutter/issues/61021
);
testWidgets('keysPressed is correct when modifier is released before key', (WidgetTester tester) async {
for (final String platform in <String>['linux', 'android', 'macos', 'fuchsia', 'windows', 'ios']) {
RawKeyboard.instance.clearKeysPressed();
expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform');
await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform, physicalKey: PhysicalKeyboardKey.shiftLeft);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
// Linux doesn't have a concept of left/right keys, so they're all
// shown as down when either is pressed.
if (platform == 'linux') LogicalKeyboardKey.shiftRight,
},
),
reason: 'on $platform',
);
// TODO(gspencergoog): Switch to capital A when the new key event code
// is finished that can simulate real keys.
// https://github.com/flutter/flutter/issues/33521
// This should really be done with a simulated capital A, but the event
// simulation code doesn't really support that, since it only can
// simulate events that appear in the key maps (and capital letters
// don't appear there).
await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform, physicalKey: PhysicalKeyboardKey.keyA);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
if (platform == 'linux') LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.keyA,
},
),
reason: 'on $platform',
);
await simulateKeyUpEvent(LogicalKeyboardKey.shiftLeft, platform: platform, physicalKey: PhysicalKeyboardKey.shiftLeft);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.keyA,
},
),
reason: 'on $platform',
);
await simulateKeyUpEvent(LogicalKeyboardKey.keyA, platform: platform, physicalKey: PhysicalKeyboardKey.keyA);
expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform');
}
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // https://github.com/flutter/flutter/issues/76741
);
testWidgets('keysPressed modifiers are synchronized with key events on macOS', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'macos',
);
// Change the modifiers so that they show the shift key as already down
// when this event is received, but it's not in keysPressed yet.
data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataMacOs.modifierLeftShift | RawKeyEventDataMacOs.modifierShift;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is a macOS-specific test.
);
testWidgets('keysPressed modifiers are synchronized with key events on iOS', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'ios',
);
// Change the modifiers so that they show the shift key as already down
// when this event is received, but it's not in keysPressed yet.
data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataMacOs.modifierLeftShift | RawKeyEventDataMacOs.modifierShift;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is a iOS-specific test.
);
testWidgets('keysPressed modifiers are synchronized with key events on Windows', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'windows',
);
// Change the modifiers so that they show the shift key as already down
// when this event is received, but it's not in keysPressed yet.
data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataWindows.modifierLeftShift | RawKeyEventDataWindows.modifierShift;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is a Windows-specific test.
);
testWidgets('keysPressed modifiers are synchronized with key events on android', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'android',
);
// Change the modifiers so that they show the shift key as already down
// when this event is received, but it's not in keysPressed yet.
data['metaState'] = (data['metaState'] as int) | RawKeyEventDataAndroid.modifierLeftShift | RawKeyEventDataAndroid.modifierShift;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is an Android-specific test.
);
testWidgets('keysPressed modifiers are synchronized with key events on fuchsia', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'fuchsia',
);
// Change the modifiers so that they show the shift key as already down
// when this event is received, but it's not in keysPressed yet.
data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataFuchsia.modifierLeftShift;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is a Fuchsia-specific test.
);
testWidgets('keysPressed modifiers are synchronized with key events on Linux GLFW', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'linux',
);
// Change the modifiers so that they show the shift key as already down
// when this event is received, but it's not in keysPressed yet.
data['modifiers'] = (data['modifiers'] as int) | GLFWKeyHelper.modifierShift;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
// Linux doesn't have a concept of left/right keys, so they're all
// shown as down when either is pressed.
LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.keyA,
},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is a GLFW-specific test.
);
Future<void> simulateGTKKeyEvent(bool keyDown, int scancode, int keycode, int modifiers) async {
final Map<String, dynamic> data = <String, dynamic>{
'type': keyDown ? 'keydown' : 'keyup',
'keymap': 'linux',
'toolkit': 'gtk',
'scanCode': scancode,
'keyCode': keycode,
'modifiers': modifiers,
};
// Dispatch an empty key data to disable HardwareKeyboard sanity check,
// since we're only testing if the raw keyboard can handle the message.
// In a real application, the embedder responder will send the correct key data
// (which is tested in the engine).
TestDefaultBinaryMessengerBinding.instance.keyEventManager.handleKeyData(const ui.KeyData(
type: ui.KeyEventType.down,
timeStamp: Duration.zero,
logical: 0,
physical: 0,
character: null,
synthesized: false,
));
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
}
// Regression test for https://github.com/flutter/flutter/issues/93278 .
//
// GTK has some weird behavior where the tested key event sequence will
// result in a AltRight down event without Alt bitmask.
testWidgets('keysPressed modifiers are synchronized with key events on Linux GTK (down events)', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
await simulateGTKKeyEvent(true, 0x6c/*AltRight*/, 0xffea/*AltRight*/, 0x2000000);
await simulateGTKKeyEvent(true, 0x32/*ShiftLeft*/, 0xfe08/*NextGroup*/, 0x2000008/*MOD3*/);
await simulateGTKKeyEvent(false, 0x6c/*AltRight*/, 0xfe03/*AltRight*/, 0x2002008/*MOD3|Reserve14*/);
await simulateGTKKeyEvent(true, 0x6c/*AltRight*/, 0xfe03/*AltRight*/, 0x2002000/*Reserve14*/);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.altRight,
},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is a GTK-specific test.
);
// Regression test for https://github.com/flutter/flutter/issues/114591 .
//
// On Linux, CapsLock can be remapped to a non-modifier key.
testWidgets('CapsLock should not be release when remapped on Linux', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
await simulateGTKKeyEvent(true, 0x42/*CapsLock*/, 0xff08/*Backspace*/, 0x2000000);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.backspace,
},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is a GTK-specific test.
);
// Regression test for https://github.com/flutter/flutter/issues/114591 .
//
// On Web, CapsLock can be remapped to a non-modifier key.
testWidgets('CapsLock should not be release when remapped on Web', (WidgetTester _) async {
final List<RawKeyEvent> events = <RawKeyEvent>[];
RawKeyboard.instance.addListener(events.add);
addTearDown(() {
RawKeyboard.instance.removeListener(events.add);
});
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'CapsLock',
'key': 'Backspace',
'location': 0,
'metaState': 0,
'keyCode': 8,
}),
(ByteData? data) { },
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.backspace,
},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: !isBrowser, // [intended] This is a Browser-specific test.
);
testWidgets('keysPressed modifiers are synchronized with key events on web', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event. Change the modifiers so
// that they show the shift key as already down when this event is
// received, but it's not in keysPressed yet.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'web',
);
data['metaState'] = (data['metaState'] as int) | RawKeyEventDataWeb.modifierShift;
// Dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.keyA,
},
),
);
// Generate the data for a regular key up event. Don't set the modifiers
// for shift so that they show the shift key as already up when this event
// is received, and it's in keysPressed.
final Map<String, dynamic> data2 = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'web',
isDown: false,
)..['metaState'] = 0;
// Dispatch the modified data.
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data2),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{},
),
);
// Press right modifier key
final Map<String, dynamic> data3 = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.shiftRight,
platform: 'web',
);
data['metaState'] = (data['metaState'] as int) | RawKeyEventDataWeb.modifierShift;
// Dispatch the modified data.
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data3),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftRight,
},
),
);
// Release the key
final Map<String, dynamic> data4 = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.shiftRight,
platform: 'web',
isDown: false,
)..['metaState'] = 0;
// Dispatch the modified data.
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data4),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{},
),
);
});
testWidgets('sided modifiers without a side set return all sides on Android', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'android',
);
// Set only the generic "down" modifier, without setting a side.
data['metaState'] = (data['metaState'] as int) |
RawKeyEventDataAndroid.modifierShift |
RawKeyEventDataAndroid.modifierAlt |
RawKeyEventDataAndroid.modifierControl |
RawKeyEventDataAndroid.modifierMeta;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.metaRight,
LogicalKeyboardKey.keyA,
},
),
);
},
variant: KeySimulatorTransitModeVariant.rawKeyData(),
skip: isBrowser, // [intended] This is a Android-specific test.
);
testWidgets('sided modifiers without a side set return all sides on macOS', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'macos',
);
// Set only the generic "shift down" modifier, without setting a side.
data['modifiers'] = (data['modifiers'] as int) |
RawKeyEventDataMacOs.modifierShift |
RawKeyEventDataMacOs.modifierOption |
RawKeyEventDataMacOs.modifierCommand |
RawKeyEventDataMacOs.modifierControl;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.metaRight,
LogicalKeyboardKey.keyA,
},
),
);
}, skip: isBrowser); // [intended] This is a macOS-specific test.
testWidgets('sided modifiers without a side set return all sides on iOS', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'ios',
);
// Set only the generic "shift down" modifier, without setting a side.
data['modifiers'] = (data['modifiers'] as int) |
RawKeyEventDataIos.modifierShift |
RawKeyEventDataIos.modifierOption |
RawKeyEventDataIos.modifierCommand |
RawKeyEventDataIos.modifierControl;
// dispatch the modified data.
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.metaRight,
LogicalKeyboardKey.keyA,
},
),
);
}, skip: isBrowser); // [intended] This is an iOS-specific test.
testWidgets('repeat events', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
late RawKeyEvent receivedEvent;
RawKeyboard.instance.keyEventHandler = (RawKeyEvent event) {
receivedEvent = event;
return true;
};
// Dispatch a down event.
final Map<String, dynamic> downData = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'windows',
);
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(downData),
(ByteData? data) {},
);
expect(receivedEvent.repeat, false);
// Dispatch another down event, which should be recognized as a repeat.
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(downData),
(ByteData? data) {},
);
expect(receivedEvent.repeat, true);
// Dispatch an up event.
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
isDown: false,
platform: 'windows',
)),
(ByteData? data) {},
);
expect(receivedEvent.repeat, false);
RawKeyboard.instance.keyEventHandler = null;
}, skip: isBrowser); // [intended] This is a Windows-specific test.
testWidgets('sided modifiers without a side set return all sides on Windows', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'windows',
);
// Set only the generic "shift down" modifier, without setting a side.
// Windows doesn't have a concept of "either" for the Windows (meta) key.
data['modifiers'] = (data['modifiers'] as int) |
RawKeyEventDataWindows.modifierShift |
RawKeyEventDataWindows.modifierAlt |
RawKeyEventDataWindows.modifierControl;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.keyA,
},
),
);
}, skip: isBrowser); // [intended] This is a Windows-specific test.
testWidgets('sided modifiers without a side set return all sides on Linux GLFW', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'linux',
);
// Set only the generic "shift down" modifier, without setting a side.
// Windows doesn't have a concept of "either" for the Windows (meta) key.
data['modifiers'] = (data['modifiers'] as int) |
GLFWKeyHelper.modifierShift |
GLFWKeyHelper.modifierAlt |
GLFWKeyHelper.modifierControl |
GLFWKeyHelper.modifierMeta;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.metaRight,
LogicalKeyboardKey.keyA,
},
),
);
}, skip: isBrowser); // [intended] This is a GLFW-specific test.
testWidgets('sided modifiers without a side set return left sides on web', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'web',
);
// Set only the generic "shift down" modifier, without setting a side.
data['metaState'] = (data['metaState'] as int) |
RawKeyEventDataWeb.modifierShift |
RawKeyEventDataWeb.modifierAlt |
RawKeyEventDataWeb.modifierControl |
RawKeyEventDataWeb.modifierMeta;
// dispatch the modified data.
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {},
);
expect(
RawKeyboard.instance.keysPressed,
equals(
<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.keyA,
},
),
);
});
testWidgets('RawKeyboard asserts if no keys are in keysPressed after receiving a key down event', (WidgetTester tester) async {
final Map<String, dynamic> keyEventMessage;
if (kIsWeb) {
keyEventMessage = const <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'ShiftLeft', // Left shift code
'metaState': 0x0, // No shift key metaState set!
};
} else {
keyEventMessage = const <String, dynamic>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 16, // Left shift key keyCode
'characterCodePoint': 0,
'scanCode': 42,
'modifiers': 0x0, // No shift key metaState set!
};
}
expect(
() async {
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(keyEventMessage),
(ByteData? data) { },
);
},
throwsA(isA<AssertionError>().having(
(AssertionError error) => error.toString(),
'.toString()',
contains('Attempted to send a key down event when no keys are in keysPressed'),
)),
);
});
testWidgets('Allows inconsistent modifier for iOS', (WidgetTester _) async {
// Use `testWidgets` for clean-ups.
final List<RawKeyEvent> events = <RawKeyEvent>[];
RawKeyboard.instance.addListener(events.add);
addTearDown(() {
RawKeyboard.instance.removeListener(events.add);
});
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x00000039,
'characters': '',
'charactersIgnoringModifiers': '',
'modifiers': 0,
}),
(ByteData? data) { },
);
expect(events, hasLength(1));
final RawKeyEvent capsLockKey = events[0];
final RawKeyEventDataIos data = capsLockKey.data as RawKeyEventDataIos;
expect(data.physicalKey, equals(PhysicalKeyboardKey.capsLock));
expect(data.logicalKey, equals(LogicalKeyboardKey.capsLock));
expect(RawKeyboard.instance.keysPressed, contains(LogicalKeyboardKey.capsLock));
}, skip: isBrowser); // [intended] This is an iOS-specific group.
testWidgets('Allows inconsistent modifier for Android', (WidgetTester _) async {
// Use `testWidgets` for clean-ups.
final List<RawKeyEvent> events = <RawKeyEvent>[];
RawKeyboard.instance.addListener(events.add);
addTearDown(() {
RawKeyboard.instance.removeListener(events.add);
});
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 115,
'plainCodePoint': 0,
'codePoint': 0,
'scanCode': 58,
'metaState': 0,
'source': 0x101,
'deviceId': 1,
}),
(ByteData? data) { },
);
expect(events, hasLength(1));
final RawKeyEvent capsLockKey = events[0];
final RawKeyEventDataAndroid data = capsLockKey.data as RawKeyEventDataAndroid;
expect(data.physicalKey, equals(PhysicalKeyboardKey.capsLock));
expect(data.logicalKey, equals(LogicalKeyboardKey.capsLock));
expect(RawKeyboard.instance.keysPressed, contains(LogicalKeyboardKey.capsLock));
}, skip: isBrowser); // [intended] This is an Android-specific group.
testWidgets('Allows inconsistent modifier for Web - Alt graph', (WidgetTester _) async {
// Regression test for https://github.com/flutter/flutter/issues/113836
final List<RawKeyEvent> events = <RawKeyEvent>[];
RawKeyboard.instance.addListener(events.add);
addTearDown(() {
RawKeyboard.instance.removeListener(events.add);
});
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'AltRight',
'key': 'AltGraph',
'location': 2,
'metaState': 0,
'keyCode': 225,
}),
(ByteData? data) { },
);
expect(events, hasLength(1));
final RawKeyEvent altRightKey = events[0];
final RawKeyEventDataWeb data = altRightKey.data as RawKeyEventDataWeb;
expect(data.physicalKey, equals(PhysicalKeyboardKey.altRight));
expect(data.logicalKey, equals(LogicalKeyboardKey.altGraph));
expect(RawKeyboard.instance.keysPressed, contains(LogicalKeyboardKey.altGraph));
}, skip: !isBrowser); // [intended] This is a Browser-specific test.
testWidgets('Allows inconsistent modifier for Web - Alt right', (WidgetTester _) async {
// Regression test for https://github.com/flutter/flutter/issues/113836
final List<RawKeyEvent> events = <RawKeyEvent>[];
RawKeyboard.instance.addListener(events.add);
addTearDown(() {
RawKeyboard.instance.removeListener(events.add);
});
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'web',
'code': 'AltRight',
'key': 'Alt',
'location': 2,
'metaState': 0,
'keyCode': 225,
}),
(ByteData? data) { },
);
expect(events, hasLength(1));
final RawKeyEvent altRightKey = events[0];
final RawKeyEventDataWeb data = altRightKey.data as RawKeyEventDataWeb;
expect(data.physicalKey, equals(PhysicalKeyboardKey.altRight));
expect(data.logicalKey, equals(LogicalKeyboardKey.altRight));
expect(RawKeyboard.instance.keysPressed, contains(LogicalKeyboardKey.altRight));
}, skip: !isBrowser); // [intended] This is a Browser-specific test.
testWidgets('Dispatch events to all handlers', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
final List<int> logs = <int>[];
await tester.pumpWidget(
RawKeyboardListener(
autofocus: true,
focusNode: focusNode,
child: Container(),
onKey: (RawKeyEvent event) {
logs.add(1);
},
),
);
// Only the Service binding handler.
expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA),
false);
expect(logs, <int>[1]);
logs.clear();
// Add a handler.
void handler2(RawKeyEvent event) {
logs.add(2);
}
RawKeyboard.instance.addListener(handler2);
expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA),
false);
expect(logs, <int>[1, 2]);
logs.clear();
// Add another handler.
void handler3(RawKeyEvent event) {
logs.add(3);
}
RawKeyboard.instance.addListener(handler3);
expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA),
false);
expect(logs, <int>[1, 2, 3]);
logs.clear();
// Add handler2 again.
RawKeyboard.instance.addListener(handler2);
expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA),
false);
expect(logs, <int>[1, 2, 3, 2]);
logs.clear();
// Remove handler2 once.
RawKeyboard.instance.removeListener(handler2);
expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA),
false);
expect(logs, <int>[1, 3, 2]);
logs.clear();
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Exceptions from RawKeyboard listeners are caught and reported', (WidgetTester tester) async {
void throwingListener(RawKeyEvent event) {
throw 1;
}
// When the listener throws an error...
RawKeyboard.instance.addListener(throwingListener);
// Simulate a key down event.
FlutterErrorDetails? record;
await _runWhileOverridingOnError(
() => simulateKeyDownEvent(LogicalKeyboardKey.keyA),
onError: (FlutterErrorDetails details) {
record = details;
}
);
// ... the error should be caught.
expect(record, isNotNull);
expect(record!.exception, 1);
final Map<String, DiagnosticsNode> infos = _groupDiagnosticsByName(record!.informationCollector!());
expect(infos['Event'], isA<DiagnosticsProperty<RawKeyEvent>>());
// But the exception should not interrupt recording the state.
// Now the key handler no longer throws an error.
RawKeyboard.instance.removeListener(throwingListener);
record = null;
// Simulate a key up event.
await _runWhileOverridingOnError(
() => simulateKeyUpEvent(LogicalKeyboardKey.keyA),
onError: (FlutterErrorDetails details) {
record = details;
}
);
// If the previous state (key down) wasn't recorded, this key up event will
// trigger assertions.
expect(record, isNull);
});
});
group('RawKeyEventDataAndroid', () {
const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{
RawKeyEventDataAndroid.modifierAlt | RawKeyEventDataAndroid.modifierLeftAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left),
RawKeyEventDataAndroid.modifierAlt | RawKeyEventDataAndroid.modifierRightAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right),
RawKeyEventDataAndroid.modifierShift | RawKeyEventDataAndroid.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left),
RawKeyEventDataAndroid.modifierShift | RawKeyEventDataAndroid.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right),
RawKeyEventDataAndroid.modifierSym: _ModifierCheck(ModifierKey.symbolModifier, KeyboardSide.all),
RawKeyEventDataAndroid.modifierFunction: _ModifierCheck(ModifierKey.functionModifier, KeyboardSide.all),
RawKeyEventDataAndroid.modifierControl | RawKeyEventDataAndroid.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left),
RawKeyEventDataAndroid.modifierControl | RawKeyEventDataAndroid.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right),
RawKeyEventDataAndroid.modifierMeta | RawKeyEventDataAndroid.modifierLeftMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left),
RawKeyEventDataAndroid.modifierMeta | RawKeyEventDataAndroid.modifierRightMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right),
RawKeyEventDataAndroid.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all),
RawKeyEventDataAndroid.modifierNumLock: _ModifierCheck(ModifierKey.numLockModifier, KeyboardSide.all),
RawKeyEventDataAndroid.modifierScrollLock: _ModifierCheck(ModifierKey.scrollLockModifier, KeyboardSide.all),
};
test('modifier keys are recognized individually', () {
for (final int modifier in modifierTests.keys) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 0x04,
'plainCodePoint': 0x64,
'codePoint': 0x44,
'scanCode': 0x20,
'metaState': modifier,
'source': 0x101, // Keyboard source.
'deviceId': 1,
});
final RawKeyEventDataAndroid data = event.data as RawKeyEventDataAndroid;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: "$key should be pressed with metaState $modifier, but isn't.",
);
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier.',
);
}
}
}
});
test('modifier keys are recognized when combined', () {
for (final int modifier in modifierTests.keys) {
if (modifier == RawKeyEventDataAndroid.modifierFunction) {
// No need to combine function key with itself.
continue;
}
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 0x04,
'plainCodePoint': 0x64,
'codePoint': 0x44,
'scanCode': 0x20,
'metaState': modifier | RawKeyEventDataAndroid.modifierFunction,
'source': 0x101, // Keyboard source.
'deviceId': 1,
});
final RawKeyEventDataAndroid data = event.data as RawKeyEventDataAndroid;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key || key == ModifierKey.functionModifier) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: '$key should be pressed with metaState $modifier '
"and additional key ${RawKeyEventDataAndroid.modifierFunction}, but isn't.",
);
if (key != ModifierKey.functionModifier) {
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(data.getModifierSide(key), equals(KeyboardSide.all));
}
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier '
'and additional key ${RawKeyEventDataAndroid.modifierFunction}.',
);
}
}
}
});
test('Printable keyboard keys are correctly translated', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 29,
'plainCodePoint': 'a'.codeUnitAt(0),
'codePoint': 'A'.codeUnitAt(0),
'character': 'A',
'scanCode': 30,
'metaState': 0x0,
'source': 0x101, // Keyboard source.
'deviceId': 1,
});
final RawKeyEventDataAndroid data = keyAEvent.data as RawKeyEventDataAndroid;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
expect(data.keyLabel, equals('a'));
});
test('Control keyboard keys are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 111,
'codePoint': 0,
'scanCode': 1,
'metaState': 0x0,
'source': 0x101, // Keyboard source.
'deviceId': 1,
});
final RawKeyEventDataAndroid data = escapeKeyEvent.data as RawKeyEventDataAndroid;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
});
test('Modifier keyboard keys are correctly translated', () {
final RawKeyEvent shiftLeftKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 59,
'plainCodePoint': 0,
'codePoint': 0,
'scanCode': 42,
'metaState': RawKeyEventDataAndroid.modifierLeftShift,
'source': 0x101, // Keyboard source.
'deviceId': 1,
});
final RawKeyEventDataAndroid data = shiftLeftKeyEvent.data as RawKeyEventDataAndroid;
expect(data.physicalKey, equals(PhysicalKeyboardKey.shiftLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.shiftLeft));
expect(data.keyLabel, isEmpty);
});
test('DPAD keys from a joystick give physical key mappings', () {
final RawKeyEvent joystickDpadDown = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 20,
'plainCodePoint': 0,
'codePoint': 0,
'scanCode': 0,
'metaState': 0,
'source': 0x1000010, // Joystick source.
'deviceId': 1,
});
final RawKeyEventDataAndroid data = joystickDpadDown.data as RawKeyEventDataAndroid;
expect(data.physicalKey, equals(PhysicalKeyboardKey.arrowDown));
expect(data.logicalKey, equals(LogicalKeyboardKey.arrowDown));
expect(data.keyLabel, isEmpty);
});
test('Arrow keys from a keyboard give correct physical key mappings', () {
final RawKeyEvent joystickDpadDown = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 20,
'plainCodePoint': 0,
'codePoint': 0,
'scanCode': 108,
'metaState': 0,
'source': 0x101, // Keyboard source.
});
final RawKeyEventDataAndroid data = joystickDpadDown.data as RawKeyEventDataAndroid;
expect(data.physicalKey, equals(PhysicalKeyboardKey.arrowDown));
expect(data.logicalKey, equals(LogicalKeyboardKey.arrowDown));
expect(data.keyLabel, isEmpty);
});
test('DPAD center from a game pad gives physical key mappings', () {
final RawKeyEvent joystickDpadCenter = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 23, // DPAD_CENTER code.
'plainCodePoint': 0,
'codePoint': 0,
'scanCode': 317, // Left side thumb joystick center click button.
'metaState': 0,
'source': 0x501, // Gamepad and keyboard source.
'deviceId': 1,
});
final RawKeyEventDataAndroid data = joystickDpadCenter.data as RawKeyEventDataAndroid;
expect(data.physicalKey, equals(PhysicalKeyboardKey.gameButtonThumbLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.select));
expect(data.keyLabel, isEmpty);
});
test('Device id is read from message', () {
final RawKeyEvent joystickDpadCenter = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 23, // DPAD_CENTER code.
'plainCodePoint': 0,
'codePoint': 0,
'scanCode': 317, // Left side thumb joystick center click button.
'metaState': 0,
'source': 0x501, // Gamepad and keyboard source.
'deviceId': 10,
});
final RawKeyEventDataAndroid data = joystickDpadCenter.data as RawKeyEventDataAndroid;
expect(data.deviceId, equals(10));
});
test('Repeat count is passed correctly', () {
final RawKeyEvent repeatCountEvent = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 29,
'plainCodePoint': 'a'.codeUnitAt(0),
'codePoint': 'A'.codeUnitAt(0),
'character': 'A',
'scanCode': 30,
'metaState': 0x0,
'source': 0x101, // Keyboard source.
'repeatCount': 42,
});
final RawKeyEventDataAndroid data = repeatCountEvent.data as RawKeyEventDataAndroid;
expect(data.repeatCount, equals(42));
});
testWidgets('Key events are responded to correctly.', (WidgetTester tester) async {
expect(RawKeyboard.instance.keysPressed, isEmpty);
// Generate the data for a regular key down event.
final Map<String, dynamic> data = KeyEventSimulator.getKeyData(
LogicalKeyboardKey.keyA,
platform: 'android',
);
Map<String, Object?>? message;
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {
message = SystemChannels.keyEvent.codec.decodeMessage(data) as Map<String, Object?>?;
},
);
expect(message, equals(<String, Object?>{ 'handled': false }));
message = null;
// Set up a widget that will receive focused text events.
final FocusNode focusNode = FocusNode(debugLabel: 'Test Node');
addTearDown(focusNode.dispose);
await tester.pumpWidget(
Focus(
focusNode: focusNode,
onKey: (FocusNode node, RawKeyEvent event) {
return KeyEventResult.handled; // handle all events.
},
child: const SizedBox(),
),
);
focusNode.requestFocus();
await tester.pump();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {
message = SystemChannels.keyEvent.codec.decodeMessage(data) as Map<String, Object?>?;
},
);
expect(message, equals(<String, Object?>{ 'handled': true }));
tester.binding.defaultBinaryMessenger.setMockMessageHandler(SystemChannels.keyEvent.name, null);
});
test('data.toString', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 29,
'plainCodePoint': 97,
'codePoint': 65,
'character': 'A',
'scanCode': 30,
'metaState': 0x0,
'source': 0x101, // Keyboard source.
'repeatCount': 42,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataAndroid#00000('
'flags: 0, codePoint: 65, plainCodePoint: 97, keyCode: 29, '
'scanCode: 30, metaState: 0)'));
});
test('data.equality', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 29,
'plainCodePoint': 97,
'codePoint': 65,
'character': 'A',
'scanCode': 30,
'metaState': 0x0,
'source': 0x101, // Keyboard source.
'repeatCount': 42,
}).data, const RawKeyEventDataAndroid(
codePoint: 65,
plainCodePoint: 97,
keyCode: 29,
scanCode: 30,
));
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'android',
'keyCode': 29,
'plainCodePoint': 97,
'codePoint': 65,
'character': 'A',
'scanCode': 30,
'metaState': 0x0,
'source': 0x101, // Keyboard source.
'repeatCount': 42,
}).data, isNot(equals(const RawKeyEventDataAndroid())));
});
}, skip: isBrowser); // [intended] This is an Android-specific group.
group('RawKeyEventDataFuchsia', () {
const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{
RawKeyEventDataFuchsia.modifierAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.any),
RawKeyEventDataFuchsia.modifierLeftAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left),
RawKeyEventDataFuchsia.modifierRightAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right),
RawKeyEventDataFuchsia.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.any),
RawKeyEventDataFuchsia.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left),
RawKeyEventDataFuchsia.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right),
RawKeyEventDataFuchsia.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.any),
RawKeyEventDataFuchsia.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left),
RawKeyEventDataFuchsia.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right),
RawKeyEventDataFuchsia.modifierMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.any),
RawKeyEventDataFuchsia.modifierLeftMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left),
RawKeyEventDataFuchsia.modifierRightMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right),
RawKeyEventDataFuchsia.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.any),
};
test('modifier keys are recognized individually', () {
for (final int modifier in modifierTests.keys) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'fuchsia',
'hidUsage': 0x04,
'codePoint': 0x64,
'modifiers': modifier,
});
final RawKeyEventDataFuchsia data = event.data as RawKeyEventDataFuchsia;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: "$key should be pressed with metaState $modifier, but isn't.",
);
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier.',
);
}
}
}
});
test('modifier keys are recognized when combined', () {
for (final int modifier in modifierTests.keys) {
if (modifier == RawKeyEventDataFuchsia.modifierCapsLock) {
// No need to combine caps lock key with itself.
continue;
}
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'fuchsia',
'hidUsage': 0x04,
'codePoint': 0x64,
'modifiers': modifier | RawKeyEventDataFuchsia.modifierCapsLock,
});
final RawKeyEventDataFuchsia data = event.data as RawKeyEventDataFuchsia;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key || key == ModifierKey.capsLockModifier) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: '$key should be pressed with metaState $modifier '
"and additional key ${RawKeyEventDataFuchsia.modifierCapsLock}, but isn't.",
);
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier '
'and additional key ${RawKeyEventDataFuchsia.modifierCapsLock}.',
);
}
}
}
});
test('Printable keyboard keys are correctly translated', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'fuchsia',
'hidUsage': 0x00070004,
'codePoint': 'a'.codeUnitAt(0),
'character': 'a',
});
final RawKeyEventDataFuchsia data = keyAEvent.data as RawKeyEventDataFuchsia;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
expect(data.keyLabel, equals('a'));
});
test('Control keyboard keys are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'fuchsia',
'hidUsage': 0x00070029,
});
final RawKeyEventDataFuchsia data = escapeKeyEvent.data as RawKeyEventDataFuchsia;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
});
test('Modifier keyboard keys are correctly translated', () {
final RawKeyEvent shiftLeftKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'fuchsia',
'hidUsage': 0x000700e1,
});
final RawKeyEventDataFuchsia data = shiftLeftKeyEvent.data as RawKeyEventDataFuchsia;
expect(data.physicalKey, equals(PhysicalKeyboardKey.shiftLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.shiftLeft));
expect(data.keyLabel, isEmpty);
});
test('data.toString', () {
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'fuchsia',
'hidUsage': 0x00070004,
'codePoint': 97,
'character': 'a',
'modifiers': 0x10,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataFuchsia#00000(hidUsage: 458756, codePoint: 97, modifiers: 16)'));
});
test('data.equality', () {
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'fuchsia',
'hidUsage': 0x00070004,
'codePoint': 97,
'character': 'a',
'modifiers': 0x10,
}).data, const RawKeyEventDataFuchsia(
hidUsage: 0x00070004,
codePoint: 97,
modifiers: 0x10,
));
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'fuchsia',
'hidUsage': 0x00070004,
'codePoint': 97,
'character': 'a',
'modifiers': 0x10,
}).data, isNot(equals(const RawKeyEventDataFuchsia())));
});
}, skip: isBrowser); // [intended] This is a Fuchsia-specific group.
group('RawKeyEventDataMacOs', () {
const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{
RawKeyEventDataMacOs.modifierOption | RawKeyEventDataMacOs.modifierLeftOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left),
RawKeyEventDataMacOs.modifierOption | RawKeyEventDataMacOs.modifierRightOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right),
RawKeyEventDataMacOs.modifierShift | RawKeyEventDataMacOs.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left),
RawKeyEventDataMacOs.modifierShift | RawKeyEventDataMacOs.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right),
RawKeyEventDataMacOs.modifierControl | RawKeyEventDataMacOs.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left),
RawKeyEventDataMacOs.modifierControl | RawKeyEventDataMacOs.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right),
RawKeyEventDataMacOs.modifierCommand | RawKeyEventDataMacOs.modifierLeftCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left),
RawKeyEventDataMacOs.modifierCommand | RawKeyEventDataMacOs.modifierRightCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right),
RawKeyEventDataMacOs.modifierOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.all),
RawKeyEventDataMacOs.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all),
RawKeyEventDataMacOs.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all),
RawKeyEventDataMacOs.modifierCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.all),
RawKeyEventDataMacOs.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all),
};
test('modifier keys are recognized individually', () {
for (final int modifier in modifierTests.keys) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x04,
'characters': 'a',
'charactersIgnoringModifiers': 'a',
'modifiers': modifier,
});
final RawKeyEventDataMacOs data = event.data as RawKeyEventDataMacOs;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: "$key should be pressed with metaState $modifier, but isn't.",
);
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier.',
);
}
}
}
});
test('modifier keys are recognized when combined', () {
for (final int modifier in modifierTests.keys) {
if (modifier == RawKeyEventDataMacOs.modifierCapsLock) {
// No need to combine caps lock key with itself.
continue;
}
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x04,
'characters': 'a',
'charactersIgnoringModifiers': 'a',
'modifiers': modifier | RawKeyEventDataMacOs.modifierCapsLock,
});
final RawKeyEventDataMacOs data = event.data as RawKeyEventDataMacOs;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key || key == ModifierKey.capsLockModifier) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: '$key should be pressed with metaState $modifier '
"and additional key ${RawKeyEventDataMacOs.modifierCapsLock}, but isn't.",
);
if (key != ModifierKey.capsLockModifier) {
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(data.getModifierSide(key), equals(KeyboardSide.all));
}
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier '
'and additional key ${RawKeyEventDataMacOs.modifierCapsLock}.',
);
}
}
}
});
test('Lower letter keys are correctly translated', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000000,
'characters': 'a',
'charactersIgnoringModifiers': 'a',
'modifiers': 0x0,
});
final RawKeyEventDataMacOs data = keyAEvent.data as RawKeyEventDataMacOs;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
expect(data.keyLabel, equals('a'));
});
test('Upper letter keys are correctly translated', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000000,
'characters': 'A',
'charactersIgnoringModifiers': 'A',
'modifiers': 0x20002,
});
final RawKeyEventDataMacOs data = keyAEvent.data as RawKeyEventDataMacOs;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
expect(data.keyLabel, equals('A'));
});
test('Control keyboard keys are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000035,
'characters': '',
'charactersIgnoringModifiers': '',
'modifiers': 0x0,
});
final RawKeyEventDataMacOs data = escapeKeyEvent.data as RawKeyEventDataMacOs;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
});
test('Modifier keyboard keys are correctly translated', () {
final RawKeyEvent shiftLeftKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000038,
'characters': '',
'charactersIgnoringModifiers': '',
'modifiers': RawKeyEventDataMacOs.modifierLeftShift,
});
final RawKeyEventDataMacOs data = shiftLeftKeyEvent.data as RawKeyEventDataMacOs;
expect(data.physicalKey, equals(PhysicalKeyboardKey.shiftLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.shiftLeft));
expect(data.keyLabel, isEmpty);
});
test('Unprintable keyboard keys are correctly translated', () {
final RawKeyEvent leftArrowKey = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x0000007B,
'characters': '',
'charactersIgnoringModifiers': '', // NSLeftArrowFunctionKey = 0xF702
'modifiers': RawKeyEventDataMacOs.modifierFunction,
});
final RawKeyEventDataMacOs data = leftArrowKey.data as RawKeyEventDataMacOs;
expect(data.physicalKey, equals(PhysicalKeyboardKey.arrowLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.arrowLeft));
});
test('Multi-char keyboard keys are correctly translated', () {
final RawKeyEvent leftArrowKey = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000000,
'characters': 'án',
'charactersIgnoringModifiers': 'án',
'modifiers': 0,
});
final RawKeyEventDataMacOs data = leftArrowKey.data as RawKeyEventDataMacOs;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(const LogicalKeyboardKey(0x1400000000)));
});
test('Prioritize logical key from specifiedLogicalKey', () {
final RawKeyEvent digit1FromFrench = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000012,
'characters': '&',
'charactersIgnoringModifiers': '&',
'specifiedLogicalKey': 0x000000031,
'modifiers': 0,
});
final RawKeyEventDataMacOs data = digit1FromFrench.data as RawKeyEventDataMacOs;
expect(data.physicalKey, equals(PhysicalKeyboardKey.digit1));
expect(data.logicalKey, equals(LogicalKeyboardKey.digit1));
});
test('data.toString', () {
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000060,
'characters': 'A',
'charactersIgnoringModifiers': 'a',
'modifiers': 0x10,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataMacOs#00000(characters: A, charactersIgnoringModifiers: a, keyCode: 96, modifiers: 16)'));
});
test('data.equality', () {
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000060,
'characters': 'A',
'charactersIgnoringModifiers': 'a',
'modifiers': 0x10,
}).data, const RawKeyEventDataMacOs(
keyCode: 0x00000060,
characters: 'A',
charactersIgnoringModifiers: 'a',
modifiers: 0x10,
));
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'macos',
'keyCode': 0x00000060,
'characters': 'A',
'charactersIgnoringModifiers': 'a',
'modifiers': 0x10,
}).data, isNot(equals(const RawKeyEventDataMacOs())));
});
}, skip: isBrowser); // [intended] This is a macOS-specific group.
group('RawKeyEventDataIos', () {
const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{
RawKeyEventDataIos.modifierOption | RawKeyEventDataIos.modifierLeftOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left),
RawKeyEventDataIos.modifierOption | RawKeyEventDataIos.modifierRightOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right),
RawKeyEventDataIos.modifierShift | RawKeyEventDataIos.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left),
RawKeyEventDataIos.modifierShift | RawKeyEventDataIos.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right),
RawKeyEventDataIos.modifierControl | RawKeyEventDataIos.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left),
RawKeyEventDataIos.modifierControl | RawKeyEventDataIos.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right),
RawKeyEventDataIos.modifierCommand | RawKeyEventDataIos.modifierLeftCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left),
RawKeyEventDataIos.modifierCommand | RawKeyEventDataIos.modifierRightCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right),
RawKeyEventDataIos.modifierOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.all),
RawKeyEventDataIos.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all),
RawKeyEventDataIos.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all),
RawKeyEventDataIos.modifierCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.all),
RawKeyEventDataIos.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all),
};
test('modifier keys are recognized individually', () {
for (final int modifier in modifierTests.keys) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x04,
'characters': 'a',
'charactersIgnoringModifiers': 'a',
'modifiers': modifier,
});
final RawKeyEventDataIos data = event.data as RawKeyEventDataIos;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: "$key should be pressed with metaState $modifier, but isn't.",
);
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier.',
);
}
}
}
});
test('modifier keys are recognized when combined', () {
for (final int modifier in modifierTests.keys) {
if (modifier == RawKeyEventDataIos.modifierCapsLock) {
// No need to combine caps lock key with itself.
continue;
}
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x04,
'characters': 'a',
'charactersIgnoringModifiers': 'a',
'modifiers': modifier | RawKeyEventDataIos.modifierCapsLock,
});
final RawKeyEventDataIos data = event.data as RawKeyEventDataIos;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key || key == ModifierKey.capsLockModifier) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: '$key should be pressed with metaState $modifier '
"and additional key ${RawKeyEventDataIos.modifierCapsLock}, but isn't.",
);
if (key != ModifierKey.capsLockModifier) {
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(data.getModifierSide(key), equals(KeyboardSide.all));
}
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier '
'and additional key ${RawKeyEventDataIos.modifierCapsLock}.',
);
}
}
}
});
test('Printable keyboard keys are correctly translated', () {
const String unmodifiedCharacter = 'a';
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x00000004,
'characters': 'a',
'charactersIgnoringModifiers': unmodifiedCharacter,
'modifiers': 0x0,
});
final RawKeyEventDataIos data = keyAEvent.data as RawKeyEventDataIos;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
expect(data.keyLabel, equals('a'));
});
test('Control keyboard keys are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x00000029,
'characters': '',
'charactersIgnoringModifiers': '',
'modifiers': 0x0,
});
final RawKeyEventDataIos data = escapeKeyEvent.data as RawKeyEventDataIos;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
});
test('Modifier keyboard keys are correctly translated', () {
final RawKeyEvent shiftLeftKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x000000e1,
'characters': '',
'charactersIgnoringModifiers': '',
'modifiers': RawKeyEventDataIos.modifierLeftShift,
});
final RawKeyEventDataIos data = shiftLeftKeyEvent.data as RawKeyEventDataIos;
expect(data.physicalKey, equals(PhysicalKeyboardKey.shiftLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.shiftLeft));
expect(data.keyLabel, isEmpty);
});
test('Unprintable keyboard keys are correctly translated', () {
final RawKeyEvent leftArrowKey = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x00000050,
'characters': '',
'charactersIgnoringModifiers': 'UIKeyInputLeftArrow',
'modifiers': RawKeyEventDataIos.modifierFunction,
});
final RawKeyEventDataIos data = leftArrowKey.data as RawKeyEventDataIos;
expect(data.physicalKey, equals(PhysicalKeyboardKey.arrowLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.arrowLeft));
});
test('data.toString', () {
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x00000004,
'characters': 'A',
'charactersIgnoringModifiers': 'a',
'modifiers': 0x10,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataIos#00000(characters: A, charactersIgnoringModifiers: a, keyCode: 4, modifiers: 16)'));
});
test('data.equality', () {
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x00000004,
'characters': 'A',
'charactersIgnoringModifiers': 'a',
'modifiers': 0x10,
}).data, const RawKeyEventDataIos(
keyCode: 0x00000004,
characters: 'A',
charactersIgnoringModifiers: 'a',
modifiers: 0x10,
));
expect(RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'ios',
'keyCode': 0x00000004,
'characters': 'A',
'charactersIgnoringModifiers': 'a',
'modifiers': 0x10,
}).data, isNot(equals(const RawKeyEventDataIos())));
});
}, skip: isBrowser); // [intended] This is an iOS-specific group.
group('RawKeyEventDataWindows', () {
const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{
RawKeyEventDataWindows.modifierLeftAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left),
RawKeyEventDataWindows.modifierRightAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right),
RawKeyEventDataWindows.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left),
RawKeyEventDataWindows.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right),
RawKeyEventDataWindows.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left),
RawKeyEventDataWindows.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right),
RawKeyEventDataWindows.modifierLeftMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left),
RawKeyEventDataWindows.modifierRightMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right),
RawKeyEventDataWindows.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all),
RawKeyEventDataWindows.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all),
RawKeyEventDataWindows.modifierAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.all),
RawKeyEventDataWindows.modifierCaps: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all),
RawKeyEventDataWindows.modifierNumLock: _ModifierCheck(ModifierKey.numLockModifier, KeyboardSide.all),
RawKeyEventDataWindows.modifierScrollLock: _ModifierCheck(ModifierKey.scrollLockModifier, KeyboardSide.all),
};
test('modifier keys are recognized individually', () {
for (final int modifier in modifierTests.keys) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 0x04,
'characterCodePoint': 0,
'scanCode': 0x04,
'modifiers': modifier,
});
final RawKeyEventDataWindows data = event.data as RawKeyEventDataWindows;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: "$key should be pressed with modifier $modifier, but isn't.",
);
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier.',
);
}
}
}
});
test('modifier keys are recognized when combined', () {
for (final int modifier in modifierTests.keys) {
if (modifier == RawKeyEventDataWindows.modifierCaps) {
// No need to combine caps lock key with itself.
continue;
}
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, dynamic>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 0x04,
'characterCodePoint': 0,
'scanCode': 0x04,
'modifiers': modifier | RawKeyEventDataWindows.modifierCaps,
});
final RawKeyEventDataWindows data = event.data as RawKeyEventDataWindows;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key || key == ModifierKey.capsLockModifier) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: '$key should be pressed with metaState $modifier '
"and additional key ${RawKeyEventDataWindows.modifierCaps}, but isn't.",
);
if (key != ModifierKey.capsLockModifier) {
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(data.getModifierSide(key), equals(KeyboardSide.all));
}
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier '
'and additional key ${RawKeyEventDataWindows.modifierCaps}.',
);
}
}
}
});
test('Printable keyboard keys are correctly translated', () {
const int unmodifiedCharacter = 97; // ASCII value for 'a'.
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 0x00000000,
'characterCodePoint': unmodifiedCharacter,
'scanCode': 0x0000001e,
'modifiers': 0x0,
});
final RawKeyEventDataWindows data = keyAEvent.data as RawKeyEventDataWindows;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
expect(data.keyLabel, equals('a'));
});
test('Control keyboard keys are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 27, // keycode for escape key
'scanCode': 0x00000001, // scanCode for escape key
'characterCodePoint': 0,
'modifiers': 0x0,
});
final RawKeyEventDataWindows data = escapeKeyEvent.data as RawKeyEventDataWindows;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
});
test('Modifier keyboard keys are correctly translated', () {
final RawKeyEvent shiftLeftKeyEvent = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 160, // keyCode for left shift.
'scanCode': 0x0000002a, // scanCode for left shift.
'characterCodePoint': 0,
'modifiers': RawKeyEventDataWindows.modifierLeftShift,
});
final RawKeyEventDataWindows data = shiftLeftKeyEvent.data as RawKeyEventDataWindows;
expect(data.physicalKey, equals(PhysicalKeyboardKey.shiftLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.shiftLeft));
expect(data.keyLabel, isEmpty);
});
test('Unprintable keyboard keys are correctly translated', () {
final RawKeyEvent leftArrowKey = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 37, // keyCode for left arrow.
'scanCode': 0x0000e04b, // scanCode for left arrow.
'characterCodePoint': 0,
'modifiers': 0,
});
final RawKeyEventDataWindows data = leftArrowKey.data as RawKeyEventDataWindows;
expect(data.physicalKey, equals(PhysicalKeyboardKey.arrowLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.arrowLeft));
});
testWidgets('Win32 VK_PROCESSKEY events are skipped', (WidgetTester tester) async {
const String platform = 'windows';
bool lastHandled = true;
final List<RawKeyEvent> events = <RawKeyEvent>[];
// Test both code paths: addListener, and FocusNode.onKey.
RawKeyboard.instance.addListener(events.add);
final FocusNode node = FocusNode(
onKey: (_, RawKeyEvent event) {
events.add(event);
return KeyEventResult.ignored;
},
);
addTearDown(node.dispose);
await tester.pumpWidget(RawKeyboardListener(
focusNode: node,
child: Container(),
));
node.requestFocus();
await tester.pumpAndSettle();
// Dispatch an arbitrary key press for the correct transit mode.
await simulateKeyDownEvent(LogicalKeyboardKey.keyA);
await simulateKeyUpEvent(LogicalKeyboardKey.keyA);
expect(events, hasLength(4));
events.clear();
// Simulate raw events because VK_PROCESSKEY does not exist in the key mapping.
Future<void> simulateKeyEventMessage(String type, int keyCode, int scanCode) {
return tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(<String, Object?>{
'type': type,
'keymap': platform,
'keyCode': keyCode,
'scanCode': scanCode,
'modifiers': 0,
}),
(ByteData? data) {
final Map<String, Object?> decoded = SystemChannels.keyEvent.codec.decodeMessage(data)! as Map<String, Object?>;
lastHandled = decoded['handled']! as bool;
},
);
}
await simulateKeyEventMessage('keydown', 229, 30);
expect(events, isEmpty);
expect(lastHandled, true);
expect(RawKeyboard.instance.keysPressed, isEmpty);
await simulateKeyEventMessage('keyup', 65, 30);
expect(events, isEmpty);
expect(lastHandled, true);
expect(RawKeyboard.instance.keysPressed, isEmpty);
}, variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData());
test('data.toString', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 0x00000010,
'characterCodePoint': 10,
'scanCode': 0x0000001e,
'modifiers': 0x20,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataWindows#00000(keyCode: 16, scanCode: 30, characterCodePoint: 10, modifiers: 32)'));
});
test('data.equality', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 0x00000010,
'characterCodePoint': 10,
'scanCode': 0x0000001e,
'modifiers': 0x20,
}).data, const RawKeyEventDataWindows(
keyCode: 0x00000010,
scanCode: 0x1e,
modifiers: 0x20,
characterCodePoint: 10,
));
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'windows',
'keyCode': 0x00000010,
'characterCodePoint': 10,
'scanCode': 0x0000001e,
'modifiers': 0x20,
}).data, isNot(equals(const RawKeyEventDataWindows())));
});
}, skip: isBrowser); // [intended] This is a Windows-specific group.
group('RawKeyEventDataLinux-GLFW', () {
const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{
GLFWKeyHelper.modifierAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.all),
GLFWKeyHelper.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all),
GLFWKeyHelper.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all),
GLFWKeyHelper.modifierMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.all),
GLFWKeyHelper.modifierNumericPad: _ModifierCheck(ModifierKey.numLockModifier, KeyboardSide.all),
GLFWKeyHelper.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all),
};
// How modifiers are interpreted depends upon the keyCode for GLFW.
int keyCodeForModifier(int modifier, {required bool isLeft}) {
return switch (modifier) {
GLFWKeyHelper.modifierAlt => isLeft ? 342 : 346,
GLFWKeyHelper.modifierShift => isLeft ? 340 : 344,
GLFWKeyHelper.modifierControl => isLeft ? 341 : 345,
GLFWKeyHelper.modifierMeta => isLeft ? 343 : 347,
GLFWKeyHelper.modifierNumericPad => 282,
GLFWKeyHelper.modifierCapsLock => 280,
_ => 65, // keyA
};
}
test('modifier keys are recognized individually', () {
for (final int modifier in modifierTests.keys) {
for (final bool isDown in <bool>[true, false]) {
for (final bool isLeft in <bool>[true, false]) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, Object?>{
'type': isDown ? 'keydown' : 'keyup',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': keyCodeForModifier(modifier, isLeft: isLeft),
'scanCode': 0x00000026,
'unicodeScalarValues': 97,
// GLFW modifiers don't include the current key event.
'modifiers': isDown ? 0 : modifier,
});
final RawKeyEventDataLinux data = event.data as RawKeyEventDataLinux;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isDown ? isTrue : isFalse,
reason: "${isLeft ? 'left' : 'right'} $key ${isDown ? 'should' : 'should not'} be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but isn't.",
);
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: "${isLeft ? 'left' : 'right'} $key should not be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but is.",
);
}
}
}
}
}
});
test('modifier keys are recognized when combined', () {
for (final int modifier in modifierTests.keys) {
if (modifier == GLFWKeyHelper.modifierControl) {
// No need to combine CTRL key with itself.
continue;
}
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 97,
'modifiers': modifier | GLFWKeyHelper.modifierControl,
});
final RawKeyEventDataLinux data = event.data as RawKeyEventDataLinux;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key || key == ModifierKey.controlModifier) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: '$key should be pressed with metaState $modifier '
"and additional key ${GLFWKeyHelper.modifierControl}, but isn't.",
);
if (key != ModifierKey.controlModifier) {
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(data.getModifierSide(key), equals(KeyboardSide.all));
}
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier '
'and additional key ${GLFWKeyHelper.modifierControl}.',
);
}
}
}
});
test('Printable keyboard keys are correctly translated', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 113,
'modifiers': 0x0,
});
final RawKeyEventDataLinux data = keyAEvent.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyQ));
expect(data.keyLabel, equals('q'));
});
test('Code points with two Unicode scalar values are allowed', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 0x10FFFF,
'modifiers': 0x0,
});
final RawKeyEventDataLinux data = keyAEvent.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey.keyId, equals(0x10FFFF));
expect(data.keyLabel, equals(''));
});
test('Code points with more than three Unicode scalar values are not allowed', () {
// |keyCode| and |scanCode| are arbitrary values. This test should fail due to an invalid |unicodeScalarValues|.
void createFailingKey() {
RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 0x1F00000000,
'modifiers': 0x0,
});
}
expect(() => createFailingKey(), throwsAssertionError);
});
test('Control keyboard keys are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 256,
'scanCode': 0x00000009,
'unicodeScalarValues': 0,
'modifiers': 0x0,
});
final RawKeyEventDataLinux data = escapeKeyEvent.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
});
test('Modifier keyboard keys are correctly translated', () {
final RawKeyEvent shiftLeftKeyEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 340,
'scanCode': 0x00000032,
'unicodeScalarValues': 0,
});
final RawKeyEventDataLinux data = shiftLeftKeyEvent.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.shiftLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.shiftLeft));
expect(data.keyLabel, isEmpty);
});
test('data.toString', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 0x10FFFF,
'modifiers': 0x10,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataLinux#00000(toolkit: GLFW, unicodeScalarValues: 1114111, scanCode: 38, keyCode: 65, modifiers: 16, isDown: true)'));
});
test('data.equality', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 0x10FFFF,
'modifiers': 0x10,
}).data, RawKeyEventDataLinux(
keyHelper: KeyHelper('glfw'),
unicodeScalarValues: 0x10FFFF,
keyCode: 65,
scanCode: 0x26,
modifiers: 0x10,
isDown: true,
));
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'glfw',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 0x10FFFF,
'modifiers': 0x10,
}).data, isNot(equals(RawKeyEventDataLinux(
keyHelper: KeyHelper('glfw'), isDown: true)),
));
});
}, skip: isBrowser); // [intended] This is a GLFW-specific group.
group('RawKeyEventDataLinux-GTK', () {
const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{
GtkKeyHelper.modifierMod1: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.all),
GtkKeyHelper.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all),
GtkKeyHelper.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all),
GtkKeyHelper.modifierMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.all),
GtkKeyHelper.modifierMod2: _ModifierCheck(ModifierKey.numLockModifier, KeyboardSide.all),
GtkKeyHelper.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all),
};
// How modifiers are interpreted depends upon the keyCode for GTK.
int keyCodeForModifier(int modifier, {required bool isLeft}) {
return switch (modifier) {
GtkKeyHelper.modifierShift => isLeft ? 65505 : 65506,
GtkKeyHelper.modifierControl => isLeft ? 65507 : 65508,
GtkKeyHelper.modifierMeta => isLeft ? 65515 : 65516,
GtkKeyHelper.modifierMod1 => 65513,
GtkKeyHelper.modifierMod2 => 65407,
GtkKeyHelper.modifierCapsLock => 65509,
_ => 65, // keyA
};
}
test('modifier keys are recognized individually', () {
for (final int modifier in modifierTests.keys) {
for (final bool isDown in <bool>[true, false]) {
for (final bool isLeft in <bool>[true, false]) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, Object?>{
'type': isDown ? 'keydown' : 'keyup',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': keyCodeForModifier(modifier, isLeft: isLeft),
'scanCode': 0x00000026,
'unicodeScalarValues': 97,
// GTK modifiers don't include the current key event.
'modifiers': isDown ? 0 : modifier,
});
final RawKeyEventDataLinux data = event.data as RawKeyEventDataLinux;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isDown ? isTrue : isFalse,
reason: "${isLeft ? 'left' : 'right'} $key ${isDown ? 'should' : 'should not'} be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but isn't.",
);
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: "${isLeft ? 'left' : 'right'} $key should not be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but is.",
);
}
}
}
}
}
});
test('modifier keys are recognized when combined', () {
for (final int modifier in modifierTests.keys) {
if (modifier == GtkKeyHelper.modifierControl) {
// No need to combine CTRL key with itself.
continue;
}
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 97,
'modifiers': modifier | GtkKeyHelper.modifierControl,
});
final RawKeyEventDataLinux data = event.data as RawKeyEventDataLinux;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier]!.key == key || key == ModifierKey.controlModifier) {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isTrue,
reason: '$key should be pressed with metaState $modifier '
"and additional key ${GtkKeyHelper.modifierControl}, but isn't.",
);
if (key != ModifierKey.controlModifier) {
expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side));
} else {
expect(data.getModifierSide(key), equals(KeyboardSide.all));
}
} else {
expect(
data.isModifierPressed(key, side: modifierTests[modifier]!.side),
isFalse,
reason: '$key should not be pressed with metaState $modifier '
'and additional key ${GtkKeyHelper.modifierControl}.',
);
}
}
}
});
test('Printable keyboard keys are correctly translated', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 113,
'modifiers': 0x0,
});
final RawKeyEventDataLinux data = keyAEvent.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyQ));
expect(data.keyLabel, equals('q'));
});
test('Code points with two Unicode scalar values are allowed', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 0x10FFFF,
'modifiers': 0x0,
});
final RawKeyEventDataLinux data = keyAEvent.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey.keyId, equals(0x10FFFF));
expect(data.keyLabel, equals(''));
});
test('Code points with more than three Unicode scalar values are not allowed', () {
// |keyCode| and |scanCode| are arbitrary values. This test should fail due to an invalid |unicodeScalarValues|.
void createFailingKey() {
RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 0x1F00000000,
'modifiers': 0x0,
});
}
expect(() => createFailingKey(), throwsAssertionError);
});
test('Control keyboard keys are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65307,
'scanCode': 0x00000009,
'unicodeScalarValues': 0,
'modifiers': 0x0,
});
final RawKeyEventDataLinux data = escapeKeyEvent.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
});
test('Modifier keyboard keys are correctly translated', () {
final RawKeyEvent shiftLeftKeyEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65505,
'scanCode': 0x00000032,
'unicodeScalarValues': 0,
});
final RawKeyEventDataLinux data = shiftLeftKeyEvent.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.shiftLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.shiftLeft));
expect(data.keyLabel, isEmpty);
});
test('Prioritize logical key from specifiedLogicalKey', () {
final RawKeyEvent digit1FromFrench = RawKeyEvent.fromMessage(const <String, dynamic>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 0x6c6,
'scanCode': 0x26,
'unicodeScalarValues': 0x424,
'specifiedLogicalKey': 0x61,
});
final RawKeyEventDataLinux data = digit1FromFrench.data as RawKeyEventDataLinux;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
});
test('data.toString', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 113,
'modifiers': 0x10,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataLinux#00000(toolkit: GTK, unicodeScalarValues: 113, scanCode: 38, keyCode: 65, modifiers: 16, isDown: true)'));
});
test('data.equality', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 113,
'modifiers': 0x10,
}).data, RawKeyEventDataLinux(
keyHelper: KeyHelper('gtk'),
unicodeScalarValues: 113,
keyCode: 65,
scanCode: 0x26,
modifiers: 0x10,
isDown: true,
));
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 113,
'modifiers': 0x10,
}).data, isNot(equals(RawKeyEventDataLinux(
keyHelper: KeyHelper('glfw'),
unicodeScalarValues: 113,
keyCode: 65,
scanCode: 0x26,
modifiers: 0x10,
isDown: true,
))));
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'linux',
'toolkit': 'gtk',
'keyCode': 65,
'scanCode': 0x00000026,
'unicodeScalarValues': 113,
'modifiers': 0x10,
}).data, isNot(equals(RawKeyEventDataLinux(
keyHelper: KeyHelper('gtk'), isDown: true)),
));
});
}, skip: isBrowser); // [intended] This is a GTK-specific group.
group('RawKeyEventDataWeb', () {
const Map<int, ModifierKey> modifierTests = <int, ModifierKey>{
RawKeyEventDataWeb.modifierAlt: ModifierKey.altModifier,
RawKeyEventDataWeb.modifierShift: ModifierKey.shiftModifier,
RawKeyEventDataWeb.modifierControl: ModifierKey.controlModifier,
RawKeyEventDataWeb.modifierMeta: ModifierKey.metaModifier,
RawKeyEventDataWeb.modifierCapsLock: ModifierKey.capsLockModifier,
RawKeyEventDataWeb.modifierNumLock: ModifierKey.numLockModifier,
RawKeyEventDataWeb.modifierScrollLock: ModifierKey.scrollLockModifier,
};
const Map<String, LogicalKeyboardKey> modifierTestsWithNoLocation =
<String, LogicalKeyboardKey>{
'Alt': LogicalKeyboardKey.altLeft,
'Shift': LogicalKeyboardKey.shiftLeft,
'Control': LogicalKeyboardKey.controlLeft,
'Meta': LogicalKeyboardKey.metaLeft,
};
test('modifier keys are recognized individually', () {
for (final int modifier in modifierTests.keys) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'RandomCode',
'metaState': modifier,
});
final RawKeyEventDataWeb data = event.data as RawKeyEventDataWeb;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier] == key) {
expect(
data.isModifierPressed(key),
isTrue,
reason: "$key should be pressed with metaState $modifier, but isn't.",
);
} else {
expect(
data.isModifierPressed(key),
isFalse,
reason: '$key should not be pressed with metaState $modifier.',
);
}
}
}
});
test('modifier keys are recognized when combined', () {
for (final int modifier in modifierTests.keys) {
if (modifier == RawKeyEventDataWeb.modifierMeta) {
// No need to combine meta key with itself.
continue;
}
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'RandomCode',
'metaState': modifier | RawKeyEventDataWeb.modifierMeta,
});
final RawKeyEventDataWeb data = event.data as RawKeyEventDataWeb;
for (final ModifierKey key in ModifierKey.values) {
if (modifierTests[modifier] == key || key == ModifierKey.metaModifier) {
expect(
data.isModifierPressed(key),
isTrue,
reason: '$key should be pressed with metaState $modifier '
"and additional key ${RawKeyEventDataWeb.modifierMeta}, but isn't.",
);
} else {
expect(
data.isModifierPressed(key),
isFalse,
reason: '$key should not be pressed with metaState $modifier '
'and additional key ${RawKeyEventDataWeb.modifierMeta}.',
);
}
}
}
});
test('modifier keys with no location are mapped to left', () {
for (final String modifierKey in modifierTestsWithNoLocation.keys) {
final RawKeyEvent event = RawKeyEvent.fromMessage(<String, Object?>{
'type': 'keydown',
'keymap': 'web',
'key': modifierKey,
'location': 0,
});
final RawKeyEventDataWeb data = event.data as RawKeyEventDataWeb;
expect(data.logicalKey, modifierTestsWithNoLocation[modifierKey]);
}
});
test('Lower letter keys are correctly translated', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'KeyA',
'key': 'a',
'location': 0,
'metaState': 0x0,
'keyCode': 0x41,
});
final RawKeyEventDataWeb data = keyAEvent.data as RawKeyEventDataWeb;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
expect(data.keyLabel, equals('a'));
expect(data.keyCode, equals(0x41));
});
test('Upper letter keys are correctly translated', () {
final RawKeyEvent keyAEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'KeyA',
'key': 'A',
'location': 0,
'metaState': 0x1, // Shift
'keyCode': 0x41,
});
final RawKeyEventDataWeb data = keyAEvent.data as RawKeyEventDataWeb;
expect(data.physicalKey, equals(PhysicalKeyboardKey.keyA));
expect(data.logicalKey, equals(LogicalKeyboardKey.keyA));
expect(data.keyLabel, equals('A'));
expect(data.keyCode, equals(0x41));
});
test('Control keyboard keys are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'Escape',
'key': 'Escape',
'location': 0,
'metaState': 0x0,
'keyCode': 0x1B,
});
final RawKeyEventDataWeb data = escapeKeyEvent.data as RawKeyEventDataWeb;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
expect(data.keyCode, equals(0x1B));
});
test('Modifier keyboard keys are correctly translated', () {
final RawKeyEvent shiftKeyEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'ShiftLeft',
'key': 'Shift',
'location': 1,
'metaState': RawKeyEventDataWeb.modifierShift,
'keyCode': 0x10,
});
final RawKeyEventDataWeb data = shiftKeyEvent.data as RawKeyEventDataWeb;
expect(data.physicalKey, equals(PhysicalKeyboardKey.shiftLeft));
expect(data.logicalKey, equals(LogicalKeyboardKey.shiftLeft));
expect(data.keyLabel, isEmpty);
expect(data.keyCode, equals(0x10));
});
test('Esc keys generated by older browsers are correctly translated', () {
final RawKeyEvent escapeKeyEvent = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'Esc',
'key': 'Esc',
'location': 0,
'metaState': 0x0,
'keyCode': 0x1B,
});
final RawKeyEventDataWeb data = escapeKeyEvent.data as RawKeyEventDataWeb;
expect(data.physicalKey, equals(PhysicalKeyboardKey.escape));
expect(data.logicalKey, equals(LogicalKeyboardKey.escape));
expect(data.keyLabel, isEmpty);
expect(data.keyCode, equals(0x1B));
});
test('Arrow keys from a keyboard give correct physical key mappings', () {
final RawKeyEvent arrowKeyDown = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'ArrowDown',
'key': 'ArrowDown',
'location': 0,
'metaState': 0x0,
'keyCode': 0x28,
});
final RawKeyEventDataWeb data = arrowKeyDown.data as RawKeyEventDataWeb;
expect(data.physicalKey, equals(PhysicalKeyboardKey.arrowDown));
expect(data.logicalKey, equals(LogicalKeyboardKey.arrowDown));
expect(data.keyLabel, isEmpty);
expect(data.keyCode, equals(0x28));
});
test('Unrecognized keys are mapped to Web plane', () {
final RawKeyEvent arrowKeyDown = RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'Unrecog1',
'key': 'Unrecog2',
'location': 0,
'metaState': 0x0,
});
final RawKeyEventDataWeb data = arrowKeyDown.data as RawKeyEventDataWeb;
// This might be easily broken on Web if the code fails to acknowledge
// that JavaScript doesn't handle 64-bit bit-wise operation.
expect(data.physicalKey.usbHidUsage, greaterThan(0x01700000000));
expect(data.physicalKey.usbHidUsage, lessThan(0x01800000000));
expect(data.logicalKey.keyId, greaterThan(0x01700000000));
expect(data.logicalKey.keyId, lessThan(0x01800000000));
expect(data.keyLabel, isEmpty);
expect(data.keyCode, equals(0));
});
test('data.toString', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'KeyA',
'key': 'a',
'location': 2,
'metaState': 0x10,
'keyCode': 0x41,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataWeb#00000(code: KeyA, key: a, location: 2, metaState: 16, keyCode: 65)'));
// Without location
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'KeyA',
'key': 'a',
'metaState': 0x10,
'keyCode': 0x41,
}).data.toString(), equalsIgnoringHashCodes(
'RawKeyEventDataWeb#00000(code: KeyA, key: a, location: 0, metaState: 16, keyCode: 65)'));
});
test('data.equality', () {
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'KeyA',
'key': 'a',
'location': 2,
'metaState': 0x10,
'keyCode': 0x41,
}).data, const RawKeyEventDataWeb(
key: 'a',
code: 'KeyA',
location: 2,
metaState: 0x10,
keyCode: 0x41
));
expect(RawKeyEvent.fromMessage(const <String, Object?>{
'type': 'keydown',
'keymap': 'web',
'code': 'KeyA',
'key': 'a',
'location': 2,
'metaState': 0x10,
'keyCode': 0x41,
}).data, isNot(equals(const RawKeyEventDataWeb(code: 'KeyA', key: 'a'))));
});
});
}
Future<void> _runWhileOverridingOnError(AsyncCallback body, {required FlutterExceptionHandler onError}) async {
final FlutterExceptionHandler? oldFlutterErrorOnError = FlutterError.onError;
FlutterError.onError = onError;
try {
await body();
} finally {
FlutterError.onError = oldFlutterErrorOnError;
}
}
Map<String, DiagnosticsNode> _groupDiagnosticsByName(Iterable<DiagnosticsNode> infos) {
return Map<String, DiagnosticsNode>.fromIterable(
infos,
key: (Object? node) => (node! as DiagnosticsNode).name ?? '',
);
}
| flutter/packages/flutter/test/services/raw_keyboard_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/raw_keyboard_test.dart",
"repo_id": "flutter",
"token_count": 52499
} | 673 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group(ActionDispatcher, () {
testWidgets('ActionDispatcher invokes actions when asked.', (WidgetTester tester) async {
await tester.pumpWidget(Container());
bool invoked = false;
const ActionDispatcher dispatcher = ActionDispatcher();
final Object? result = dispatcher.invokeAction(
TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
),
const TestIntent(),
);
expect(result, isTrue);
expect(invoked, isTrue);
});
});
group(Actions, () {
Intent? invokedIntent;
Action<Intent>? invokedAction;
ActionDispatcher? invokedDispatcher;
void collect({Action<Intent>? action, Intent? intent, ActionDispatcher? dispatcher}) {
invokedIntent = intent;
invokedAction = action;
invokedDispatcher = dispatcher;
}
void clear() {
invokedIntent = null;
invokedAction = null;
invokedDispatcher = null;
}
setUp(clear);
testWidgets('Actions widget can invoke actions with default dispatcher', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
await tester.pumpWidget(
Actions(
actions: <Type, Action<Intent>>{
TestIntent: TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
),
},
child: Container(key: containerKey),
),
);
await tester.pump();
final Object? result = Actions.invoke(
containerKey.currentContext!,
const TestIntent(),
);
expect(result, isTrue);
expect(invoked, isTrue);
});
testWidgets('Actions widget can invoke actions with default dispatcher and maybeInvoke', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
await tester.pumpWidget(
Actions(
actions: <Type, Action<Intent>>{
TestIntent: TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
),
},
child: Container(key: containerKey),
),
);
await tester.pump();
final Object? result = Actions.maybeInvoke(
containerKey.currentContext!,
const TestIntent(),
);
expect(result, isTrue);
expect(invoked, isTrue);
});
testWidgets('maybeInvoke returns null when no action is found', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
await tester.pumpWidget(
Actions(
actions: <Type, Action<Intent>>{
TestIntent: TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
),
},
child: Container(key: containerKey),
),
);
await tester.pump();
final Object? result = Actions.maybeInvoke(
containerKey.currentContext!,
const DoNothingIntent(),
);
expect(result, isNull);
expect(invoked, isFalse);
});
testWidgets('invoke throws when no action is found', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
await tester.pumpWidget(
Actions(
actions: <Type, Action<Intent>>{
TestIntent: TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
),
},
child: Container(key: containerKey),
),
);
await tester.pump();
final Object? result = Actions.maybeInvoke(
containerKey.currentContext!,
const DoNothingIntent(),
);
expect(result, isNull);
expect(invoked, isFalse);
});
testWidgets('Actions widget can invoke actions with custom dispatcher', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
const TestIntent intent = TestIntent();
final Action<Intent> testAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
);
await tester.pumpWidget(
Actions(
dispatcher: TestDispatcher(postInvoke: collect),
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
child: Container(key: containerKey),
),
);
await tester.pump();
final Object? result = Actions.invoke<TestIntent>(
containerKey.currentContext!,
intent,
);
expect(result, isTrue);
expect(invoked, isTrue);
expect(invokedIntent, equals(intent));
});
testWidgets('Actions can invoke actions in ancestor dispatcher', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
const TestIntent intent = TestIntent();
final Action<Intent> testAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
);
await tester.pumpWidget(
Actions(
dispatcher: TestDispatcher1(postInvoke: collect),
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
child: Actions(
dispatcher: TestDispatcher(postInvoke: collect),
actions: const <Type, Action<Intent>>{},
child: Container(key: containerKey),
),
),
);
await tester.pump();
final Object? result = Actions.invoke<TestIntent>(
containerKey.currentContext!,
intent,
);
expect(result, isTrue);
expect(invoked, isTrue);
expect(invokedIntent, equals(intent));
expect(invokedAction, equals(testAction));
expect(invokedDispatcher.runtimeType, equals(TestDispatcher1));
});
testWidgets("Actions can invoke actions in ancestor dispatcher if a lower one isn't specified", (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
const TestIntent intent = TestIntent();
final Action<Intent> testAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
);
await tester.pumpWidget(
Actions(
dispatcher: TestDispatcher1(postInvoke: collect),
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
child: Actions(
actions: const <Type, Action<Intent>>{},
child: Container(key: containerKey),
),
),
);
await tester.pump();
final Object? result = Actions.invoke<TestIntent>(
containerKey.currentContext!,
intent,
);
expect(result, isTrue);
expect(invoked, isTrue);
expect(invokedIntent, equals(intent));
expect(invokedAction, equals(testAction));
expect(invokedDispatcher.runtimeType, equals(TestDispatcher1));
});
testWidgets('Actions widget can be found with of', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
final ActionDispatcher testDispatcher = TestDispatcher1(postInvoke: collect);
await tester.pumpWidget(
Actions(
dispatcher: testDispatcher,
actions: const <Type, Action<Intent>>{},
child: Container(key: containerKey),
),
);
await tester.pump();
final ActionDispatcher dispatcher = Actions.of(containerKey.currentContext!);
expect(dispatcher, equals(testDispatcher));
});
testWidgets('Action can be found with find', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
final ActionDispatcher testDispatcher = TestDispatcher1(postInvoke: collect);
bool invoked = false;
final TestAction testAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
);
await tester.pumpWidget(
Actions(
dispatcher: testDispatcher,
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
child: Actions(
actions: const <Type, Action<Intent>>{},
child: Container(key: containerKey),
),
),
);
await tester.pump();
expect(Actions.find<TestIntent>(containerKey.currentContext!), equals(testAction));
expect(() => Actions.find<DoNothingIntent>(containerKey.currentContext!), throwsAssertionError);
expect(Actions.maybeFind<DoNothingIntent>(containerKey.currentContext!), isNull);
await tester.pumpWidget(
Actions(
dispatcher: testDispatcher,
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
child: Actions(
actions: const <Type, Action<Intent>>{},
child: Container(key: containerKey),
),
),
);
await tester.pump();
expect(Actions.find<TestIntent>(containerKey.currentContext!), equals(testAction));
expect(() => Actions.find<DoNothingIntent>(containerKey.currentContext!), throwsAssertionError);
expect(Actions.maybeFind<DoNothingIntent>(containerKey.currentContext!), isNull);
});
testWidgets('FocusableActionDetector keeps track of focus and hover even when disabled.', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
const Intent intent = TestIntent();
final FocusNode focusNode = FocusNode(debugLabel: 'Test Node');
final Action<Intent> testAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
);
bool hovering = false;
bool focusing = false;
addTearDown(focusNode.dispose);
Future<void> buildTest(bool enabled) async {
await tester.pumpWidget(
Center(
child: Actions(
dispatcher: TestDispatcher1(postInvoke: collect),
actions: const <Type, Action<Intent>>{},
child: FocusableActionDetector(
enabled: enabled,
focusNode: focusNode,
shortcuts: const <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.enter): intent,
},
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
onShowHoverHighlight: (bool value) => hovering = value,
onShowFocusHighlight: (bool value) => focusing = value,
child: SizedBox(width: 100, height: 100, key: containerKey),
),
),
),
);
return tester.pump();
}
await buildTest(true);
focusNode.requestFocus();
await tester.pump();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byKey(containerKey)));
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
expect(hovering, isTrue);
expect(focusing, isTrue);
expect(invoked, isTrue);
invoked = false;
await buildTest(false);
expect(hovering, isFalse);
expect(focusing, isFalse);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(invoked, isFalse);
await buildTest(true);
expect(focusing, isFalse);
expect(hovering, isTrue);
await buildTest(false);
expect(focusing, isFalse);
expect(hovering, isFalse);
await gesture.moveTo(Offset.zero);
await buildTest(true);
expect(hovering, isFalse);
expect(focusing, isFalse);
});
testWidgets('FocusableActionDetector changes mouse cursor when hovered', (WidgetTester tester) async {
await tester.pumpWidget(
MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: FocusableActionDetector(
mouseCursor: SystemMouseCursors.text,
onShowHoverHighlight: (_) {},
onShowFocusHighlight: (_) {},
child: Container(),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: const Offset(1, 1));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test default
await tester.pumpWidget(
MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: FocusableActionDetector(
onShowHoverHighlight: (_) {},
onShowFocusHighlight: (_) {},
child: Container(),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
});
testWidgets('Actions.invoke returns the value of Action.invoke', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
final Object sentinel = Object();
bool invoked = false;
const TestIntent intent = TestIntent();
final Action<Intent> testAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return sentinel;
},
);
await tester.pumpWidget(
Actions(
dispatcher: TestDispatcher(postInvoke: collect),
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
child: Container(key: containerKey),
),
);
await tester.pump();
final Object? result = Actions.invoke<TestIntent>(
containerKey.currentContext!,
intent,
);
expect(identical(result, sentinel), isTrue);
expect(invoked, isTrue);
});
testWidgets('ContextAction can return null', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
const TestIntent intent = TestIntent();
final TestContextAction testAction = TestContextAction();
await tester.pumpWidget(
Actions(
dispatcher: TestDispatcher1(postInvoke: collect),
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
child: Container(key: containerKey),
),
);
await tester.pump();
final Object? result = Actions.invoke<TestIntent>(
containerKey.currentContext!,
intent,
);
expect(result, isNull);
expect(invokedIntent, equals(intent));
expect(invokedAction, equals(testAction));
expect(invokedDispatcher.runtimeType, equals(TestDispatcher1));
expect(testAction.capturedContexts.single, containerKey.currentContext);
});
testWidgets('Disabled actions stop propagation to an ancestor', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked = false;
const TestIntent intent = TestIntent();
final TestAction enabledTestAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
);
enabledTestAction.enabled = true;
final TestAction disabledTestAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
);
disabledTestAction.enabled = false;
await tester.pumpWidget(
Actions(
dispatcher: TestDispatcher1(postInvoke: collect),
actions: <Type, Action<Intent>>{
TestIntent: enabledTestAction,
},
child: Actions(
dispatcher: TestDispatcher(postInvoke: collect),
actions: <Type, Action<Intent>>{
TestIntent: disabledTestAction,
},
child: Container(key: containerKey),
),
),
);
await tester.pump();
final Object? result = Actions.invoke<TestIntent>(
containerKey.currentContext!,
intent,
);
expect(result, isNull);
expect(invoked, isFalse);
expect(invokedIntent, isNull);
expect(invokedAction, isNull);
expect(invokedDispatcher, isNull);
});
});
group('Listening', () {
testWidgets('can listen to enabled state of Actions', (WidgetTester tester) async {
final GlobalKey containerKey = GlobalKey();
bool invoked1 = false;
bool invoked2 = false;
bool invoked3 = false;
final TestAction action1 = TestAction(
onInvoke: (Intent intent) {
invoked1 = true;
return invoked1;
},
);
final TestAction action2 = TestAction(
onInvoke: (Intent intent) {
invoked2 = true;
return invoked2;
},
);
final TestAction action3 = TestAction(
onInvoke: (Intent intent) {
invoked3 = true;
return invoked3;
},
);
bool enabled1 = true;
action1.addActionListener((Action<Intent> action) => enabled1 = action.isEnabled(const TestIntent()));
action1.enabled = false;
expect(enabled1, isFalse);
bool enabled2 = true;
action2.addActionListener((Action<Intent> action) => enabled2 = action.isEnabled(const SecondTestIntent()));
action2.enabled = false;
expect(enabled2, isFalse);
bool enabled3 = true;
action3.addActionListener((Action<Intent> action) => enabled3 = action.isEnabled(const ThirdTestIntent()));
action3.enabled = false;
expect(enabled3, isFalse);
await tester.pumpWidget(
Actions(
actions: <Type, Action<TestIntent>>{
TestIntent: action1,
SecondTestIntent: action2,
},
child: Actions(
actions: <Type, Action<TestIntent>>{
ThirdTestIntent: action3,
},
child: Container(key: containerKey),
),
),
);
Object? result = Actions.maybeInvoke(
containerKey.currentContext!,
const TestIntent(),
);
expect(enabled1, isFalse);
expect(result, isNull);
expect(invoked1, isFalse);
action1.enabled = true;
result = Actions.invoke(
containerKey.currentContext!,
const TestIntent(),
);
expect(enabled1, isTrue);
expect(result, isTrue);
expect(invoked1, isTrue);
bool? enabledChanged;
await tester.pumpWidget(
Actions(
actions: <Type, Action<Intent>>{
TestIntent: action1,
SecondTestIntent: action2,
},
child: ActionListener(
listener: (Action<Intent> action) => enabledChanged = action.isEnabled(const ThirdTestIntent()),
action: action2,
child: Actions(
actions: <Type, Action<Intent>>{
ThirdTestIntent: action3,
},
child: Container(key: containerKey),
),
),
),
);
await tester.pump();
result = Actions.maybeInvoke<TestIntent>(
containerKey.currentContext!,
const SecondTestIntent(),
);
expect(enabledChanged, isNull);
expect(enabled2, isFalse);
expect(result, isNull);
expect(invoked2, isFalse);
action2.enabled = true;
expect(enabledChanged, isTrue);
result = Actions.invoke<TestIntent>(
containerKey.currentContext!,
const SecondTestIntent(),
);
expect(enabled2, isTrue);
expect(result, isTrue);
expect(invoked2, isTrue);
await tester.pumpWidget(
Actions(
actions: <Type, Action<Intent>>{
TestIntent: action1,
},
child: Actions(
actions: <Type, Action<Intent>>{
ThirdTestIntent: action3,
},
child: Container(key: containerKey),
),
),
);
expect(action1.listeners.length, equals(2));
expect(action2.listeners.length, equals(1));
expect(action3.listeners.length, equals(2));
await tester.pumpWidget(
Actions(
actions: <Type, Action<Intent>>{
TestIntent: action1,
ThirdTestIntent: action3,
},
child: Container(key: containerKey),
),
);
expect(action1.listeners.length, equals(2));
expect(action2.listeners.length, equals(1));
expect(action3.listeners.length, equals(2));
await tester.pumpWidget(
Actions(
actions: <Type, Action<Intent>>{
TestIntent: action1,
},
child: Container(key: containerKey),
),
);
expect(action1.listeners.length, equals(2));
expect(action2.listeners.length, equals(1));
expect(action3.listeners.length, equals(1));
await tester.pumpWidget(Container());
await tester.pump();
expect(action1.listeners.length, equals(1));
expect(action2.listeners.length, equals(1));
expect(action3.listeners.length, equals(1));
});
});
group(FocusableActionDetector, () {
const Intent intent = TestIntent();
late bool invoked;
late bool hovering;
late bool focusing;
late FocusNode focusNode;
late Action<Intent> testAction;
Future<void> pumpTest(
WidgetTester tester, {
bool enabled = true,
bool directional = false,
bool supplyCallbacks = true,
required Key key,
}) async {
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData(
navigationMode: directional ? NavigationMode.directional : NavigationMode.traditional,
),
child: Center(
child: Actions(
dispatcher: const TestDispatcher1(),
actions: const <Type, Action<Intent>>{},
child: FocusableActionDetector(
enabled: enabled,
focusNode: focusNode,
shortcuts: const <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.enter): intent,
},
actions: <Type, Action<Intent>>{
TestIntent: testAction,
},
onShowHoverHighlight: supplyCallbacks ? (bool value) => hovering = value : null,
onShowFocusHighlight: supplyCallbacks ? (bool value) => focusing = value : null,
child: SizedBox(width: 100, height: 100, key: key),
),
),
),
),
);
return tester.pump();
}
setUp(() async {
invoked = false;
hovering = false;
focusing = false;
focusNode = FocusNode(debugLabel: 'Test Node');
testAction = TestAction(
onInvoke: (Intent intent) {
invoked = true;
return invoked;
},
);
});
tearDown(() async {
focusNode.dispose();
});
testWidgets('FocusableActionDetector keeps track of focus and hover even when disabled.', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final GlobalKey containerKey = GlobalKey();
await pumpTest(tester, key: containerKey);
focusNode.requestFocus();
await tester.pump();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byKey(containerKey)));
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
expect(hovering, isTrue);
expect(focusing, isTrue);
expect(invoked, isTrue);
invoked = false;
await pumpTest(tester, enabled: false, key: containerKey);
expect(hovering, isFalse);
expect(focusing, isFalse);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(invoked, isFalse);
await pumpTest(tester, key: containerKey);
expect(focusing, isFalse);
expect(hovering, isTrue);
await pumpTest(tester, enabled: false, key: containerKey);
expect(focusing, isFalse);
expect(hovering, isFalse);
await gesture.moveTo(Offset.zero);
await pumpTest(tester, key: containerKey);
expect(hovering, isFalse);
expect(focusing, isFalse);
});
testWidgets('FocusableActionDetector shows focus highlight appropriately when focused and disabled', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final GlobalKey containerKey = GlobalKey();
await pumpTest(tester, key: containerKey);
await tester.pump();
expect(focusing, isFalse);
await pumpTest(tester, key: containerKey);
focusNode.requestFocus();
await tester.pump();
expect(focusing, isTrue);
focusing = false;
await pumpTest(tester, enabled: false, key: containerKey);
focusNode.requestFocus();
await tester.pump();
expect(focusing, isFalse);
await pumpTest(tester, enabled: false, key: containerKey);
focusNode.requestFocus();
await tester.pump();
expect(focusing, isFalse);
// In directional navigation, focus should show, even if disabled.
await pumpTest(tester, enabled: false, key: containerKey, directional: true);
focusNode.requestFocus();
await tester.pump();
expect(focusing, isTrue);
});
testWidgets('FocusableActionDetector can be used without callbacks', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final GlobalKey containerKey = GlobalKey();
await pumpTest(tester, key: containerKey, supplyCallbacks: false);
focusNode.requestFocus();
await tester.pump();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byKey(containerKey)));
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
expect(hovering, isFalse);
expect(focusing, isFalse);
expect(invoked, isTrue);
invoked = false;
await pumpTest(tester, enabled: false, key: containerKey, supplyCallbacks: false);
expect(hovering, isFalse);
expect(focusing, isFalse);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(invoked, isFalse);
await pumpTest(tester, key: containerKey, supplyCallbacks: false);
expect(focusing, isFalse);
expect(hovering, isFalse);
await pumpTest(tester, enabled: false, key: containerKey, supplyCallbacks: false);
expect(focusing, isFalse);
expect(hovering, isFalse);
await gesture.moveTo(Offset.zero);
await pumpTest(tester, key: containerKey, supplyCallbacks: false);
expect(hovering, isFalse);
expect(focusing, isFalse);
});
testWidgets(
'FocusableActionDetector can prevent its descendants from being focusable',
(WidgetTester tester) async {
final FocusNode buttonNode = FocusNode(debugLabel: 'Test');
addTearDown(buttonNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: FocusableActionDetector(
child: ElevatedButton(
onPressed: () {},
focusNode: buttonNode,
child: const Text('Test'),
),
),
),
);
// Button is focusable
expect(buttonNode.hasFocus, isFalse);
buttonNode.requestFocus();
await tester.pump();
expect(buttonNode.hasFocus, isTrue);
await tester.pumpWidget(
MaterialApp(
home: FocusableActionDetector(
descendantsAreFocusable: false,
child: ElevatedButton(
onPressed: () {},
focusNode: buttonNode,
child: const Text('Test'),
),
),
),
);
// Button is NOT focusable
expect(buttonNode.hasFocus, isFalse);
buttonNode.requestFocus();
await tester.pump();
expect(buttonNode.hasFocus, isFalse);
},
);
testWidgets(
'FocusableActionDetector can prevent its descendants from being traversable',
(WidgetTester tester) async {
final FocusNode buttonNode1 = FocusNode(debugLabel: 'Button Node 1');
final FocusNode buttonNode2 = FocusNode(debugLabel: 'Button Node 2');
final FocusNode skipTraversalNode = FocusNode(skipTraversal: true);
addTearDown(() {
buttonNode1.dispose();
buttonNode2.dispose();
skipTraversalNode.dispose();
});
await tester.pumpWidget(
MaterialApp(
home: FocusableActionDetector(
focusNode: skipTraversalNode,
child: Column(
children: <Widget>[
ElevatedButton(
onPressed: () {},
focusNode: buttonNode1,
child: const Text('Node 1'),
),
ElevatedButton(
onPressed: () {},
focusNode: buttonNode2,
child: const Text('Node 2'),
),
],
),
),
),
);
buttonNode1.requestFocus();
await tester.pump();
expect(buttonNode1.hasFocus, isTrue);
expect(buttonNode2.hasFocus, isFalse);
primaryFocus!.nextFocus();
await tester.pump();
expect(buttonNode1.hasFocus, isFalse);
expect(buttonNode2.hasFocus, isTrue);
await tester.pumpWidget(
MaterialApp(
home: FocusableActionDetector(
focusNode: skipTraversalNode,
descendantsAreTraversable: false,
child: Column(
children: <Widget>[
ElevatedButton(
onPressed: () {},
focusNode: buttonNode1,
child: const Text('Node 1'),
),
ElevatedButton(
onPressed: () {},
focusNode: buttonNode2,
child: const Text('Node 2'),
),
],
),
),
),
);
buttonNode1.requestFocus();
await tester.pump();
expect(buttonNode1.hasFocus, isTrue);
expect(buttonNode2.hasFocus, isFalse);
primaryFocus!.nextFocus();
await tester.pump();
expect(buttonNode1.hasFocus, isFalse);
expect(buttonNode2.hasFocus, isFalse);
},
);
testWidgets('FocusableActionDetector can exclude Focus semantics', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: FocusableActionDetector(
child: Column(
children: <Widget>[
TextButton(
onPressed: () {},
child: const Text('Button 1'),
),
TextButton(
onPressed: () {},
child: const Text('Button 2'),
),
],
),
),
),
);
expect(
tester.getSemantics(find.byType(FocusableActionDetector)),
matchesSemantics(
scopesRoute: true,
children: <Matcher>[
// This semantic is from `Focus` widget under `FocusableActionDetector`.
matchesSemantics(
isFocusable: true,
children: <Matcher>[
matchesSemantics(
hasTapAction: true,
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
label: 'Button 1',
textDirection: TextDirection.ltr,
),
matchesSemantics(
hasTapAction: true,
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
label: 'Button 2',
textDirection: TextDirection.ltr,
),
],
),
],
),
);
// Set `includeFocusSemantics` to false to exclude semantics
// from `Focus` widget under `FocusableActionDetector`.
await tester.pumpWidget(
MaterialApp(
home: FocusableActionDetector(
includeFocusSemantics: false,
child: Column(
children: <Widget>[
TextButton(
onPressed: () {},
child: const Text('Button 1'),
),
TextButton(
onPressed: () {},
child: const Text('Button 2'),
),
],
),
),
),
);
// Semantics from the `Focus` widget will be removed.
expect(
tester.getSemantics(find.byType(FocusableActionDetector)),
matchesSemantics(
scopesRoute: true,
children: <Matcher>[
matchesSemantics(
hasTapAction: true,
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
label: 'Button 1',
textDirection: TextDirection.ltr,
),
matchesSemantics(
hasTapAction: true,
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
label: 'Button 2',
textDirection: TextDirection.ltr,
),
],
),
);
});
});
group('Action subclasses', () {
testWidgets('CallbackAction passes correct intent when invoked.', (WidgetTester tester) async {
late Intent passedIntent;
final TestAction action = TestAction(onInvoke: (Intent intent) {
passedIntent = intent;
return true;
});
const TestIntent intent = TestIntent();
action._testInvoke(intent);
expect(passedIntent, equals(intent));
});
testWidgets('VoidCallbackAction', (WidgetTester tester) async {
bool called = false;
void testCallback() {
called = true;
}
final VoidCallbackAction action = VoidCallbackAction();
final VoidCallbackIntent intent = VoidCallbackIntent(testCallback);
action.invoke(intent);
expect(called, isTrue);
});
testWidgets('Base Action class default toKeyEventResult delegates to consumesKey', (WidgetTester tester) async {
expect(
DefaultToKeyEventResultAction(consumesKey: false).toKeyEventResult(const DefaultToKeyEventResultIntent(), null),
KeyEventResult.skipRemainingHandlers,
);
expect(
DefaultToKeyEventResultAction(consumesKey: true).toKeyEventResult(const DefaultToKeyEventResultIntent(), null),
KeyEventResult.handled,
);
});
});
group('Diagnostics', () {
testWidgets('default Intent debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
// ignore: invalid_use_of_protected_member
const TestIntent().debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) {
return !node.isFiltered(DiagnosticLevel.info);
})
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, isEmpty);
});
testWidgets('default Actions debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
Actions(
actions: const <Type, Action<Intent>>{},
dispatcher: const ActionDispatcher(),
child: Container(),
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) {
return !node.isFiltered(DiagnosticLevel.info);
})
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description.length, equals(2));
expect(
description,
equalsIgnoringHashCodes(<String>[
'dispatcher: ActionDispatcher#00000',
'actions: {}',
]),
);
});
testWidgets('Actions implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
Actions(
key: const ValueKey<String>('foo'),
dispatcher: const ActionDispatcher(),
actions: <Type, Action<Intent>>{
TestIntent: TestAction(onInvoke: (Intent intent) => null),
},
child: Container(key: const ValueKey<String>('baz')),
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) {
return !node.isFiltered(DiagnosticLevel.info);
})
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description.length, equals(2));
expect(
description,
equalsIgnoringHashCodes(<String>[
'dispatcher: ActionDispatcher#00000',
'actions: {TestIntent: TestAction#00000}',
]),
);
});
});
group('Action overriding', () {
final List<String> invocations = <String>[];
BuildContext? invokingContext;
tearDown(() {
invocations.clear();
invokingContext = null;
});
testWidgets('Basic usage', (WidgetTester tester) async {
late BuildContext invokingContext2;
late BuildContext invokingContext3;
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent : Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
invokingContext2 = context2;
return Actions(
actions: <Type, Action<Intent>> {
LogIntent : Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
invokingContext3 = context3;
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
'action1.invokeAsOverride-post-super',
]);
invocations.clear();
// Invoke from a different (higher) context.
Actions.invoke(invokingContext3, LogIntent(log: invocations));
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action2.invoke',
'action1.invokeAsOverride-post-super',
]);
invocations.clear();
// Invoke from a different (higher) context.
Actions.invoke(invokingContext2, LogIntent(log: invocations));
expect(invocations, <String>['action1.invoke']);
});
testWidgets('Does not break after use', (WidgetTester tester) async {
late BuildContext invokingContext2;
late BuildContext invokingContext3;
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
invokingContext2 = context2;
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
invokingContext3 = context3;
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
// Invoke a bunch of times and verify it still produces the same result.
final List<BuildContext> randomContexts = <BuildContext>[
invokingContext!,
invokingContext2,
invokingContext!,
invokingContext3,
invokingContext3,
invokingContext3,
invokingContext2,
];
for (final BuildContext randomContext in randomContexts) {
Actions.invoke(randomContext, LogIntent(log: invocations));
}
invocations.clear();
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
'action1.invokeAsOverride-post-super',
]);
});
testWidgets('Does not override if not overridable', (WidgetTester tester) async {
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> { LogIntent : LogInvocationAction(actionName: 'action2') },
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
]);
});
testWidgets('The final override controls isEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
'action1.invokeAsOverride-post-super',
]);
invocations.clear();
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1', enabled: false), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[]);
});
testWidgets('The override can choose to defer isActionEnabled to the overridable', (WidgetTester tester) async {
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationButDeferIsEnabledAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
// Nothing since the final override defers its isActionEnabled state to action2,
// which is disabled.
expect(invocations, <String>[]);
invocations.clear();
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationButDeferIsEnabledAction(actionName: 'action2'), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3', enabled: false), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
// The final override (action1) is enabled so all 3 actions are enabled.
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
'action1.invokeAsOverride-post-super',
]);
});
testWidgets('Throws on infinite recursions', (WidgetTester tester) async {
late StateSetter setState;
BuildContext? action2LookupContext;
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: StatefulBuilder(
builder: (BuildContext context2, StateSetter stateSetter) {
setState = stateSetter;
return Actions(
actions: <Type, Action<Intent>> {
if (action2LookupContext != null) LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: action2LookupContext!),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
// Let action2 look up its override using a context below itself, so it
// will find action3 as its override.
expect(tester.takeException(), isNull);
setState(() {
action2LookupContext = invokingContext;
});
await tester.pump();
expect(tester.takeException(), isNull);
Object? exception;
try {
Actions.invoke(invokingContext!, LogIntent(log: invocations));
} catch (e) {
exception = e;
}
expect(exception?.toString(), contains('debugAssertIsEnabledMutuallyRecursive'));
});
testWidgets('Throws on invoking invalid override', (WidgetTester tester) async {
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
return Actions(
actions: <Type, Action<Intent>> { LogIntent : TestContextAction() },
child: Builder(
builder: (BuildContext context) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context),
},
child: Builder(
builder: (BuildContext context1) {
invokingContext = context1;
return const SizedBox();
},
),
);
},
),
);
},
),
);
Object? exception;
try {
Actions.invoke(invokingContext!, LogIntent(log: invocations));
} catch (e) {
exception = e;
}
expect(
exception?.toString(),
contains('cannot be handled by an Action of runtime type TestContextAction.'),
);
});
testWidgets('Make an overridable action overridable', (WidgetTester tester) async {
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(
defaultAction: Action<LogIntent>.overridable(
defaultAction: Action<LogIntent>.overridable(
defaultAction: LogInvocationAction(actionName: 'action3'),
context: context1,
),
context: context2,
),
context: context3,
),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
'action1.invokeAsOverride-post-super',
]);
});
testWidgets('Overriding Actions can change the intent', (WidgetTester tester) async {
final List<String> newLogChannel = <String>[];
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: RedirectOutputAction(actionName: 'action2', newLog: newLogChannel), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action1.invokeAsOverride-post-super',
]);
expect(newLogChannel, <String>[
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
]);
});
testWidgets('Override non-context overridable Actions with a ContextAction', (WidgetTester tester) async {
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
// The default Action is a ContextAction subclass.
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationContextAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
'action1.invokeAsOverride-post-super',
]);
// Action1 is a ContextAction and action2 & action3 are not.
// They should not lose information.
expect(LogInvocationContextAction.invokeContext, isNotNull);
expect(LogInvocationContextAction.invokeContext, invokingContext);
});
testWidgets('Override a ContextAction with a regular Action', (WidgetTester tester) async {
await tester.pumpWidget(
Builder(
builder: (BuildContext context1) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1),
},
child: Builder(
builder: (BuildContext context2) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationContextAction(actionName: 'action2', enabled: false), context: context2),
},
child: Builder(
builder: (BuildContext context3) {
return Actions(
actions: <Type, Action<Intent>> {
LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3),
},
child: Builder(
builder: (BuildContext context4) {
invokingContext = context4;
return const SizedBox();
},
),
);
},
),
);
},
),
);
},
),
);
Actions.invoke(invokingContext!, LogIntent(log: invocations));
expect(invocations, <String>[
'action1.invokeAsOverride-pre-super',
'action2.invokeAsOverride-pre-super',
'action3.invoke',
'action2.invokeAsOverride-post-super',
'action1.invokeAsOverride-post-super',
]);
// Action2 is a ContextAction and action1 & action2 are regular actions.
// Invoking action2 from action3 should still supply a non-null
// BuildContext.
expect(LogInvocationContextAction.invokeContext, isNotNull);
expect(LogInvocationContextAction.invokeContext, invokingContext);
});
});
}
typedef PostInvokeCallback = void Function({Action<Intent> action, Intent intent, ActionDispatcher dispatcher});
class TestIntent extends Intent {
const TestIntent();
}
class SecondTestIntent extends TestIntent {
const SecondTestIntent();
}
class ThirdTestIntent extends SecondTestIntent {
const ThirdTestIntent();
}
class TestAction extends CallbackAction<TestIntent> {
TestAction({
required OnInvokeCallback onInvoke,
}) : super(onInvoke: onInvoke);
@override
bool isEnabled(TestIntent intent) => enabled;
bool get enabled => _enabled;
bool _enabled = true;
set enabled(bool value) {
if (_enabled == value) {
return;
}
_enabled = value;
notifyActionListeners();
}
@override
void addActionListener(ActionListenerCallback listener) {
super.addActionListener(listener);
listeners.add(listener);
}
@override
void removeActionListener(ActionListenerCallback listener) {
super.removeActionListener(listener);
listeners.remove(listener);
}
List<ActionListenerCallback> listeners = <ActionListenerCallback>[];
void _testInvoke(TestIntent intent) => invoke(intent);
}
class TestDispatcher extends ActionDispatcher {
const TestDispatcher({this.postInvoke});
final PostInvokeCallback? postInvoke;
@override
Object? invokeAction(Action<Intent> action, Intent intent, [BuildContext? context]) {
final Object? result = super.invokeAction(action, intent, context);
postInvoke?.call(action: action, intent: intent, dispatcher: this);
return result;
}
}
class TestDispatcher1 extends TestDispatcher {
const TestDispatcher1({super.postInvoke});
}
class TestContextAction extends ContextAction<TestIntent> {
List<BuildContext?> capturedContexts = <BuildContext?>[];
@override
void invoke(covariant TestIntent intent, [BuildContext? context]) {
capturedContexts.add(context);
}
}
class LogIntent extends Intent {
const LogIntent({ required this.log });
final List<String> log;
}
class LogInvocationAction extends Action<LogIntent> {
LogInvocationAction({ required this.actionName, this.enabled = true });
final String actionName;
final bool enabled;
@override
bool get isActionEnabled => enabled;
@override
void invoke(LogIntent intent) {
final Action<LogIntent>? callingAction = this.callingAction;
if (callingAction == null) {
intent.log.add('$actionName.invoke');
} else {
intent.log.add('$actionName.invokeAsOverride-pre-super');
callingAction.invoke(intent);
intent.log.add('$actionName.invokeAsOverride-post-super');
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('actionName', actionName));
}
}
class LogInvocationContextAction extends ContextAction<LogIntent> {
LogInvocationContextAction({ required this.actionName, this.enabled = true });
static BuildContext? invokeContext;
final String actionName;
final bool enabled;
@override
bool get isActionEnabled => enabled;
@override
void invoke(LogIntent intent, [BuildContext? context]) {
invokeContext = context;
final Action<LogIntent>? callingAction = this.callingAction;
if (callingAction == null) {
intent.log.add('$actionName.invoke');
} else {
intent.log.add('$actionName.invokeAsOverride-pre-super');
callingAction.invoke(intent);
intent.log.add('$actionName.invokeAsOverride-post-super');
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('actionName', actionName));
}
}
class LogInvocationButDeferIsEnabledAction extends LogInvocationAction {
LogInvocationButDeferIsEnabledAction({ required super.actionName });
// Defer `isActionEnabled` to the overridable action.
@override
bool get isActionEnabled => callingAction?.isActionEnabled ?? false;
}
class RedirectOutputAction extends LogInvocationAction {
RedirectOutputAction({
required super.actionName,
super.enabled,
required this.newLog,
});
final List<String> newLog;
@override
void invoke(LogIntent intent) => super.invoke(LogIntent(log: newLog));
}
class DefaultToKeyEventResultIntent extends Intent {
const DefaultToKeyEventResultIntent();
}
class DefaultToKeyEventResultAction extends Action<DefaultToKeyEventResultIntent> {
DefaultToKeyEventResultAction({
required bool consumesKey
}) : _consumesKey = consumesKey;
final bool _consumesKey;
@override
bool consumesKey(DefaultToKeyEventResultIntent intent) => _consumesKey;
@override
void invoke(DefaultToKeyEventResultIntent intent) {}
}
| flutter/packages/flutter/test/widgets/actions_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/actions_test.dart",
"repo_id": "flutter",
"token_count": 33094
} | 674 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class TestRoute<T> extends PageRoute<T> {
TestRoute({ required this.child, super.settings });
final Widget child;
@override
Duration get transitionDuration => const Duration(milliseconds: 150);
@override
Color? get barrierColor => null;
@override
String? get barrierLabel => null;
@override
bool get maintainState => false;
@override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return child;
}
}
Future<void> pumpApp(WidgetTester tester) async {
await tester.pumpWidget(
WidgetsApp(
color: const Color(0xFF333333),
onGenerateRoute: (RouteSettings settings) {
return TestRoute<void>(settings: settings, child: Container());
},
),
);
}
void main() {
testWidgets('WidgetsApp control test', (WidgetTester tester) async {
await pumpApp(tester);
expect(find.byType(WidgetsApp), findsOneWidget);
expect(find.byType(Navigator), findsOneWidget);
expect(find.byType(PerformanceOverlay), findsNothing);
expect(find.byType(CheckedModeBanner), findsOneWidget);
});
testWidgets('showPerformanceOverlayOverride true', (WidgetTester tester) async {
expect(WidgetsApp.showPerformanceOverlayOverride, false);
WidgetsApp.showPerformanceOverlayOverride = true;
await pumpApp(tester);
expect(find.byType(WidgetsApp), findsOneWidget);
expect(find.byType(Navigator), findsOneWidget);
expect(find.byType(PerformanceOverlay), findsOneWidget);
expect(find.byType(CheckedModeBanner), findsOneWidget);
WidgetsApp.showPerformanceOverlayOverride = false;
}, skip: isBrowser); // TODO(yjbanov): https://github.com/flutter/flutter/issues/52258
testWidgets('showPerformanceOverlayOverride false', (WidgetTester tester) async {
WidgetsApp.showPerformanceOverlayOverride = true;
expect(WidgetsApp.showPerformanceOverlayOverride, true);
WidgetsApp.showPerformanceOverlayOverride = false;
await pumpApp(tester);
expect(find.byType(WidgetsApp), findsOneWidget);
expect(find.byType(Navigator), findsOneWidget);
expect(find.byType(PerformanceOverlay), findsNothing);
expect(find.byType(CheckedModeBanner), findsOneWidget);
});
testWidgets('debugAllowBannerOverride false', (WidgetTester tester) async {
expect(WidgetsApp.showPerformanceOverlayOverride, false);
expect(WidgetsApp.debugAllowBannerOverride, true);
WidgetsApp.debugAllowBannerOverride = false;
await pumpApp(tester);
expect(find.byType(WidgetsApp), findsOneWidget);
expect(find.byType(Navigator), findsOneWidget);
expect(find.byType(PerformanceOverlay), findsNothing);
expect(find.byType(CheckedModeBanner), findsNothing);
WidgetsApp.debugAllowBannerOverride = true; // restore to default value
});
testWidgets('debugAllowBannerOverride true', (WidgetTester tester) async {
WidgetsApp.debugAllowBannerOverride = false;
expect(WidgetsApp.showPerformanceOverlayOverride, false);
expect(WidgetsApp.debugAllowBannerOverride, false);
WidgetsApp.debugAllowBannerOverride = true;
await pumpApp(tester);
expect(find.byType(WidgetsApp), findsOneWidget);
expect(find.byType(Navigator), findsOneWidget);
expect(find.byType(PerformanceOverlay), findsNothing);
expect(find.byType(CheckedModeBanner), findsOneWidget);
});
}
| flutter/packages/flutter/test/widgets/app_overrides_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/app_overrides_test.dart",
"repo_id": "flutter",
"token_count": 1180
} | 675 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:developer' as developer;
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('first frame callback sets the default UserTag', () {
final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();
// TODO(iskakaushik): https://github.com/flutter/flutter/issues/86947
final String userTag = developer.getCurrentTag().label;
final bool isValid = <String>{'Default', 'AppStartUp'}.contains(userTag);
expect(isValid, equals(true));
developer.UserTag('test tag').makeCurrent();
expect(developer.getCurrentTag().label, equals('test tag'));
binding.drawFrame();
// Simulates the engine again.
binding.platformDispatcher.onReportTimings!(<FrameTiming>[]);
expect(developer.getCurrentTag().label, equals('Default'));
});
}
| flutter/packages/flutter/test/widgets/binding_first_frame_developer_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/binding_first_frame_developer_test.dart",
"repo_id": "flutter",
"token_count": 352
} | 676 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final LayerLink link = LayerLink();
testWidgets('Change link during layout', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
Widget build({ LayerLink? linkToUse }) {
return Directionality(
textDirection: TextDirection.ltr,
// The LayoutBuilder forces the CompositedTransformTarget widget to
// access its own size when [RenderObject.debugActiveLayout] is
// non-null.
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Stack(
children: <Widget>[
Positioned(
left: 123.0,
top: 456.0,
child: CompositedTransformTarget(
link: linkToUse ?? link,
child: const SizedBox(height: 10.0, width: 10.0),
),
),
Positioned(
left: 787.0,
top: 343.0,
child: CompositedTransformFollower(
link: linkToUse ?? link,
targetAnchor: Alignment.center,
followerAnchor: Alignment.center,
child: SizedBox(key: key, height: 20.0, width: 20.0),
),
),
],
);
},
),
);
}
await tester.pumpWidget(build());
final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox;
expect(box.localToGlobal(Offset.zero), const Offset(118.0, 451.0));
await tester.pumpWidget(build(linkToUse: LayerLink()));
expect(box.localToGlobal(Offset.zero), const Offset(118.0, 451.0));
});
testWidgets('LeaderLayer should not cause error', (WidgetTester tester) async {
final LayerLink link = LayerLink();
Widget buildWidget({
required double paddingLeft,
Color siblingColor = const Color(0xff000000),
}) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: paddingLeft),
child: CompositedTransformTarget(
link: link,
child: RepaintBoundary(child: ClipRect(child: Container(color: const Color(0x00ff0000)))),
),
),
Positioned.fill(child: RepaintBoundary(child: ColoredBox(color: siblingColor))),
],
),
);
}
await tester.pumpWidget(buildWidget(paddingLeft: 10));
await tester.pumpWidget(buildWidget(paddingLeft: 0));
await tester.pumpWidget(buildWidget(paddingLeft: 0, siblingColor: const Color(0x0000ff00)));
});
group('Composited transforms - only offsets', () {
final GlobalKey key = GlobalKey();
Widget build({ required Alignment targetAlignment, required Alignment followerAlignment }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned(
left: 123.0,
top: 456.0,
child: CompositedTransformTarget(
link: link,
child: const SizedBox(height: 10.0, width: 10.0),
),
),
Positioned(
left: 787.0,
top: 343.0,
child: CompositedTransformFollower(
link: link,
targetAnchor: targetAlignment,
followerAnchor: followerAlignment,
child: SizedBox(key: key, height: 20.0, width: 20.0),
),
),
],
),
);
}
testWidgets('topLeft', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft));
final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox;
expect(box.localToGlobal(Offset.zero), const Offset(123.0, 456.0));
});
testWidgets('center', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.center, followerAlignment: Alignment.center));
final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox;
expect(box.localToGlobal(Offset.zero), const Offset(118.0, 451.0));
});
testWidgets('bottomRight - topRight', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight));
final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox;
expect(box.localToGlobal(Offset.zero), const Offset(113.0, 466.0));
});
});
group('Composited transforms - with rotations', () {
final GlobalKey key1 = GlobalKey();
final GlobalKey key2 = GlobalKey();
Widget build({ required Alignment targetAlignment, required Alignment followerAlignment }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned(
top: 123.0,
left: 456.0,
child: Transform.rotate(
angle: 1.0, // radians
child: CompositedTransformTarget(
link: link,
child: SizedBox(key: key1, width: 80.0, height: 10.0),
),
),
),
Positioned(
top: 787.0,
left: 343.0,
child: Transform.rotate(
angle: -0.3, // radians
child: CompositedTransformFollower(
link: link,
targetAnchor: targetAlignment,
followerAnchor: followerAlignment,
child: SizedBox(key: key2, width: 40.0, height: 20.0),
),
),
),
],
),
);
}
testWidgets('topLeft', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft));
final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox;
final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
final Offset position1 = box1.localToGlobal(Offset.zero);
final Offset position2 = box2.localToGlobal(Offset.zero);
expect(position1, offsetMoreOrLessEquals(position2));
});
testWidgets('center', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.center, followerAlignment: Alignment.center));
final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox;
final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
final Offset position1 = box1.localToGlobal(const Offset(40, 5));
final Offset position2 = box2.localToGlobal(const Offset(20, 10));
expect(position1, offsetMoreOrLessEquals(position2));
});
testWidgets('bottomRight - topRight', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight));
final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox;
final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
final Offset position1 = box1.localToGlobal(const Offset(80, 10));
final Offset position2 = box2.localToGlobal(const Offset(40, 0));
expect(position1, offsetMoreOrLessEquals(position2));
});
});
group('Composited transforms - nested', () {
final GlobalKey key1 = GlobalKey();
final GlobalKey key2 = GlobalKey();
Widget build({ required Alignment targetAlignment, required Alignment followerAlignment }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned(
top: 123.0,
left: 456.0,
child: Transform.rotate(
angle: 1.0, // radians
child: CompositedTransformTarget(
link: link,
child: SizedBox(key: key1, width: 80.0, height: 10.0),
),
),
),
Positioned(
top: 787.0,
left: 343.0,
child: Transform.rotate(
angle: -0.3, // radians
child: Padding(
padding: const EdgeInsets.all(20.0),
child: CompositedTransformFollower(
link: LayerLink(),
child: Transform(
transform: Matrix4.skew(0.9, 1.1),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: CompositedTransformFollower(
link: link,
targetAnchor: targetAlignment,
followerAnchor: followerAlignment,
child: SizedBox(key: key2, width: 40.0, height: 20.0),
),
),
),
),
),
),
),
],
),
);
}
testWidgets('topLeft', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft));
final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox;
final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
final Offset position1 = box1.localToGlobal(Offset.zero);
final Offset position2 = box2.localToGlobal(Offset.zero);
expect(position1, offsetMoreOrLessEquals(position2));
});
testWidgets('center', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.center, followerAlignment: Alignment.center));
final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox;
final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
final Offset position1 = box1.localToGlobal(Alignment.center.alongSize(const Size(80, 10)));
final Offset position2 = box2.localToGlobal(Alignment.center.alongSize(const Size(40, 20)));
expect(position1, offsetMoreOrLessEquals(position2));
});
testWidgets('bottomRight - topRight', (WidgetTester tester) async {
await tester.pumpWidget(build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight));
final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox;
final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
final Offset position1 = box1.localToGlobal(Alignment.bottomRight.alongSize(const Size(80, 10)));
final Offset position2 = box2.localToGlobal(Alignment.topRight.alongSize(const Size(40, 20)));
expect(position1, offsetMoreOrLessEquals(position2));
});
});
group('Composited transforms - hit testing', () {
final GlobalKey key1 = GlobalKey();
final GlobalKey key2 = GlobalKey();
final GlobalKey key3 = GlobalKey();
bool tapped = false;
Widget build({ required Alignment targetAlignment, required Alignment followerAlignment }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned(
left: 123.0,
top: 456.0,
child: CompositedTransformTarget(
link: link,
child: SizedBox(key: key1, height: 10.0, width: 10.0),
),
),
CompositedTransformFollower(
link: link,
child: GestureDetector(
key: key2,
behavior: HitTestBehavior.opaque,
onTap: () { tapped = true; },
child: SizedBox(key: key3, height: 2.0, width: 2.0),
),
),
],
),
);
}
const List<Alignment> alignments = <Alignment>[
Alignment.topLeft, Alignment.topRight,
Alignment.center,
Alignment.bottomLeft, Alignment.bottomRight,
];
setUp(() { tapped = false; });
for (final Alignment targetAlignment in alignments) {
for (final Alignment followerAlignment in alignments) {
testWidgets('$targetAlignment - $followerAlignment', (WidgetTester tester) async{
await tester.pumpWidget(build(targetAlignment: targetAlignment, followerAlignment: followerAlignment));
final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
expect(box2.size, const Size(2.0, 2.0));
expect(tapped, isFalse);
await tester.tap(find.byKey(key3), warnIfMissed: false); // the container itself is transparent to hits
expect(tapped, isTrue);
});
}
}
});
testWidgets('Leader after Follower asserts', (WidgetTester tester) async {
final LayerLink link = LayerLink();
await tester.pumpWidget(
CompositedTransformFollower(
link: link,
child: CompositedTransformTarget(
link: link,
child: const SizedBox(height: 20, width: 20),
),
),
);
expect(
(tester.takeException() as AssertionError).message,
contains('LeaderLayer anchor must come before FollowerLayer in paint order'),
);
});
testWidgets(
'`FollowerLayer` (`CompositedTransformFollower`) has null pointer error when using with some kinds of `Layer`s',
(WidgetTester tester) async {
final LayerLink link = LayerLink();
await tester.pumpWidget(
CompositedTransformTarget(
link: link,
child: CompositedTransformFollower(
link: link,
child: const _CustomWidget(),
),
),
);
});
}
class _CustomWidget extends SingleChildRenderObjectWidget {
const _CustomWidget();
@override
_CustomRenderObject createRenderObject(BuildContext context) => _CustomRenderObject();
@override
void updateRenderObject(BuildContext context, _CustomRenderObject renderObject) {}
}
class _CustomRenderObject extends RenderProxyBox {
_CustomRenderObject({RenderBox? child}) : super(child);
@override
void paint(PaintingContext context, Offset offset) {
if (layer == null) {
layer = _CustomLayer(
computeSomething: _computeSomething,
);
} else {
(layer as _CustomLayer?)?.computeSomething = _computeSomething;
}
context.pushLayer(layer!, super.paint, Offset.zero);
}
void _computeSomething() {
// indeed, use `globalToLocal` to compute some useful data
globalToLocal(Offset.zero);
}
}
class _CustomLayer extends ContainerLayer {
_CustomLayer({required this.computeSomething});
VoidCallback computeSomething;
@override
void addToScene(ui.SceneBuilder builder) {
computeSomething(); // indeed, need to use result of this function
super.addToScene(builder);
}
}
| flutter/packages/flutter/test/widgets/composited_transform_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/composited_transform_test.dart",
"repo_id": "flutter",
"token_count": 6701
} | 677 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can call setState from didUpdateWidget', (WidgetTester tester) async {
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.ltr,
child: WidgetUnderTest(text: 'hello'),
));
expect(find.text('hello'), findsOneWidget);
expect(find.text('world'), findsNothing);
final _WidgetUnderTestState state = tester.state<_WidgetUnderTestState>(find.byType(WidgetUnderTest));
expect(state.setStateCalled, 0);
expect(state.didUpdateWidgetCalled, 0);
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.ltr,
child: WidgetUnderTest(text: 'world'),
));
expect(find.text('world'), findsOneWidget);
expect(find.text('hello'), findsNothing);
expect(state.setStateCalled, 1);
expect(state.didUpdateWidgetCalled, 1);
});
}
class WidgetUnderTest extends StatefulWidget {
const WidgetUnderTest({super.key, required this.text});
final String text;
@override
State<WidgetUnderTest> createState() => _WidgetUnderTestState();
}
class _WidgetUnderTestState extends State<WidgetUnderTest> {
late String text = widget.text;
int setStateCalled = 0;
int didUpdateWidgetCalled = 0;
@override
void didUpdateWidget(WidgetUnderTest oldWidget) {
super.didUpdateWidget(oldWidget);
didUpdateWidgetCalled += 1;
if (oldWidget.text != widget.text) {
// This setState is load bearing for the test.
setState(() {
text = widget.text;
});
}
}
@override
void setState(VoidCallback fn) {
super.setState(fn);
setStateCalled += 1;
}
@override
Widget build(BuildContext context) {
return Text(text);
}
}
| flutter/packages/flutter/test/widgets/did_update_widget_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/did_update_widget_test.dart",
"repo_id": "flutter",
"token_count": 674
} | 678 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('ErrorWidget.builder', (WidgetTester tester) async {
final ErrorWidgetBuilder oldBuilder = ErrorWidget.builder;
ErrorWidget.builder = (FlutterErrorDetails details) {
return const Text('oopsie!', textDirection: TextDirection.ltr);
};
await tester.pumpWidget(
SizedBox(
child: Builder(
builder: (BuildContext context) {
throw 'test';
},
),
),
);
expect(tester.takeException().toString(), 'test');
expect(find.text('oopsie!'), findsOneWidget);
ErrorWidget.builder = oldBuilder;
});
testWidgets('ErrorWidget.builder', (WidgetTester tester) async {
final ErrorWidgetBuilder oldBuilder = ErrorWidget.builder;
ErrorWidget.builder = (FlutterErrorDetails details) {
return ErrorWidget('');
};
await tester.pumpWidget(
SizedBox(
child: Builder(
builder: (BuildContext context) {
throw 'test';
},
),
),
);
expect(tester.takeException().toString(), 'test');
expect(find.byType(ErrorWidget), isNot(paints..paragraph()));
ErrorWidget.builder = oldBuilder;
});
}
| flutter/packages/flutter/test/widgets/error_widget_builder_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/error_widget_builder_test.dart",
"repo_id": "flutter",
"token_count": 544
} | 679 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> scrollAt(Offset position, WidgetTester tester, [Offset offset = const Offset(0.0, 20.0)]) {
final TestPointer testPointer = TestPointer(1, PointerDeviceKind.mouse);
// Create a hover event so that |testPointer| has a location when generating the scroll.
testPointer.hover(position);
return tester.sendEventToBinding(testPointer.scroll(offset));
}
| flutter/packages/flutter/test/widgets/gesture_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/gesture_utils.dart",
"repo_id": "flutter",
"token_count": 188
} | 680 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import '../painting/mocks_for_image_cache.dart';
void main() {
late ImageProvider image;
setUpAll(() async {
image = TestImageProvider(
21,
42,
image: await createTestImage(width: 10, height: 10),
);
});
testWidgets('ImageIcon sizing - no theme, default size', (WidgetTester tester) async {
await tester.pumpWidget(
Center(
child: ImageIcon(image),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon));
expect(renderObject.size, equals(const Size.square(24.0)));
expect(find.byType(Image), findsOneWidget);
});
testWidgets('Icon opacity', (WidgetTester tester) async {
await tester.pumpWidget(
Center(
child: IconTheme(
data: const IconThemeData(opacity: 0.5),
child: ImageIcon(image),
),
),
);
expect(tester.widget<Image>(find.byType(Image)).color!.alpha, equals(128));
});
testWidgets('ImageIcon sizing - no theme, explicit size', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: ImageIcon(
null,
size: 96.0,
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon));
expect(renderObject.size, equals(const Size.square(96.0)));
});
testWidgets('ImageIcon sizing - sized theme', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: IconTheme(
data: IconThemeData(size: 36.0),
child: ImageIcon(null),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon));
expect(renderObject.size, equals(const Size.square(36.0)));
});
testWidgets('ImageIcon sizing - sized theme, explicit size', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: IconTheme(
data: IconThemeData(size: 36.0),
child: ImageIcon(
null,
size: 48.0,
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon));
expect(renderObject.size, equals(const Size.square(48.0)));
});
testWidgets('ImageIcon sizing - sizeless theme, default size', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: IconTheme(
data: IconThemeData(),
child: ImageIcon(null),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon));
expect(renderObject.size, equals(const Size.square(24.0)));
});
testWidgets('ImageIcon has semantics data', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconTheme(
data: IconThemeData(),
child: ImageIcon(null, semanticLabel: 'test'),
),
),
),
);
expect(tester.getSemantics(find.byType(ImageIcon)), matchesSemantics(
label: 'test',
textDirection: TextDirection.ltr,
));
handle.dispose();
});
}
| flutter/packages/flutter/test/widgets/image_icon_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/image_icon_test.dart",
"repo_id": "flutter",
"token_count": 1429
} | 681 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class Leaf extends StatefulWidget {
const Leaf({
super.key,
required this.child,
});
final Widget child;
@override
State<Leaf> createState() => _LeafState();
}
class _LeafState extends State<Leaf> {
bool _keepAlive = false;
void setKeepAlive(bool value) {
setState(() { _keepAlive = value; });
}
@override
Widget build(BuildContext context) {
return KeepAlive(
keepAlive: _keepAlive,
child: widget.child,
);
}
}
List<Widget> generateList(Widget child) {
return List<Widget>.generate(
100,
(int index) => Leaf(
key: GlobalObjectKey<_LeafState>(index),
child: child,
),
growable: false,
);
}
void main() {
test('KeepAlive debugTypicalAncestorWidgetClass', () {
final KeepAlive keepAlive = KeepAlive(keepAlive: false, child: Container());
expect(
keepAlive.debugTypicalAncestorWidgetDescription,
'SliverWithKeepAliveWidget or TwoDimensionalViewport',
);
});
testWidgets('KeepAlive with ListView with itemExtent', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
cacheExtent: 0.0,
addAutomaticKeepAlives: false,
addRepaintBoundaries: false,
addSemanticIndexes: false,
itemExtent: 12.3, // about 50 widgets visible
children: generateList(const Placeholder()),
),
),
);
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
await tester.drag(find.byType(ListView), const Offset(0.0, -300.0)); // about 25 widgets' worth
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
const GlobalObjectKey<_LeafState>(60).currentState!.setKeepAlive(true);
await tester.drag(find.byType(ListView), const Offset(0.0, 300.0)); // back to top
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60)), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
const GlobalObjectKey<_LeafState>(60).currentState!.setKeepAlive(false);
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
});
testWidgets('KeepAlive with ListView without itemExtent', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
cacheExtent: 0.0,
addAutomaticKeepAlives: false,
addRepaintBoundaries: false,
addSemanticIndexes: false,
children: generateList(const SizedBox(height: 12.3, child: Placeholder())), // about 50 widgets visible
),
),
);
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
await tester.drag(find.byType(ListView), const Offset(0.0, -300.0)); // about 25 widgets' worth
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
const GlobalObjectKey<_LeafState>(60).currentState!.setKeepAlive(true);
await tester.drag(find.byType(ListView), const Offset(0.0, 300.0)); // back to top
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60)), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
const GlobalObjectKey<_LeafState>(60).currentState!.setKeepAlive(false);
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
});
testWidgets('KeepAlive with GridView', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GridView.count(
cacheExtent: 0.0,
addAutomaticKeepAlives: false,
addRepaintBoundaries: false,
addSemanticIndexes: false,
crossAxisCount: 2,
childAspectRatio: 400.0 / 24.6, // about 50 widgets visible
children: generateList(const Placeholder()),
),
),
);
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
await tester.drag(find.byType(GridView), const Offset(0.0, -300.0)); // about 25 widgets' worth
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
const GlobalObjectKey<_LeafState>(60).currentState!.setKeepAlive(true);
await tester.drag(find.byType(GridView), const Offset(0.0, 300.0)); // back to top
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60)), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
const GlobalObjectKey<_LeafState>(60).currentState!.setKeepAlive(false);
await tester.pump();
expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(30)), findsOneWidget);
expect(find.byKey(const GlobalObjectKey<_LeafState>(59), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(60), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(61), skipOffstage: false), findsNothing);
expect(find.byKey(const GlobalObjectKey<_LeafState>(90), skipOffstage: false), findsNothing);
});
testWidgets('KeepAlive render tree description', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
addAutomaticKeepAlives: false,
addRepaintBoundaries: false,
addSemanticIndexes: false,
itemExtent: 400.0, // 2 visible children
children: generateList(const Placeholder()),
),
),
);
// The important lines below are the ones marked with "<----"
expect(tester.binding.renderView.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes(
'_ReusableRenderView#00000\n'
' │ debug mode enabled - ${Platform.operatingSystem}\n'
' │ view size: Size(2400.0, 1800.0) (in physical pixels)\n'
' │ device pixel ratio: 3.0 (physical pixels per logical pixel)\n'
' │ configuration: BoxConstraints(w=800.0, h=600.0) at 3.0x (in\n'
' │ logical pixels)\n'
' │\n'
' └─child: RenderRepaintBoundary#00000\n'
' │ needs compositing\n'
' │ parentData: <none>\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ layer: OffsetLayer#00000\n'
' │ size: Size(800.0, 600.0)\n'
' │ metrics: 0.0% useful (1 bad vs 0 good)\n'
' │ diagnosis: insufficient data to draw conclusion (less than five\n'
' │ repaints)\n'
' │\n'
' └─child: RenderCustomPaint#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ painter: null\n'
' │ foregroundPainter:\n'
' │ _GlowingOverscrollIndicatorPainter(_GlowController(color:\n'
' │ Color(0xffffffff), axis: vertical), _GlowController(color:\n'
' │ Color(0xffffffff), axis: vertical))\n'
' │\n'
' └─child: RenderRepaintBoundary#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ layer: OffsetLayer#00000\n'
' │ size: Size(800.0, 600.0)\n'
' │ metrics: 0.0% useful (1 bad vs 0 good)\n'
' │ diagnosis: insufficient data to draw conclusion (less than five\n'
' │ repaints)\n'
' │\n'
' └─child: _RenderScrollSemantics#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ semantics node: SemanticsNode#1\n'
' │ semantic boundary\n'
' │ size: Size(800.0, 600.0)\n'
' │\n'
' └─child: RenderPointerListener#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ behavior: deferToChild\n'
' │ listeners: signal\n'
' │\n'
' └─child: RenderSemanticsGestureHandler#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ behavior: opaque\n'
' │ gestures: vertical scroll\n'
' │\n'
' └─child: RenderPointerListener#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ behavior: opaque\n'
' │ listeners: down, panZoomStart\n'
' │\n'
' └─child: RenderSemanticsAnnotations#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │\n'
' └─child: RenderIgnorePointer#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ ignoring: false\n'
' │ ignoringSemantics: null\n'
' │\n'
' └─child: RenderViewport#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ layer: OffsetLayer#00000\n'
' │ size: Size(800.0, 600.0)\n'
' │ axisDirection: down\n'
' │ crossAxisDirection: right\n'
' │ offset: ScrollPositionWithSingleContext#00000(offset: 0.0, range:\n'
' │ 0.0..39400.0, viewport: 600.0, ScrollableState,\n'
' │ AlwaysScrollableScrollPhysics -> ClampingScrollPhysics ->\n'
' │ RangeMaintainingScrollPhysics, IdleScrollActivity#00000,\n'
' │ ScrollDirection.idle)\n'
' │ anchor: 0.0\n'
' │\n'
' └─center child: RenderSliverPadding#00000 relayoutBoundary=up1\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: 40000.0, paintExtent:\n'
' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true,\n'
' │ cacheExtent: 850.0)\n'
' │ padding: EdgeInsets.zero\n'
' │ textDirection: ltr\n'
' │\n'
' └─child: RenderSliverFixedExtentList#00000 relayoutBoundary=up2\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: 40000.0, paintExtent:\n'
' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true,\n'
' │ cacheExtent: 850.0)\n'
' │ currently live children: 0 to 2\n'
' │\n'
' ├─child with index 0: RenderLimitedBox#00000\n'
' │ │ parentData: index=0; layoutOffset=0.0\n'
' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ │ size: Size(800.0, 400.0)\n'
' │ │ maxWidth: 400.0\n'
' │ │ maxHeight: 400.0\n'
' │ │\n'
' │ └─child: RenderCustomPaint#00000\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ size: Size(800.0, 400.0)\n'
' │ painter: _PlaceholderPainter#00000()\n'
' │ preferredSize: Size(Infinity, Infinity)\n'
' │\n'
' ├─child with index 1: RenderLimitedBox#00000\n' // <----- no dashed line starts here
' │ │ parentData: index=1; layoutOffset=400.0\n'
' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ │ size: Size(800.0, 400.0)\n'
' │ │ maxWidth: 400.0\n'
' │ │ maxHeight: 400.0\n'
' │ │\n'
' │ └─child: RenderCustomPaint#00000\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ size: Size(800.0, 400.0)\n'
' │ painter: _PlaceholderPainter#00000()\n'
' │ preferredSize: Size(Infinity, Infinity)\n'
' │\n'
' └─child with index 2: RenderLimitedBox#00000 NEEDS-PAINT\n'
' │ parentData: index=2; layoutOffset=800.0\n'
' │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ size: Size(800.0, 400.0)\n'
' │ maxWidth: 400.0\n'
' │ maxHeight: 400.0\n'
' │\n'
' └─child: RenderCustomPaint#00000 NEEDS-PAINT\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=800.0, h=400.0)\n'
' size: Size(800.0, 400.0)\n'
' painter: _PlaceholderPainter#00000()\n'
' preferredSize: Size(Infinity, Infinity)\n',
));
const GlobalObjectKey<_LeafState>(0).currentState!.setKeepAlive(true);
await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0));
await tester.pump();
const GlobalObjectKey<_LeafState>(3).currentState!.setKeepAlive(true);
await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0));
await tester.pump();
expect(tester.binding.renderView.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes(
'_ReusableRenderView#00000\n'
' │ debug mode enabled - ${Platform.operatingSystem}\n'
' │ view size: Size(2400.0, 1800.0) (in physical pixels)\n'
' │ device pixel ratio: 3.0 (physical pixels per logical pixel)\n'
' │ configuration: BoxConstraints(w=800.0, h=600.0) at 3.0x (in\n'
' │ logical pixels)\n'
' │\n'
' └─child: RenderRepaintBoundary#00000\n'
' │ needs compositing\n'
' │ parentData: <none>\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ layer: OffsetLayer#00000\n'
' │ size: Size(800.0, 600.0)\n'
' │ metrics: 0.0% useful (1 bad vs 0 good)\n'
' │ diagnosis: insufficient data to draw conclusion (less than five\n'
' │ repaints)\n'
' │\n'
' └─child: RenderCustomPaint#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ painter: null\n'
' │ foregroundPainter:\n'
' │ _GlowingOverscrollIndicatorPainter(_GlowController(color:\n'
' │ Color(0xffffffff), axis: vertical), _GlowController(color:\n'
' │ Color(0xffffffff), axis: vertical))\n'
' │\n'
' └─child: RenderRepaintBoundary#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ layer: OffsetLayer#00000\n'
' │ size: Size(800.0, 600.0)\n'
' │ metrics: 0.0% useful (1 bad vs 0 good)\n'
' │ diagnosis: insufficient data to draw conclusion (less than five\n'
' │ repaints)\n'
' │\n'
' └─child: _RenderScrollSemantics#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ semantics node: SemanticsNode#1\n'
' │ semantic boundary\n'
' │ size: Size(800.0, 600.0)\n'
' │\n'
' └─child: RenderPointerListener#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ behavior: deferToChild\n'
' │ listeners: signal\n'
' │\n'
' └─child: RenderSemanticsGestureHandler#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ behavior: opaque\n'
' │ gestures: vertical scroll\n'
' │\n'
' └─child: RenderPointerListener#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ behavior: opaque\n'
' │ listeners: down, panZoomStart\n'
' │\n'
' └─child: RenderSemanticsAnnotations#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │\n'
' └─child: RenderIgnorePointer#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ ignoring: false\n'
' │ ignoringSemantics: null\n'
' │\n'
' └─child: RenderViewport#00000\n'
' │ needs compositing\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ layer: OffsetLayer#00000\n'
' │ size: Size(800.0, 600.0)\n'
' │ axisDirection: down\n'
' │ crossAxisDirection: right\n'
' │ offset: ScrollPositionWithSingleContext#00000(offset: 2000.0,\n'
' │ range: 0.0..39400.0, viewport: 600.0, ScrollableState,\n'
' │ AlwaysScrollableScrollPhysics -> ClampingScrollPhysics ->\n'
' │ RangeMaintainingScrollPhysics, IdleScrollActivity#00000,\n'
' │ ScrollDirection.idle)\n'
' │ anchor: 0.0\n'
' │\n'
' └─center child: RenderSliverPadding#00000 relayoutBoundary=up1\n'
' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n'
' │ constraints: SliverConstraints(AxisDirection.down,\n'
' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n'
' │ 2000.0, precedingScrollExtent: 0.0, remainingPaintExtent:\n'
' │ 600.0, crossAxisExtent: 800.0, crossAxisDirection:\n'
' │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n'
' │ remainingCacheExtent: 1100.0, cacheOrigin: -250.0)\n'
' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent:\n'
' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true,\n'
' │ cacheExtent: 1100.0)\n'
' │ padding: EdgeInsets.zero\n'
' │ textDirection: ltr\n'
' │\n'
' └─child: RenderSliverFixedExtentList#00000 relayoutBoundary=up2\n'
' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n'
' │ constraints: SliverConstraints(AxisDirection.down,\n'
' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n'
' │ 2000.0, precedingScrollExtent: 0.0, remainingPaintExtent:\n'
' │ 600.0, crossAxisExtent: 800.0, crossAxisDirection:\n'
' │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n'
' │ remainingCacheExtent: 1100.0, cacheOrigin: -250.0)\n'
' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent:\n'
' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true,\n'
' │ cacheExtent: 1100.0)\n'
' │ currently live children: 4 to 7\n'
' │\n'
' ├─child with index 4: RenderLimitedBox#00000 NEEDS-PAINT\n'
' │ │ parentData: index=4; layoutOffset=1600.0\n'
' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ │ size: Size(800.0, 400.0)\n'
' │ │ maxWidth: 400.0\n'
' │ │ maxHeight: 400.0\n'
' │ │\n'
' │ └─child: RenderCustomPaint#00000 NEEDS-PAINT\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ size: Size(800.0, 400.0)\n'
' │ painter: _PlaceholderPainter#00000()\n'
' │ preferredSize: Size(Infinity, Infinity)\n'
' │\n'
' ├─child with index 5: RenderLimitedBox#00000\n' // <----- this is index 5, not 0
' │ │ parentData: index=5; layoutOffset=2000.0\n'
' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ │ size: Size(800.0, 400.0)\n'
' │ │ maxWidth: 400.0\n'
' │ │ maxHeight: 400.0\n'
' │ │\n'
' │ └─child: RenderCustomPaint#00000\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ size: Size(800.0, 400.0)\n'
' │ painter: _PlaceholderPainter#00000()\n'
' │ preferredSize: Size(Infinity, Infinity)\n'
' │\n'
' ├─child with index 6: RenderLimitedBox#00000\n'
' │ │ parentData: index=6; layoutOffset=2400.0\n'
' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ │ size: Size(800.0, 400.0)\n'
' │ │ maxWidth: 400.0\n'
' │ │ maxHeight: 400.0\n'
' │ │\n'
' │ └─child: RenderCustomPaint#00000\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ size: Size(800.0, 400.0)\n'
' │ painter: _PlaceholderPainter#00000()\n'
' │ preferredSize: Size(Infinity, Infinity)\n'
' │\n'
' ├─child with index 7: RenderLimitedBox#00000 NEEDS-PAINT\n'
' ╎ │ parentData: index=7; layoutOffset=2800.0\n'
' ╎ │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' ╎ │ size: Size(800.0, 400.0)\n'
' ╎ │ maxWidth: 400.0\n'
' ╎ │ maxHeight: 400.0\n'
' ╎ │\n'
' ╎ └─child: RenderCustomPaint#00000 NEEDS-PAINT\n'
' ╎ parentData: <none> (can use size)\n'
' ╎ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' ╎ size: Size(800.0, 400.0)\n'
' ╎ painter: _PlaceholderPainter#00000()\n'
' ╎ preferredSize: Size(Infinity, Infinity)\n'
' ╎\n'
' ╎╌child with index 0 (kept alive but not laid out): RenderLimitedBox#00000\n' // <----- this one is index 0 and is marked as being kept alive but not laid out
' ╎ │ parentData: index=0; keepAlive; layoutOffset=0.0\n'
' ╎ │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' ╎ │ size: Size(800.0, 400.0)\n'
' ╎ │ maxWidth: 400.0\n'
' ╎ │ maxHeight: 400.0\n'
' ╎ │\n'
' ╎ └─child: RenderCustomPaint#00000\n'
' ╎ parentData: <none> (can use size)\n'
' ╎ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' ╎ size: Size(800.0, 400.0)\n'
' ╎ painter: _PlaceholderPainter#00000()\n'
' ╎ preferredSize: Size(Infinity, Infinity)\n'
' ╎\n'
' └╌child with index 3 (kept alive but not laid out): RenderLimitedBox#00000\n'
' │ parentData: index=3; keepAlive; layoutOffset=1200.0\n'
' │ constraints: BoxConstraints(w=800.0, h=400.0)\n'
' │ size: Size(800.0, 400.0)\n'
' │ maxWidth: 400.0\n'
' │ maxHeight: 400.0\n'
' │\n'
' └─child: RenderCustomPaint#00000\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=800.0, h=400.0)\n'
' size: Size(800.0, 400.0)\n'
' painter: _PlaceholderPainter#00000()\n'
' preferredSize: Size(Infinity, Infinity)\n',
));
}, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87876
}
| flutter/packages/flutter/test/widgets/keep_alive_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/keep_alive_test.dart",
"repo_id": "flutter",
"token_count": 18946
} | 682 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Nested ListView with shrinkWrap', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
shrinkWrap: true,
children: <Widget>[
ListView(
shrinkWrap: true,
children: const <Widget>[
Text('1'),
Text('2'),
Text('3'),
],
),
ListView(
shrinkWrap: true,
children: const <Widget>[
Text('4'),
Text('5'),
Text('6'),
],
),
],
),
),
);
});
testWidgets('Underflowing ListView should relayout for additional children', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/5950
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 100.0, child: Text('100')),
],
),
),
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 100.0, child: Text('100')),
SizedBox(height: 200.0, child: Text('200')),
],
),
),
);
expect(find.text('200'), findsOneWidget);
});
testWidgets('Underflowing ListView contentExtent should track additional children', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 100.0, child: Text('100')),
],
),
),
);
final RenderSliverList list = tester.renderObject(find.byType(SliverList));
expect(list.geometry!.scrollExtent, equals(100.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 100.0, child: Text('100')),
SizedBox(height: 200.0, child: Text('200')),
],
),
),
);
expect(list.geometry!.scrollExtent, equals(300.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(),
),
);
expect(list.geometry!.scrollExtent, equals(0.0));
});
testWidgets('Overflowing ListView should relayout for missing children', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 300.0, child: Text('300')),
SizedBox(height: 400.0, child: Text('400')),
],
),
),
);
expect(find.text('300'), findsOneWidget);
expect(find.text('400'), findsOneWidget);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 300.0, child: Text('300')),
],
),
),
);
expect(find.text('300'), findsOneWidget);
expect(find.text('400'), findsNothing);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(),
),
);
expect(find.text('300'), findsNothing);
expect(find.text('400'), findsNothing);
});
testWidgets('Overflowing ListView should not relayout for additional children', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 300.0, child: Text('300')),
SizedBox(height: 400.0, child: Text('400')),
],
),
),
);
expect(find.text('300'), findsOneWidget);
expect(find.text('400'), findsOneWidget);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 300.0, child: Text('300')),
SizedBox(height: 400.0, child: Text('400')),
SizedBox(height: 100.0, child: Text('100')),
],
),
),
);
expect(find.text('300'), findsOneWidget);
expect(find.text('400'), findsOneWidget);
expect(find.text('100'), findsNothing);
});
testWidgets('Overflowing ListView should become scrollable', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/5920
// When a ListView's viewport hasn't overflowed, scrolling is disabled.
// When children are added that cause it to overflow, scrolling should
// be enabled.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 100.0, child: Text('100')),
],
),
),
);
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
expect(scrollable.position.maxScrollExtent, 0.0);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: const <Widget>[
SizedBox(height: 100.0, child: Text('100')),
SizedBox(height: 200.0, child: Text('200')),
SizedBox(height: 400.0, child: Text('400')),
],
),
),
);
expect(scrollable.position.maxScrollExtent, 100.0);
});
}
| flutter/packages/flutter/test/widgets/list_view_relayout_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/list_view_relayout_test.dart",
"repo_id": "flutter",
"token_count": 2780
} | 683 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart' show PointerDeviceKind, kSecondaryButton;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
late bool tapped;
late bool hovered;
late Widget tapTarget;
late Widget hoverTarget;
late Animation<Color?> colorAnimation;
setUp(() {
tapped = false;
colorAnimation = const AlwaysStoppedAnimation<Color?>(Colors.red);
tapTarget = GestureDetector(
onTap: () {
tapped = true;
},
child: const SizedBox(
width: 10.0,
height: 10.0,
child: Text('target', textDirection: TextDirection.ltr),
),
);
hovered = false;
hoverTarget = MouseRegion(
onHover: (_) { hovered = true; },
onEnter: (_) { hovered = true; },
onExit: (_) { hovered = true; },
child: const SizedBox(
width: 10.0,
height: 10.0,
child: Text('target', textDirection: TextDirection.ltr),
),
);
});
group('ModalBarrier', () {
testWidgets('prevents interactions with widgets behind it', (WidgetTester tester) async {
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
tapTarget,
const ModalBarrier(dismissible: false),
],
);
await tester.pumpWidget(subject);
await tester.tap(find.text('target'), warnIfMissed: false);
await tester.pumpWidget(subject);
expect(tapped, isFalse, reason: 'because the tap is not prevented by ModalBarrier');
});
testWidgets('prevents hover interactions with widgets behind it', (WidgetTester tester) async {
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
hoverTarget,
const ModalBarrier(dismissible: false),
],
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
// Start out of hoverTarget
await gesture.moveTo(const Offset(100, 100));
await tester.pumpWidget(subject);
// Move into hoverTarget and tap
await gesture.down(const Offset(5, 5));
await tester.pumpWidget(subject);
await gesture.up();
await tester.pumpWidget(subject);
// Move out
await gesture.moveTo(const Offset(100, 100));
await tester.pumpWidget(subject);
expect(hovered, isFalse, reason: 'because the hover is not prevented by ModalBarrier');
});
testWidgets('does not prevent interactions with widgets in front of it', (WidgetTester tester) async {
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
const ModalBarrier(dismissible: false),
tapTarget,
],
);
await tester.pumpWidget(subject);
await tester.tap(find.text('target'));
await tester.pumpWidget(subject);
expect(tapped, isTrue, reason: 'because the tap is prevented by ModalBarrier');
});
testWidgets('does not prevent interactions with translucent widgets in front of it', (WidgetTester tester) async {
bool dragged = false;
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
const ModalBarrier(dismissible: false),
GestureDetector(
behavior: HitTestBehavior.translucent,
onHorizontalDragStart: (_) {
dragged = true;
},
child: const Center(
child: Text('target', textDirection: TextDirection.ltr),
),
),
],
);
await tester.pumpWidget(subject);
await tester.dragFrom(
tester.getBottomRight(find.byType(GestureDetector)) - const Offset(10, 10),
const Offset(-20, 0),
);
await tester.pumpWidget(subject);
expect(dragged, isTrue, reason: 'because the drag is prevented by ModalBarrier');
});
testWidgets('does not prevent hover interactions with widgets in front of it', (WidgetTester tester) async {
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
const ModalBarrier(dismissible: false),
hoverTarget,
],
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
// Start out of hoverTarget
await gesture.moveTo(const Offset(100, 100));
await tester.pumpWidget(subject);
expect(hovered, isFalse);
// Move into hoverTarget
await gesture.moveTo(const Offset(5, 5));
await tester.pumpWidget(subject);
expect(hovered, isTrue, reason: 'because the hover is prevented by ModalBarrier');
hovered = false;
// Move out
await gesture.moveTo(const Offset(100, 100));
await tester.pumpWidget(subject);
expect(hovered, isTrue, reason: 'because the hover is prevented by ModalBarrier');
hovered = false;
});
testWidgets('plays system alert sound when user tries to dismiss it', (WidgetTester tester) async {
final List<String> playedSystemSounds = <String>[];
try {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform, (MethodCall methodCall) async {
if (methodCall.method == 'SystemSound.play') {
playedSystemSounds.add(methodCall.arguments as String);
}
return null;
});
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
tapTarget,
const ModalBarrier(dismissible: false),
],
);
await tester.pumpWidget(subject);
await tester.tap(find.text('target'), warnIfMissed: false);
await tester.pumpWidget(subject);
} finally {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
}
expect(playedSystemSounds, hasLength(1));
expect(playedSystemSounds[0], SystemSoundType.alert.toString());
});
testWidgets('pops the Navigator when dismissed by primary tap', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) => const SecondWidget(),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
// Press the barrier; it shouldn't dismiss yet
final TestGesture gesture = await tester.press(
find.byKey(const ValueKey<String>('barrier')),
);
await tester.pumpAndSettle(); // begin transition
expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
// Release the pointer; the barrier should be dismissed
await gesture.up();
await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsNothing,
reason: 'The route should have been dismissed by tapping the barrier.',
);
});
testWidgets('pops the Navigator when dismissed by non-primary tap', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) => const SecondWidget(),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
// Press the barrier; it shouldn't dismiss yet
final TestGesture gesture = await tester.press(
find.byKey(const ValueKey<String>('barrier')),
buttons: kSecondaryButton,
);
await tester.pumpAndSettle(); // begin transition
expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
// Release the pointer; the barrier should be dismissed
await gesture.up();
await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsNothing,
reason: 'The route should have been dismissed by tapping the barrier.',
);
});
testWidgets('may pop the Navigator when competing with other gestures', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) => const SecondWidgetWithCompetence(),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
// Tap on the barrier to dismiss it
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsNothing,
reason: 'The route should have been dismissed by tapping the barrier.',
);
});
testWidgets('does not pop the Navigator with a WillPopScope that returns false', (WidgetTester tester) async {
bool willPopCalled = false;
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) =>
Stack(
children: <Widget>[
const SecondWidget(),
WillPopScope(
child: const SizedBox(),
onWillPop: () async {
willPopCalled = true;
return false;
},
),
],
),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(willPopCalled, isFalse);
// Tap on the barrier to attempt to dismiss it
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsOneWidget,
reason: 'The route should still be present if the pop is vetoed.',
);
expect(willPopCalled, isTrue);
});
testWidgets('pops the Navigator with a WillPopScope that returns true', (WidgetTester tester) async {
bool willPopCalled = false;
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) =>
Stack(
children: <Widget>[
const SecondWidget(),
WillPopScope(
child: const SizedBox(),
onWillPop: () async {
willPopCalled = true;
return true;
},
),
],
),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(willPopCalled, isFalse);
// Tap on the barrier to attempt to dismiss it
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsNothing,
reason: 'The route should not be present if the pop is permitted.',
);
expect(willPopCalled, isTrue);
});
testWidgets('will call onDismiss callback', (WidgetTester tester) async {
bool dismissCallbackCalled = false;
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) =>
SecondWidget(onDismiss: () {
dismissCallbackCalled = true;
}),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
expect(dismissCallbackCalled, false);
// Tap on the barrier
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
expect(dismissCallbackCalled, true);
});
testWidgets('when onDismiss throws, should have correct context', (WidgetTester tester) async {
final FlutterExceptionHandler? handler = FlutterError.onError;
FlutterErrorDetails? error;
FlutterError.onError = (FlutterErrorDetails details) {
error = details;
};
final UniqueKey barrierKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: ModalBarrier(
key: barrierKey,
onDismiss: () => throw Exception('deliberate'),
),
),
));
await tester.tap(find.byKey(barrierKey));
await tester.pump();
expect(error?.context.toString(), contains('handling a gesture'));
FlutterError.onError = handler;
});
testWidgets('will not pop when given an onDismiss callback', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) => SecondWidget(onDismiss: () {}),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
// Tap on the barrier
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsOneWidget,
reason: 'The route should not have been dismissed by tapping the barrier, as there was a onDismiss callback given.',
);
});
testWidgets('Undismissible ModalBarrier hidden in semantic tree', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(const ModalBarrier(dismissible: false));
final TestSemantics expectedSemantics = TestSemantics.root();
expect(semantics, hasSemantics(expectedSemantics));
semantics.dispose();
});
testWidgets('Dismissible ModalBarrier includes button in semantic tree on iOS, macOS and android', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.ltr,
child: ModalBarrier(
semanticsLabel: 'Dismiss',
),
));
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: TestSemantics.fullScreen,
actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
label: 'Dismiss',
textDirection: TextDirection.ltr,
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
semantics.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android}));
});
group('AnimatedModalBarrier', () {
testWidgets('prevents interactions with widgets behind it', (WidgetTester tester) async {
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
tapTarget,
AnimatedModalBarrier(dismissible: false, color: colorAnimation),
],
);
await tester.pumpWidget(subject);
await tester.tap(find.text('target'), warnIfMissed: false);
await tester.pumpWidget(subject);
expect(tapped, isFalse, reason: 'because the tap is not prevented by ModalBarrier');
});
testWidgets('prevents hover interactions with widgets behind it', (WidgetTester tester) async {
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
hoverTarget,
AnimatedModalBarrier(dismissible: false, color: colorAnimation),
],
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
// Start out of hoverTarget
await gesture.moveTo(const Offset(100, 100));
await tester.pumpWidget(subject);
// Move into hoverTarget and tap
await gesture.down(const Offset(5, 5));
await tester.pumpWidget(subject);
await gesture.up();
await tester.pumpWidget(subject);
// Move out
await gesture.moveTo(const Offset(100, 100));
await tester.pumpWidget(subject);
expect(hovered, isFalse, reason: 'because the hover is not prevented by AnimatedModalBarrier');
});
testWidgets('does not prevent interactions with widgets in front of it', (WidgetTester tester) async {
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
AnimatedModalBarrier(dismissible: false, color: colorAnimation),
tapTarget,
],
);
await tester.pumpWidget(subject);
await tester.tap(find.text('target'));
await tester.pumpWidget(subject);
expect(tapped, isTrue, reason: 'because the tap is prevented by AnimatedModalBarrier');
});
testWidgets('does not prevent interactions with translucent widgets in front of it', (WidgetTester tester) async {
bool dragged = false;
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
AnimatedModalBarrier(dismissible: false, color: colorAnimation),
GestureDetector(
behavior: HitTestBehavior.translucent,
onHorizontalDragStart: (_) {
dragged = true;
},
child: const Center(
child: Text('target', textDirection: TextDirection.ltr),
),
),
],
);
await tester.pumpWidget(subject);
await tester.dragFrom(
tester.getBottomRight(find.byType(GestureDetector)) - const Offset(10, 10),
const Offset(-20, 0),
);
await tester.pumpWidget(subject);
expect(dragged, isTrue, reason: 'because the drag is prevented by AnimatedModalBarrier');
});
testWidgets('does not prevent hover interactions with widgets in front of it', (WidgetTester tester) async {
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
AnimatedModalBarrier(dismissible: false, color: colorAnimation),
hoverTarget,
],
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
// Start out of hoverTarget
await gesture.moveTo(const Offset(100, 100));
await tester.pumpWidget(subject);
expect(hovered, isFalse);
// Move into hoverTarget
await gesture.moveTo(const Offset(5, 5));
await tester.pumpWidget(subject);
expect(hovered, isTrue, reason: 'because the hover is prevented by AnimatedModalBarrier');
hovered = false;
// Move out
await gesture.moveTo(const Offset(100, 100));
await tester.pumpWidget(subject);
expect(hovered, isTrue, reason: 'because the hover is prevented by AnimatedModalBarrier');
hovered = false;
});
testWidgets('plays system alert sound when user tries to dismiss it', (WidgetTester tester) async {
final List<String> playedSystemSounds = <String>[];
try {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform, (MethodCall methodCall) async {
if (methodCall.method == 'SystemSound.play') {
playedSystemSounds.add(methodCall.arguments as String);
}
return null;
});
final Widget subject = Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
tapTarget,
AnimatedModalBarrier(dismissible: false, color: colorAnimation),
],
);
await tester.pumpWidget(subject);
await tester.tap(find.text('target'), warnIfMissed: false);
await tester.pumpWidget(subject);
} finally {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
}
expect(playedSystemSounds, hasLength(1));
expect(playedSystemSounds[0], SystemSoundType.alert.toString());
});
testWidgets('pops the Navigator when dismissed by primary tap', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) => const AnimatedSecondWidget(),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
// Press the barrier; it shouldn't dismiss yet
final TestGesture gesture = await tester.press(
find.byKey(const ValueKey<String>('barrier')),
);
await tester.pumpAndSettle(); // begin transition
expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
// Release the pointer; the barrier should be dismissed
await gesture.up();
await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsNothing,
reason: 'The route should have been dismissed by tapping the barrier.',
);
});
testWidgets('pops the Navigator when dismissed by non-primary tap', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) => const AnimatedSecondWidget(),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
// Press the barrier; it shouldn't dismiss yet
final TestGesture gesture = await tester.press(
find.byKey(const ValueKey<String>('barrier')),
buttons: kSecondaryButton,
);
await tester.pumpAndSettle(); // begin transition
expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
// Release the pointer; the barrier should be dismissed
await gesture.up();
await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsNothing,
reason: 'The route should have been dismissed by tapping the barrier.',
);
});
testWidgets('may pop the Navigator when competing with other gestures', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) => const AnimatedSecondWidgetWithCompetence(),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
// Tap on the barrier to dismiss it
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsNothing,
reason: 'The route should have been dismissed by tapping the barrier.',
);
});
testWidgets('does not pop the Navigator with a WillPopScope that returns false', (WidgetTester tester) async {
bool willPopCalled = false;
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) =>
Stack(
children: <Widget>[
const AnimatedSecondWidget(),
WillPopScope(
child: const SizedBox(),
onWillPop: () async {
willPopCalled = true;
return false;
},
),
],
),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(willPopCalled, isFalse);
// Tap on the barrier to attempt to dismiss it
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsOneWidget,
reason: 'The route should still be present if the pop is vetoed.',
);
expect(willPopCalled, isTrue);
});
testWidgets('pops the Navigator with a WillPopScope that returns true', (WidgetTester tester) async {
bool willPopCalled = false;
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) =>
Stack(
children: <Widget>[
const AnimatedSecondWidget(),
WillPopScope(
child: const SizedBox(),
onWillPop: () async {
willPopCalled = true;
return true;
},
),
],
),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(willPopCalled, isFalse);
// Tap on the barrier to attempt to dismiss it
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsNothing,
reason: 'The route should not be present if the pop is permitted.',
);
expect(willPopCalled, isTrue);
});
testWidgets('will call onDismiss callback', (WidgetTester tester) async {
bool dismissCallbackCalled = false;
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) =>
AnimatedSecondWidget(onDismiss: () {
dismissCallbackCalled = true;
}),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
expect(dismissCallbackCalled, false);
// Tap on the barrier
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
expect(dismissCallbackCalled, true);
});
testWidgets('will not pop when given an onDismiss callback', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(),
'/modal': (BuildContext context) => AnimatedSecondWidget(onDismiss: () {}),
};
await tester.pumpWidget(MaterialApp(routes: routes));
// Initially the barrier is not visible
expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
// Tapping on X routes to the barrier
await tester.tap(find.text('X'));
await tester.pump(); // begin transition
await tester.pump(const Duration(seconds: 1)); // end transition
expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
// Tap on the barrier
await tester.tap(find.byKey(const ValueKey<String>('barrier')));
await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
expect(
find.byKey(const ValueKey<String>('barrier')),
findsOneWidget,
reason: 'The route should not have been dismissed by tapping the barrier, as there was a onDismiss callback given.',
);
});
testWidgets('Undismissible AnimatedModalBarrier hidden in semantic tree', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(AnimatedModalBarrier(dismissible: false, color: colorAnimation));
final TestSemantics expectedSemantics = TestSemantics.root();
expect(semantics, hasSemantics(expectedSemantics));
semantics.dispose();
});
testWidgets('Dismissible AnimatedModalBarrier includes button in semantic tree on iOS, macOS and android', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: AnimatedModalBarrier(
semanticsLabel: 'Dismiss',
color: colorAnimation,
),
));
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: TestSemantics.fullScreen,
actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
label: 'Dismiss',
textDirection: TextDirection.ltr,
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
semantics.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android}));
});
group('SemanticsClipper', () {
testWidgets('SemanticsClipper correctly clips Semantics.rect in four directions', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final ValueNotifier<EdgeInsets> notifier = ValueNotifier<EdgeInsets>(const EdgeInsets.fromLTRB(10, 20, 30, 40));
addTearDown(notifier.dispose);
const Rect fullScreen = TestSemantics.fullScreen;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ModalBarrier(
semanticsLabel: 'Dismiss',
clipDetailsNotifier: notifier,
),
));
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: Rect.fromLTRB(fullScreen.left + 10, fullScreen.top + 20.0, fullScreen.right - 30, fullScreen.bottom - 40),
actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
label: 'Dismiss',
textDirection: TextDirection.ltr,
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
semantics.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android}));
});
testWidgets('uses default mouse cursor', (WidgetTester tester) async {
await tester.pumpWidget(const Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
MouseRegion(cursor: SystemMouseCursors.click),
ModalBarrier(dismissible: false),
],
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(ModalBarrier)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
}
class FirstWidget extends StatelessWidget {
const FirstWidget({super.key});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, '/modal');
},
child: const Text('X'),
);
}
}
class SecondWidget extends StatelessWidget {
const SecondWidget({super.key, this.onDismiss});
final VoidCallback? onDismiss;
@override
Widget build(BuildContext context) {
return ModalBarrier(
key: const ValueKey<String>('barrier'),
onDismiss: onDismiss,
);
}
}
class AnimatedSecondWidget extends StatelessWidget {
const AnimatedSecondWidget({super.key, this.onDismiss});
final VoidCallback? onDismiss;
@override
Widget build(BuildContext context) {
return AnimatedModalBarrier(
key: const ValueKey<String>('barrier'),
color: const AlwaysStoppedAnimation<Color?>(Colors.red),
onDismiss: onDismiss,
);
}
}
class SecondWidgetWithCompetence extends StatelessWidget {
const SecondWidgetWithCompetence({super.key});
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
const ModalBarrier(
key: ValueKey<String>('barrier'),
),
GestureDetector(
onVerticalDragStart: (_) {},
behavior: HitTestBehavior.translucent,
child: Container(),
),
],
);
}
}
class AnimatedSecondWidgetWithCompetence extends StatelessWidget {
const AnimatedSecondWidgetWithCompetence({super.key});
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
const AnimatedModalBarrier(
key: ValueKey<String>('barrier'),
color: AlwaysStoppedAnimation<Color?>(Colors.red),
),
GestureDetector(
onVerticalDragStart: (_) {},
behavior: HitTestBehavior.translucent,
child: Container(),
),
],
);
}
}
| flutter/packages/flutter/test/widgets/modal_barrier_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/modal_barrier_test.dart",
"repo_id": "flutter",
"token_count": 14878
} | 684 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
typedef OnObservation = void Function(Route<dynamic>? route, Route<dynamic>? previousRoute);
/// A trivial observer for testing the navigator.
class TestObserver extends NavigatorObserver {
OnObservation? onPushed;
OnObservation? onPopped;
OnObservation? onRemoved;
OnObservation? onReplaced;
OnObservation? onStartUserGesture;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
onPushed?.call(route, previousRoute);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
onPopped?.call(route, previousRoute);
}
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
onRemoved?.call(route, previousRoute);
}
@override
void didReplace({ Route<dynamic>? oldRoute, Route<dynamic>? newRoute }) {
onReplaced?.call(newRoute, oldRoute);
}
@override
void didStartUserGesture(Route<dynamic> route, Route<dynamic>? previousRoute) {
onStartUserGesture?.call(route, previousRoute);
}
}
| flutter/packages/flutter/test/widgets/observer_tester.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/observer_tester.dart",
"repo_id": "flutter",
"token_count": 406
} | 685 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/src/rendering/performance_overlay.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Performance overlay smoke test', (WidgetTester tester) async {
await tester.pumpWidget(const PerformanceOverlay());
await tester.pumpWidget(PerformanceOverlay.allEnabled());
});
testWidgets('update widget field checkerboardRasterCacheImages',
(WidgetTester tester) async {
await tester.pumpWidget(const PerformanceOverlay());
await tester.pumpWidget(
const PerformanceOverlay(checkerboardRasterCacheImages: true));
final Finder finder = find.byType(PerformanceOverlay);
expect(
tester
.renderObject<RenderPerformanceOverlay>(finder)
.checkerboardRasterCacheImages,
true);
});
testWidgets('update widget field checkerboardOffscreenLayers',
(WidgetTester tester) async {
await tester.pumpWidget(const PerformanceOverlay());
await tester.pumpWidget(
const PerformanceOverlay(checkerboardOffscreenLayers: true));
final Finder finder = find.byType(PerformanceOverlay);
expect(
tester
.renderObject<RenderPerformanceOverlay>(finder)
.checkerboardOffscreenLayers,
true);
});
}
| flutter/packages/flutter/test/widgets/performance_overlay_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/performance_overlay_test.dart",
"repo_id": "flutter",
"token_count": 515
} | 686 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
// This is a regression test for https://github.com/flutter/flutter/issues/5840.
class Bar extends StatefulWidget {
const Bar({ super.key });
@override
BarState createState() => BarState();
}
class BarState extends State<Bar> {
final GlobalKey _fooKey = GlobalKey();
bool _mode = false;
void trigger() {
setState(() {
_mode = !_mode;
});
}
@override
Widget build(BuildContext context) {
if (_mode) {
return SizedBox(
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return StatefulCreationCounter(key: _fooKey);
},
),
);
} else {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return StatefulCreationCounter(key: _fooKey);
},
);
}
}
}
class StatefulCreationCounter extends StatefulWidget {
const StatefulCreationCounter({ super.key });
@override
StatefulCreationCounterState createState() => StatefulCreationCounterState();
}
class StatefulCreationCounterState extends State<StatefulCreationCounter> {
static int creationCount = 0;
@override
void initState() {
super.initState();
creationCount += 1;
}
@override
Widget build(BuildContext context) => Container();
}
void main() {
testWidgets('reparent state with layout builder', (WidgetTester tester) async {
expect(StatefulCreationCounterState.creationCount, 0);
await tester.pumpWidget(const Bar());
expect(StatefulCreationCounterState.creationCount, 1);
final BarState s = tester.state<BarState>(find.byType(Bar));
s.trigger();
await tester.pump();
expect(StatefulCreationCounterState.creationCount, 1);
});
testWidgets('Clean then reparent with dependencies', (WidgetTester tester) async {
int layoutBuilderBuildCount = 0;
late StateSetter keyedSetState;
late StateSetter layoutBuilderSetState;
late StateSetter childSetState;
final GlobalKey key = GlobalKey();
final Widget keyedWidget = StatefulBuilder(
key: key,
builder: (BuildContext context, StateSetter setState) {
keyedSetState = setState;
MediaQuery.of(context);
return Container();
},
);
Widget layoutBuilderChild = keyedWidget;
Widget deepChild = Container();
await tester.pumpWidget(MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Column(
children: <Widget>[
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
layoutBuilderSetState = setState;
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
layoutBuilderBuildCount += 1;
return layoutBuilderChild; // initially keyedWidget above, but then a new Container
},
);
}),
ColoredBox(
color: Colors.green,
child: ColoredBox(
color: Colors.green,
child: ColoredBox(
color: Colors.green,
child: ColoredBox(
color: Colors.green,
child: ColoredBox(
color: Colors.green,
child: ColoredBox(
color: Colors.green,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
childSetState = setState;
return deepChild; // initially a Container, but then the keyedWidget above
},
),
),
),
),
),
),
),
],
),
));
expect(layoutBuilderBuildCount, 1);
keyedSetState(() { /* Change nothing but add the element to the dirty list. */ });
childSetState(() {
// The deep child builds in the initial build phase. It takes the child
// from the LayoutBuilder before the LayoutBuilder has a chance to build.
deepChild = keyedWidget;
});
layoutBuilderSetState(() {
// The layout builder will build in a separate build scope. This delays
// the removal of the keyed child until this build scope.
layoutBuilderChild = Container();
});
// The essential part of this test is that this call to pump doesn't throw.
await tester.pump();
expect(layoutBuilderBuildCount, 2);
});
}
| flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart",
"repo_id": "flutter",
"token_count": 1940
} | 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('runApp inside onPressed does not throw', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: ElevatedButton(
onPressed: () {
runApp(const Center(child: Text('Done', textDirection: TextDirection.ltr)));
},
child: const Text('GO'),
),
),
),
);
await tester.tap(find.text('GO'));
expect(find.text('Done'), findsOneWidget);
});
}
| flutter/packages/flutter/test/widgets/run_app_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/run_app_test.dart",
"repo_id": "flutter",
"token_count": 331
} | 688 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('GridView default control', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: GridView.count(
crossAxisCount: 1,
),
),
),
);
});
// Tests https://github.com/flutter/flutter/issues/5522
testWidgets('GridView displays correct children with nonzero padding', (WidgetTester tester) async {
const EdgeInsets padding = EdgeInsets.fromLTRB(0.0, 100.0, 0.0, 0.0);
final Widget testWidget = Directionality(
textDirection: TextDirection.ltr,
child: Align(
child: SizedBox(
height: 800.0,
width: 300.0, // forces the grid children to be 300..300
child: GridView.count(
crossAxisCount: 1,
padding: padding,
children: List<Widget>.generate(10, (int index) {
return Text('$index', key: ValueKey<int>(index));
}).toList(),
),
),
),
);
await tester.pumpWidget(testWidget);
// screen is 600px high, and has the following items:
// 100..400 = 0
// 400..700 = 1
await tester.pump();
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
await tester.drag(find.text('1'), const Offset(0.0, -500.0));
await tester.pump();
// -100..300 = 1
// 300..600 = 2
// 600..600 = 3
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.drag(find.text('1'), const Offset(0.0, 150.0));
await tester.pump();
// Child '0' is now back onscreen, but by less than `padding.top`.
// -250..050 = 0
// 050..450 = 1
// 450..750 = 2
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
});
testWidgets('GridView.count() fixed itemExtent, scroll to end, append, scroll', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/9506
Widget buildFrame(int itemCount) {
return Directionality(
textDirection: TextDirection.ltr,
child: GridView.count(
crossAxisCount: itemCount,
children: List<Widget>.generate(itemCount, (int index) {
return SizedBox(
height: 200.0,
child: Text('item $index'),
);
}),
),
);
}
await tester.pumpWidget(buildFrame(3));
expect(find.text('item 0'), findsOneWidget);
expect(find.text('item 1'), findsOneWidget);
expect(find.text('item 2'), findsOneWidget);
await tester.pumpWidget(buildFrame(4));
final TestGesture gesture = await tester.startGesture(const Offset(0.0, 300.0));
await gesture.moveBy(const Offset(0.0, -200.0));
await tester.pumpAndSettle();
expect(find.text('item 3'), findsOneWidget);
});
}
| flutter/packages/flutter/test/widgets/scrollable_grid_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scrollable_grid_test.dart",
"repo_id": "flutter",
"token_count": 1485
} | 689 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('markNeedsSemanticsUpdate() called on non-boundary with non-boundary parent', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Semantics(
container: true,
onTap: dummyTapHandler,
child: Semantics(
onTap: dummyTapHandler,
child: Semantics(
onTap: dummyTapHandler,
textDirection: TextDirection.ltr,
label: 'foo',
),
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
actions: SemanticsAction.tap.index,
children: <TestSemantics>[
TestSemantics(
id: 2,
actions: SemanticsAction.tap.index,
children: <TestSemantics>[
TestSemantics(
id: 3,
actions: SemanticsAction.tap.index,
label: 'foo',
),
],
),
],
),
],
), ignoreRect: true, ignoreTransform: true));
// make a change causing call to markNeedsSemanticsUpdate()
// This should not throw an assert.
await tester.pumpWidget(
Semantics(
container: true,
onTap: dummyTapHandler,
child: Semantics(
onTap: dummyTapHandler,
child: Semantics(
onTap: dummyTapHandler,
textDirection: TextDirection.ltr,
label: 'bar', // <-- only change
),
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
actions: SemanticsAction.tap.index,
children: <TestSemantics>[
TestSemantics(
id: 2,
actions: SemanticsAction.tap.index,
children: <TestSemantics>[
TestSemantics(
id: 3,
actions: SemanticsAction.tap.index,
label: 'bar',
),
],
),
],
),
],
), ignoreRect: true, ignoreTransform: true));
semantics.dispose();
});
}
void dummyTapHandler() { }
| flutter/packages/flutter/test/widgets/semantics_11_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_11_test.dart",
"repo_id": "flutter",
"token_count": 1315
} | 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 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
setUp(() {
debugResetSemanticsIdCounter();
});
testWidgets('Semantics shutdown and restart', (WidgetTester tester) async {
SemanticsTester? semantics = SemanticsTester(tester);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'test1',
textDirection: TextDirection.ltr,
),
],
);
await tester.pumpWidget(
Semantics(
label: 'test1',
textDirection: TextDirection.ltr,
child: Container(),
),
);
expect(semantics, hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreRect: true,
ignoreId: true,
));
semantics.dispose();
semantics = null;
expect(tester.binding.hasScheduledFrame, isFalse);
semantics = SemanticsTester(tester);
expect(tester.binding.hasScheduledFrame, isTrue);
await tester.pump();
expect(semantics, hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreRect: true,
ignoreId: true,
));
semantics.dispose();
}, semanticsEnabled: false);
testWidgets('Semantics tag only applies to immediate child', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: <Widget>[
SingleChildScrollView(
child: Column(
children: <Widget>[
Container(padding: const EdgeInsets.only(top: 20.0)),
const Text('label'),
],
),
),
],
),
),
);
expect(semantics, isNot(includesNodeWith(
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics},
)));
await tester.pump();
// Semantics should stay the same after a frame update.
expect(semantics, isNot(includesNodeWith(
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics},
)));
semantics.dispose();
}, semanticsEnabled: false);
testWidgets('Semantics tooltip', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
tooltip: 'test1',
textDirection: TextDirection.ltr,
),
],
);
await tester.pumpWidget(
Semantics(
tooltip: 'test1',
textDirection: TextDirection.ltr,
),
);
expect(semantics, hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreRect: true,
ignoreId: true,
));
semantics.dispose();
});
testWidgets('Detach and reattach assert', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final GlobalKey key = GlobalKey();
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
label: 'test1',
child: Semantics(
key: key,
container: true,
label: 'test2a',
child: Container(),
),
),
));
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'test1',
children: <TestSemantics>[
TestSemantics(
label: 'test2a',
),
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
));
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
label: 'test1',
child: Semantics(
container: true,
label: 'middle',
child: Semantics(
key: key,
container: true,
label: 'test2b',
child: Container(),
),
),
),
));
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'test1',
children: <TestSemantics>[
TestSemantics(
label: 'middle',
children: <TestSemantics>[
TestSemantics(
label: 'test2b',
),
],
),
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
));
semantics.dispose();
});
testWidgets('Semantics and Directionality - RTL', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Semantics(
label: 'test1',
child: Container(),
),
),
);
expect(semantics, includesNodeWith(label: 'test1', textDirection: TextDirection.rtl));
semantics.dispose();
});
testWidgets('Semantics and Directionality - LTR', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
label: 'test1',
child: Container(),
),
),
);
expect(semantics, includesNodeWith(label: 'test1', textDirection: TextDirection.ltr));
semantics.dispose();
});
testWidgets('Semantics and Directionality - cannot override RTL with LTR', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'test1',
textDirection: TextDirection.ltr,
),
],
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Semantics(
label: 'test1',
textDirection: TextDirection.ltr,
child: Container(),
),
),
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true));
semantics.dispose();
});
testWidgets('Semantics and Directionality - cannot override LTR with RTL', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'test1',
textDirection: TextDirection.rtl,
),
],
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
label: 'test1',
textDirection: TextDirection.rtl,
child: Container(),
),
),
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true));
semantics.dispose();
});
testWidgets('Semantics label and hint', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
label: 'label',
hint: 'hint',
value: 'value',
child: Container(),
),
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'label',
hint: 'hint',
value: 'value',
textDirection: TextDirection.ltr,
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true));
semantics.dispose();
});
testWidgets('Semantics hints can merge', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
container: true,
child: Column(
children: <Widget>[
Semantics(
hint: 'hint one',
),
Semantics(
hint: 'hint two',
),
],
),
),
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
hint: 'hint one\nhint two',
textDirection: TextDirection.ltr,
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true));
semantics.dispose();
});
testWidgets('Semantics values do not merge', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
container: true,
child: Column(
children: <Widget>[
Semantics(
value: 'value one',
child: const SizedBox(
height: 10.0,
width: 10.0,
),
),
Semantics(
value: 'value two',
child: const SizedBox(
height: 10.0,
width: 10.0,
),
),
],
),
),
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
children: <TestSemantics>[
TestSemantics(
value: 'value one',
textDirection: TextDirection.ltr,
),
TestSemantics(
value: 'value two',
textDirection: TextDirection.ltr,
),
],
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true));
semantics.dispose();
});
testWidgets('Semantics value and hint can merge', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
container: true,
child: Column(
children: <Widget>[
Semantics(
hint: 'hint',
),
Semantics(
value: 'value',
),
],
),
),
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
hint: 'hint',
value: 'value',
textDirection: TextDirection.ltr,
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true));
semantics.dispose();
});
testWidgets('Semantics tagForChildren works', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
container: true,
tagForChildren: const SemanticsTag('custom tag'),
child: Column(
children: <Widget>[
Semantics(
container: true,
child: const Text('child 1'),
),
Semantics(
container: true,
child: const Text('child 2'),
),
],
),
),
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
children: <TestSemantics>[
TestSemantics(
label: 'child 1',
tags: <SemanticsTag>[const SemanticsTag('custom tag')],
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'child 2',
tags: <SemanticsTag>[const SemanticsTag('custom tag')],
textDirection: TextDirection.ltr,
),
],
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true));
semantics.dispose();
});
testWidgets('Semantics widget supports all actions', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final List<SemanticsAction> performedActions = <SemanticsAction>[];
await tester.pumpWidget(
Semantics(
container: true,
onDismiss: () => performedActions.add(SemanticsAction.dismiss),
onTap: () => performedActions.add(SemanticsAction.tap),
onLongPress: () => performedActions.add(SemanticsAction.longPress),
onScrollLeft: () => performedActions.add(SemanticsAction.scrollLeft),
onScrollRight: () => performedActions.add(SemanticsAction.scrollRight),
onScrollUp: () => performedActions.add(SemanticsAction.scrollUp),
onScrollDown: () => performedActions.add(SemanticsAction.scrollDown),
onIncrease: () => performedActions.add(SemanticsAction.increase),
onDecrease: () => performedActions.add(SemanticsAction.decrease),
onCopy: () => performedActions.add(SemanticsAction.copy),
onCut: () => performedActions.add(SemanticsAction.cut),
onPaste: () => performedActions.add(SemanticsAction.paste),
onMoveCursorForwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByCharacter),
onMoveCursorBackwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByCharacter),
onSetSelection: (TextSelection _) => performedActions.add(SemanticsAction.setSelection),
onSetText: (String _) => performedActions.add(SemanticsAction.setText),
onDidGainAccessibilityFocus: () => performedActions.add(SemanticsAction.didGainAccessibilityFocus),
onDidLoseAccessibilityFocus: () => performedActions.add(SemanticsAction.didLoseAccessibilityFocus),
),
);
final Set<SemanticsAction> allActions = SemanticsAction.values.toSet()
..remove(SemanticsAction.moveCursorForwardByWord)
..remove(SemanticsAction.moveCursorBackwardByWord)
..remove(SemanticsAction.customAction) // customAction is not user-exposed.
..remove(SemanticsAction.showOnScreen); // showOnScreen is not user-exposed
const int expectedId = 1;
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: expectedId,
rect: TestSemantics.fullScreen,
actions: allActions.fold<int>(0, (int previous, SemanticsAction action) => previous | action.index),
),
],
);
expect(semantics, hasSemantics(expectedSemantics));
// Do the actions work?
final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!;
int expectedLength = 1;
for (final SemanticsAction action in allActions) {
switch (action) {
case SemanticsAction.moveCursorBackwardByCharacter:
case SemanticsAction.moveCursorForwardByCharacter:
semanticsOwner.performAction(expectedId, action, true);
case SemanticsAction.setSelection:
semanticsOwner.performAction(expectedId, action, <dynamic, dynamic>{
'base': 4,
'extent': 5,
});
case SemanticsAction.setText:
semanticsOwner.performAction(expectedId, action, 'text');
case SemanticsAction.copy:
case SemanticsAction.customAction:
case SemanticsAction.cut:
case SemanticsAction.decrease:
case SemanticsAction.didGainAccessibilityFocus:
case SemanticsAction.didLoseAccessibilityFocus:
case SemanticsAction.dismiss:
case SemanticsAction.increase:
case SemanticsAction.longPress:
case SemanticsAction.moveCursorBackwardByWord:
case SemanticsAction.moveCursorForwardByWord:
case SemanticsAction.paste:
case SemanticsAction.scrollDown:
case SemanticsAction.scrollLeft:
case SemanticsAction.scrollRight:
case SemanticsAction.scrollUp:
case SemanticsAction.showOnScreen:
case SemanticsAction.tap:
semanticsOwner.performAction(expectedId, action);
}
expect(performedActions.length, expectedLength);
expect(performedActions.last, action);
expectedLength += 1;
}
semantics.dispose();
});
testWidgets('Semantics widget supports all flags', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
// Checked state and toggled state are mutually exclusive.
await tester.pumpWidget(
Semantics(
key: const Key('a'),
container: true,
explicitChildNodes: true,
// flags
enabled: true,
hidden: true,
checked: true,
selected: true,
button: true,
slider: true,
keyboardKey: true,
link: true,
textField: true,
readOnly: true,
focused: true,
focusable: true,
inMutuallyExclusiveGroup: true,
header: true,
obscured: true,
multiline: true,
scopesRoute: true,
namesRoute: true,
image: true,
liveRegion: true,
expanded: true,
),
);
final List<SemanticsFlag> flags = SemanticsFlag.values.toList();
flags
..remove(SemanticsFlag.hasToggledState)
..remove(SemanticsFlag.isToggled)
..remove(SemanticsFlag.hasImplicitScrolling)
..remove(SemanticsFlag.isCheckStateMixed);
TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: TestSemantics.fullScreen,
flags: flags,
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
await tester.pumpWidget(Semantics(
key: const Key('b'),
container: true,
scopesRoute: false,
));
expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: TestSemantics.fullScreen,
flags: <SemanticsFlag>[],
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
await tester.pumpWidget(
Semantics(
key: const Key('c'),
toggled: true,
),
);
expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: TestSemantics.fullScreen,
flags: <SemanticsFlag>[
SemanticsFlag.hasToggledState,
SemanticsFlag.isToggled,
],
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
await tester.pumpWidget(
Semantics(
key: const Key('a'),
container: true,
explicitChildNodes: true,
// flags
enabled: true,
hidden: true,
checked: false,
mixed: true,
selected: true,
button: true,
slider: true,
keyboardKey: true,
link: true,
textField: true,
readOnly: true,
focused: true,
focusable: true,
inMutuallyExclusiveGroup: true,
header: true,
obscured: true,
multiline: true,
scopesRoute: true,
namesRoute: true,
image: true,
liveRegion: true,
expanded: true,
),
);
flags
..remove(SemanticsFlag.isChecked)
..add(SemanticsFlag.isCheckStateMixed);
semantics.dispose();
expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: TestSemantics.fullScreen,
flags: flags,
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
});
testWidgets('Actions can be replaced without triggering semantics update', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
int semanticsUpdateCount = 0;
final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics(
listener: () {
semanticsUpdateCount += 1;
},
);
final List<String> performedActions = <String>[];
await tester.pumpWidget(
Semantics(
container: true,
onTap: () => performedActions.add('first'),
),
);
const int expectedId = 1;
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: expectedId,
rect: TestSemantics.fullScreen,
actions: SemanticsAction.tap.index,
),
],
);
final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!;
expect(semantics, hasSemantics(expectedSemantics));
semanticsOwner.performAction(expectedId, SemanticsAction.tap);
expect(semanticsUpdateCount, 1);
expect(performedActions, <String>['first']);
semanticsUpdateCount = 0;
performedActions.clear();
// Updating existing handler should not trigger semantics update
await tester.pumpWidget(
Semantics(
container: true,
onTap: () => performedActions.add('second'),
),
);
expect(semantics, hasSemantics(expectedSemantics));
semanticsOwner.performAction(expectedId, SemanticsAction.tap);
expect(semanticsUpdateCount, 0);
expect(performedActions, <String>['second']);
semanticsUpdateCount = 0;
performedActions.clear();
// Adding a handler works
await tester.pumpWidget(
Semantics(
container: true,
onTap: () => performedActions.add('second'),
onLongPress: () => performedActions.add('longPress'),
),
);
final TestSemantics expectedSemanticsWithLongPress = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: expectedId,
rect: TestSemantics.fullScreen,
actions: SemanticsAction.tap.index | SemanticsAction.longPress.index,
),
],
);
expect(semantics, hasSemantics(expectedSemanticsWithLongPress));
semanticsOwner.performAction(expectedId, SemanticsAction.longPress);
expect(semanticsUpdateCount, 1);
expect(performedActions, <String>['longPress']);
semanticsUpdateCount = 0;
performedActions.clear();
// Removing a handler works
await tester.pumpWidget(
Semantics(
container: true,
onTap: () => performedActions.add('second'),
),
);
expect(semantics, hasSemantics(expectedSemantics));
expect(semanticsUpdateCount, 1);
handle.dispose();
semantics.dispose();
});
testWidgets('onTapHint and onLongPressHint create custom actions', (WidgetTester tester) async {
final SemanticsHandle semantics = tester.ensureSemantics();
await tester.pumpWidget(Semantics(
container: true,
onTap: () { },
onTapHint: 'test',
));
expect(tester.getSemantics(find.byType(Semantics)), matchesSemantics(
hasTapAction: true,
onTapHint: 'test',
));
await tester.pumpWidget(Semantics(
container: true,
onLongPress: () { },
onLongPressHint: 'foo',
));
expect(tester.getSemantics(find.byType(Semantics)), matchesSemantics(
hasLongPressAction: true,
onLongPressHint: 'foo',
));
semantics.dispose();
});
testWidgets('CustomSemanticsActions can be added to a Semantics widget', (WidgetTester tester) async {
final SemanticsHandle semantics = tester.ensureSemantics();
await tester.pumpWidget(Semantics(
container: true,
customSemanticsActions: <CustomSemanticsAction, VoidCallback>{
const CustomSemanticsAction(label: 'foo'): () { },
const CustomSemanticsAction(label: 'bar'): () { },
},
));
expect(tester.getSemantics(find.byType(Semantics)), matchesSemantics(
customActions: <CustomSemanticsAction>[
const CustomSemanticsAction(label: 'bar'),
const CustomSemanticsAction(label: 'foo'),
],
));
semantics.dispose();
});
testWidgets('Increased/decreased values are annotated', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
container: true,
value: '10s',
increasedValue: '11s',
decreasedValue: '9s',
onIncrease: () => () { },
onDecrease: () => () { },
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
actions: SemanticsAction.increase.index | SemanticsAction.decrease.index,
textDirection: TextDirection.ltr,
value: '10s',
increasedValue: '11s',
decreasedValue: '9s',
),
],
), ignoreTransform: true, ignoreRect: true, ignoreId: true));
semantics.dispose();
});
testWidgets('Semantics widgets built in a widget tree are sorted properly', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
int semanticsUpdateCount = 0;
final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics(
listener: () {
semanticsUpdateCount += 1;
},
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Semantics(
sortKey: const CustomSortKey(0.0),
explicitChildNodes: true,
child: Column(
children: <Widget>[
Semantics(sortKey: const CustomSortKey(3.0), child: const Text('Label 1')),
Semantics(sortKey: const CustomSortKey(2.0), child: const Text('Label 2')),
Semantics(
sortKey: const CustomSortKey(1.0),
explicitChildNodes: true,
child: Row(
children: <Widget>[
Semantics(sortKey: const OrdinalSortKey(3.0), child: const Text('Label 3')),
Semantics(sortKey: const OrdinalSortKey(2.0), child: const Text('Label 4')),
Semantics(sortKey: const OrdinalSortKey(1.0), child: const Text('Label 5')),
],
),
),
],
),
),
),
);
expect(semanticsUpdateCount, 1);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
id: 1,
children: <TestSemantics>[
TestSemantics(
id: 4,
children: <TestSemantics>[
TestSemantics(
id: 7,
label: r'Label 5',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 6,
label: r'Label 4',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 5,
label: r'Label 3',
textDirection: TextDirection.ltr,
),
],
),
TestSemantics(
id: 3,
label: r'Label 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 2,
label: r'Label 1',
textDirection: TextDirection.ltr,
),
],
),
],
),
ignoreTransform: true,
ignoreRect: true,
));
handle.dispose();
semantics.dispose();
});
testWidgets('Semantics widgets built with explicit sort orders are sorted properly', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
int semanticsUpdateCount = 0;
final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics(
listener: () {
semanticsUpdateCount += 1;
},
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Row(
children: <Widget>[
Semantics(
sortKey: const CustomSortKey(3.0),
child: const Text('Label 1'),
),
Semantics(
sortKey: const CustomSortKey(1.0),
child: const Text('Label 2'),
),
Semantics(
sortKey: const CustomSortKey(2.0),
child: const Text('Label 3'),
),
],
),
),
);
expect(semanticsUpdateCount, 1);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
id: 2,
label: r'Label 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 3,
label: r'Label 3',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 1,
label: r'Label 1',
textDirection: TextDirection.ltr,
),
],
),
ignoreTransform: true,
ignoreRect: true,
));
handle.dispose();
semantics.dispose();
});
testWidgets('Semantics widgets without sort orders are sorted properly', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
int semanticsUpdateCount = 0;
final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics(
listener: () {
semanticsUpdateCount += 1;
},
);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
Text('Label 1'),
Text('Label 2'),
Row(
children: <Widget>[
Text('Label 3'),
Text('Label 4'),
Text('Label 5'),
],
),
],
),
),
);
expect(semanticsUpdateCount, 1);
expect(semantics, hasSemantics(
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: r'Label 1',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: r'Label 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: r'Label 3',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: r'Label 4',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: r'Label 5',
textDirection: TextDirection.ltr,
),
],
),
ignoreTransform: true,
ignoreRect: true,
ignoreId: true,
));
handle.dispose();
semantics.dispose();
});
testWidgets('Semantics widgets that are transformed are sorted properly', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
int semanticsUpdateCount = 0;
final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics(
listener: () {
semanticsUpdateCount += 1;
},
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
const Text('Label 1'),
const Text('Label 2'),
Transform.rotate(
angle: pi / 2.0,
child: const Row(
children: <Widget>[
Text('Label 3'),
Text('Label 4'),
Text('Label 5'),
],
),
),
],
),
),
);
expect(semanticsUpdateCount, 1);
expect(semantics, hasSemantics(
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: r'Label 1',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: r'Label 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: r'Label 3',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: r'Label 4',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: r'Label 5',
textDirection: TextDirection.ltr,
),
],
),
ignoreTransform: true,
ignoreRect: true,
ignoreId: true,
));
handle.dispose();
semantics.dispose();
});
testWidgets('Semantics widgets without sort orders are sorted properly when no Directionality is present', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
int semanticsUpdateCount = 0;
final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics(listener: () {
semanticsUpdateCount += 1;
});
await tester.pumpWidget(
Stack(
alignment: Alignment.center,
children: <Widget>[
// Set this up so that the placeholder takes up the whole screen,
// and place the positioned boxes so that if we traverse in the
// geometric order, we would go from box [4, 3, 2, 1, 0], but if we
// go in child order, then we go from box [4, 1, 2, 3, 0]. We're verifying
// that we go in child order here, not geometric order, since there
// is no directionality, so we don't have a geometric opinion about
// horizontal order. We do still want to sort vertically, however,
// which is why the order isn't [0, 1, 2, 3, 4].
Semantics(
button: true,
child: const Placeholder(),
),
Positioned(
top: 200.0,
left: 100.0,
child: Semantics( // Box 0
button: true,
child: const SizedBox(width: 30.0, height: 30.0),
),
),
Positioned(
top: 100.0,
left: 200.0,
child: Semantics( // Box 1
button: true,
child: const SizedBox(width: 30.0, height: 30.0),
),
),
Positioned(
top: 100.0,
left: 100.0,
child: Semantics( // Box 2
button: true,
child: const SizedBox(width: 30.0, height: 30.0),
),
),
Positioned(
top: 100.0,
left: 0.0,
child: Semantics( // Box 3
button: true,
child: const SizedBox(width: 30.0, height: 30.0),
),
),
Positioned(
top: 10.0,
left: 100.0,
child: Semantics( // Box 4
button: true,
child: const SizedBox(width: 30.0, height: 30.0),
),
),
],
),
);
expect(semanticsUpdateCount, 1);
expect(
semantics,
hasSemantics(
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isButton],
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isButton],
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isButton],
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isButton],
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isButton],
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isButton],
),
],
),
ignoreTransform: true,
ignoreRect: true,
ignoreId: true,
),
);
handle.dispose();
semantics.dispose();
});
testWidgets('Semantics excludeSemantics ignores children', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(Semantics(
label: 'label',
excludeSemantics: true,
textDirection: TextDirection.ltr,
child: Semantics(
label: 'other label',
textDirection: TextDirection.ltr,
),
));
expect(semantics, hasSemantics(
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: 'label',
textDirection: TextDirection.ltr,
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
));
semantics.dispose();
});
testWidgets('Can change handlers', (WidgetTester tester) async {
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onTap: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasTapAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onDismiss: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasDismissAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onLongPress: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasLongPressAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onScrollLeft: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasScrollLeftAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onScrollRight: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasScrollRightAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onScrollUp: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasScrollUpAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onScrollDown: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasScrollDownAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onIncrease: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasIncreaseAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onDecrease: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasDecreaseAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onCopy: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasCopyAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onCut: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasCutAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onPaste: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasPasteAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onSetSelection: (TextSelection _) {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasSetSelectionAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onDidGainAccessibilityFocus: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasDidGainAccessibilityFocusAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
onDidLoseAccessibilityFocus: () {},
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
hasDidLoseAccessibilityFocusAction: true,
textDirection: TextDirection.ltr,
));
await tester.pumpWidget(Semantics(
container: true,
label: 'foo',
textDirection: TextDirection.ltr,
));
expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics(
label: 'foo',
textDirection: TextDirection.ltr,
));
});
testWidgets('Semantics with zero transform gets dropped', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/110671.
// Construct a widget tree that will end up with a fitted box that applies
// a zero transform because it does not actually draw its children.
// Assert that this subtree gets dropped (the root node has no children).
await tester.pumpWidget(const Column(
children: <Widget>[
SizedBox(
height: 0,
width: 500,
child: FittedBox(
child: SizedBox(
height: 55,
width: 266,
child: SingleChildScrollView(child: Column()),
),
),
),
],
));
final SemanticsNode node = RendererBinding.instance.renderView.debugSemantics!;
expect(node.transform, null); // Make sure the zero transform didn't end up on the root somehow.
expect(node.childrenCount, 0);
});
testWidgets('blocking user interaction works on explicit child node.', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Semantics(
blockUserActions: true,
explicitChildNodes: true,
child: Column(
children: <Widget>[
Semantics(
key: key1,
label: 'label1',
onTap: () {},
child: const SizedBox(width: 10, height: 10),
),
Semantics(
key: key2,
label: 'label2',
onTap: () {},
child: const SizedBox(width: 10, height: 10),
),
],
),
),
),
);
expect(
tester.getSemantics(find.byKey(key1)),
// Tap action is blocked.
matchesSemantics(
label: 'label1',
),
);
expect(
tester.getSemantics(find.byKey(key2)),
// Tap action is blocked.
matchesSemantics(
label: 'label2',
),
);
});
testWidgets('blocking user interaction on a merged child', (WidgetTester tester) async {
final UniqueKey key = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Semantics(
key: key,
container: true,
child: Column(
children: <Widget>[
Semantics(
blockUserActions: true,
label: 'label1',
onTap: () { },
child: const SizedBox(width: 10, height: 10),
),
Semantics(
label: 'label2',
onLongPress: () { },
child: const SizedBox(width: 10, height: 10),
),
],
),
),
),
);
expect(
tester.getSemantics(find.byKey(key)),
// Tap action in label1 is blocked,
matchesSemantics(
label: 'label1\nlabel2',
hasLongPressAction: true,
),
);
});
testWidgets('does not merge conflicting actions even if one of them is blocked', (WidgetTester tester) async {
final UniqueKey key = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Semantics(
key: key,
container: true,
child: Column(
children: <Widget>[
Semantics(
blockUserActions: true,
label: 'label1',
onTap: () { },
child: const SizedBox(width: 10, height: 10),
),
Semantics(
label: 'label2',
onTap: () { },
child: const SizedBox(width: 10, height: 10),
),
],
),
),
),
);
final SemanticsNode node = tester.getSemantics(find.byKey(key));
expect(
node,
matchesSemantics(
children: <Matcher>[containsSemantics(label: 'label1'), containsSemantics(label: 'label2')],
),
);
});
}
class CustomSortKey extends OrdinalSortKey {
const CustomSortKey(super.order, {super.name});
}
| flutter/packages/flutter/test/widgets/semantics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_test.dart",
"repo_id": "flutter",
"token_count": 23671
} | 691 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../rendering/rendering_tester.dart' show TestClipPaintingContext;
void main() {
testWidgets('ShrinkWrappingViewport respects clipBehavior', (WidgetTester tester) async {
Widget build(ShrinkWrappingViewport child) {
return Directionality(
textDirection: TextDirection.ltr,
child: child,
);
}
final ViewportOffset offset1 = ViewportOffset.zero();
addTearDown(offset1.dispose);
await tester.pumpWidget(build(
ShrinkWrappingViewport(
offset: offset1,
slivers: <Widget>[SliverToBoxAdapter(child: Container(height: 2000.0))],
),
));
// 1st, check that the render object has received the default clip behavior.
final RenderShrinkWrappingViewport renderObject = tester.allRenderObjects.whereType<RenderShrinkWrappingViewport>().first;
expect(renderObject.clipBehavior, equals(Clip.hardEdge));
// 2nd, check that the painting context has received the default clip behavior.
final TestClipPaintingContext context = TestClipPaintingContext();
renderObject.paint(context, Offset.zero);
expect(context.clipBehavior, equals(Clip.hardEdge));
final ViewportOffset offset2 = ViewportOffset.zero();
addTearDown(offset2.dispose);
// 3rd, pump a new widget to check that the render object can update its clip behavior.
await tester.pumpWidget(build(
ShrinkWrappingViewport(
offset: offset2,
slivers: <Widget>[SliverToBoxAdapter(child: Container(height: 2000.0))],
clipBehavior: Clip.antiAlias,
),
));
expect(renderObject.clipBehavior, equals(Clip.antiAlias));
// 4th, check that a non-default clip behavior can be sent to the painting context.
renderObject.paint(context, Offset.zero);
expect(context.clipBehavior, equals(Clip.antiAlias));
});
}
| flutter/packages/flutter/test/widgets/shrink_wrapping_viewport_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/shrink_wrapping_viewport_test.dart",
"repo_id": "flutter",
"token_count": 734
} | 692 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
class TestState extends StatefulWidget {
const TestState({ super.key, required this.child, required this.log });
final Widget child;
final List<String> log;
@override
State<TestState> createState() => _TestStateState();
}
class _TestStateState extends State<TestState> {
@override
void initState() {
super.initState();
widget.log.add('created new state');
}
@override
Widget build(BuildContext context) {
return widget.child;
}
}
void main() {
testWidgets('SliverVisibility', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final List<String> log = <String>[];
const Key anchor = Key('drag');
Widget boilerPlate(Widget sliver) {
return Localizations(
locale: const Locale('en', 'us'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
],
child: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: CustomScrollView(slivers: <Widget>[sliver]),
),
),
);
}
final Widget testChild = SliverToBoxAdapter(
child: GestureDetector(
onTap: () {
log.add('tap');
},
child: Builder(
builder: (BuildContext context) {
final bool animating = TickerMode.of(context);
return TestState(
key: anchor,
log: log,
child: Text('a $animating', textDirection: TextDirection.rtl),
);
},
),
),
);
// We now run a sequence of pumpWidget calls one after the other. In
// addition to verifying that the right behavior is seen in each case, this
// also verifies that the widget can dynamically change from state to state.
// Default
await tester.pumpWidget(boilerPlate(SliverVisibility(sliver: testChild)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paints..paragraph());
RenderViewport renderViewport = tester.renderObject(find.byType(Viewport));
RenderSliver renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>['created new state']);
await tester.tap(find.byKey(anchor));
expect(log, <String>['created new state', 'tap']);
log.clear();
// visible: false
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
)));
expect(find.byType(Text), findsNothing);
expect(find.byType(Text, skipOffstage: false), findsNothing);
expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 0.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(0));
expect(log, <String>[]);
expect(find.byKey(anchor), findsNothing);
log.clear();
// visible: false, with replacementSliver
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
replacementSliver: const SliverToBoxAdapter(child: Placeholder()),
visible: false,
)));
expect(find.byType(Text, skipOffstage: false), findsNothing);
expect(find.byType(Placeholder), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paints..path());
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 400.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(0));
expect(log, <String>[]);
expect(find.byKey(anchor), findsNothing);
log.clear();
// visible: true, with replacementSliver
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
replacementSliver: const SliverToBoxAdapter(child: Placeholder()),
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(Placeholder), findsNothing);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paints..paragraph());
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>['created new state']);
await tester.tap(find.byKey(anchor));
expect(log, <String>['created new state', 'tap']);
log.clear();
// visible: true, maintain all
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
maintainState: true,
maintainAnimation: true,
maintainSize: true,
maintainInteractivity: true,
maintainSemantics: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paints..paragraph());
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>['created new state']);
await tester.tap(find.byKey(anchor));
expect(log, <String>['created new state', 'tap']);
log.clear();
// visible: false, maintain all
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
maintainState: true,
maintainAnimation: true,
maintainSize: true,
maintainInteractivity: true,
maintainSemantics: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>[]);
await tester.tap(find.byKey(anchor));
expect(log, <String>['tap']);
log.clear();
// visible: false, maintain all, replacementSliver
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
replacementSliver: const SliverToBoxAdapter(child: Placeholder()),
visible: false,
maintainState: true,
maintainAnimation: true,
maintainSize: true,
maintainInteractivity: true,
maintainSemantics: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(Placeholder), findsNothing);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>[]);
await tester.tap(find.byKey(anchor));
expect(log, <String>['tap']);
log.clear();
// visible: false, maintain all but semantics
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
maintainState: true,
maintainAnimation: true,
maintainSize: true,
maintainInteractivity: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(0));
expect(log, <String>[]);
await tester.tap(find.byKey(anchor));
expect(log, <String>['tap']);
log.clear();
// visible: false, maintain all but interactivity
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
maintainState: true,
maintainAnimation: true,
maintainSize: true,
maintainSemantics: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>[]);
await tester.tap(find.byKey(anchor), warnIfMissed: false);
expect(log, <String>[]);
log.clear();
// visible: false, maintain state, animation, size.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
maintainState: true,
maintainAnimation: true,
maintainSize: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(0));
expect(log, <String>[]);
await tester.tap(find.byKey(anchor), warnIfMissed: false);
expect(log, <String>[]);
log.clear();
// visible: false, maintain state and animation.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
maintainState: true,
maintainAnimation: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.byType(Text), findsNothing);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 0.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(0));
expect(log, <String>['created new state']);
expect(find.byKey(anchor), findsNothing);
log.clear();
// visible: false, maintain state.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
maintainState: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.byType(Text), findsNothing);
expect(find.text('a false', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 0.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(0));
expect(log, <String>['created new state']);
expect(find.byKey(anchor), findsNothing);
log.clear();
// Now we toggle the visibility off and on a few times to make sure that
// works.
// visible: true, maintain state
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
maintainState: true,
)));
expect(find.byType(Text), findsOneWidget);
expect(find.text('a true'), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paints..paragraph());
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>[]);
await tester.tap(find.byKey(anchor));
expect(log, <String>['tap']);
log.clear();
// visible: false, maintain state.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
maintainState: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.byType(Text), findsNothing);
expect(find.text('a false', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 0.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a false'), hasLength(0));
expect(log, <String>[]);
expect(find.byKey(anchor), findsNothing);
log.clear();
// visible: true, maintain state.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
maintainState: true,
)));
expect(find.byType(Text), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), paints..paragraph());
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>[]);
await tester.tap(find.byKey(anchor));
expect(log, <String>['tap']);
log.clear();
// visible: false, maintain state.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
maintainState: true,
)));
expect(find.byType(Text, skipOffstage: false), findsOneWidget);
expect(find.byType(Text), findsNothing);
expect(find.text('a false', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 0.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a false'), hasLength(0));
expect(log, <String>[]);
expect(find.byKey(anchor), findsNothing);
log.clear();
// Same but without maintainState.
// visible: false.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
)));
expect(find.byType(Text, skipOffstage: false), findsNothing);
expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 0.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(0));
expect(log, <String>[]);
expect(find.byKey(anchor), findsNothing);
log.clear();
// visible: true.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
)));
expect(find.byType(Text), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paints..paragraph());
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>['created new state']);
await tester.tap(find.byKey(anchor));
expect(log, <String>['created new state', 'tap']);
log.clear();
//visible: false.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
visible: false,
)));
expect(find.byType(Text, skipOffstage: false), findsNothing);
expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing);
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 0.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(0));
expect(log, <String>[]);
expect(find.byKey(anchor), findsNothing);
log.clear();
// visible: true.
await tester.pumpWidget(boilerPlate(SliverVisibility(
sliver: testChild,
)));
expect(find.byType(Text), findsOneWidget);
expect(find.text('a true', skipOffstage: false), findsOneWidget);
expect(find.byType(SliverVisibility), findsOneWidget);
expect(find.byType(SliverVisibility), paints..paragraph());
renderViewport = tester.renderObject(find.byType(Viewport));
renderSliver = renderViewport.lastChild!;
expect(renderSliver.geometry!.scrollExtent, 14.0);
expect(renderSliver.constraints.crossAxisExtent, 800.0);
expect(semantics.nodesWith(label: 'a true'), hasLength(1));
expect(log, <String>['created new state']);
await tester.tap(find.byKey(anchor));
expect(log, <String>['created new state', 'tap']);
log.clear();
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/sliver_visibility_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/sliver_visibility_test.dart",
"repo_id": "flutter",
"token_count": 7366
} | 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/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
late TextStyle composingStyle;
late TextStyle misspelledTextStyle;
void main() {
setUp(() {
composingStyle = const TextStyle(decoration: TextDecoration.underline);
// Using Android handling for testing.
misspelledTextStyle = TextField.materialMisspelledTextStyle;
});
testWidgets(
'buildTextSpanWithSpellCheckSuggestions ignores composing region when composing region out of range',
(WidgetTester tester) async {
const String text = 'Hello, wrold! Hey';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = true;
const SpellCheckResults spellCheckResults =
SpellCheckResults(text, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions, isolated misspelled word with separate composing region example',
(WidgetTester tester) async {
const String text = 'Hello, wrold! Hey';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 14, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(text, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! '),
TextSpan(style: composingStyle, text: 'Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions, composing region and misspelled words overlap example',
(WidgetTester tester) async {
const String text = 'Right worng worng right';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 12, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(text, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 6, end: 11), <String>['wrong', 'worn', 'wrung']),
SuggestionSpan(
TextRange(start: 12, end: 17), <String>['wrong', 'worn', 'wrung'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Right '),
TextSpan(style: misspelledTextStyle, text: 'worng'),
const TextSpan(text: ' '),
TextSpan(style: composingStyle, text: 'worng'),
const TextSpan(text: ' right'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions, consecutive misspelled words example',
(WidgetTester tester) async {
const String text = 'Right worng worng right';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = true;
const SpellCheckResults spellCheckResults =
SpellCheckResults(text, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 6, end: 11), <String>['wrong', 'worn', 'wrung']),
SuggestionSpan(
TextRange(start: 12, end: 17), <String>['wrong', 'worn', 'wrung'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Right '),
TextSpan(style: misspelledTextStyle, text: 'worng'),
const TextSpan(text: ' '),
TextSpan(style: misspelledTextStyle, text: 'worng'),
const TextSpan(text: ' right'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text shorter than actual text example',
(WidgetTester tester) async {
const String text = 'Hello, wrold! Hey';
const String resultsText = 'Hello, wrold!';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! Hey'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text longer with more misspelled words than actual text example',
(WidgetTester tester) async {
const String text = 'Hello, wrold! Hey';
const String resultsText = 'Hello, wrold Hey feirnd!';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old']),
SuggestionSpan(
TextRange(start: 17, end: 23), <String>['friend', 'fiend', 'fern'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! Hey'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text mismatched example',
(WidgetTester tester) async {
const String text = 'Hello, wrold! Hey';
const String resultsText = 'Hello, wrild! Hey';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(TextRange(start: 7, end: 12), <String>['wild', 'world']),
]);
const TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
TextSpan(text: 'Hello, wrold! Hey'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted forward example',
(WidgetTester tester) async {
const String text = 'Hello, there wrold! Hey';
const String resultsText = 'Hello, wrold! Hey';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old']),
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, there '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! Hey'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted backwards example',
(WidgetTester tester) async {
const String text = 'Hello, wrold! Hey';
const String resultsText = 'Hello, great wrold! Hey';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 13, end: 18), <String>['world', 'word', 'old']),
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! Hey'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted backwards and forwards example',
(WidgetTester tester) async {
const String text = 'Hello, wrold! And Hye!';
const String resultsText = 'Hello, great wrold! Hye!';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 13, end: 18), <String>['world', 'word', 'old']),
SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! And '),
TextSpan(style: misspelledTextStyle, text: 'Hye'),
const TextSpan(text: '!')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions discards result when additions are made to misspelled word example',
(WidgetTester tester) async {
const String text = 'Hello, wroldd!';
const String resultsText = 'Hello, wrold!';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old']),
]);
const TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
TextSpan(text: 'Hello, wroldd!'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }));
testWidgets(
'buildTextSpanWithSpellCheckSuggestions does not throw when text contains regex reserved characters',
(WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/136032.
const String text = 'Hello, *ãresaa';
const String resultsText = 'Hello, *ãresa';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults = SpellCheckResults(
resultsText,
<SuggestionSpan>[
SuggestionSpan(TextRange(start: 7, end: 12), <String>['*rangesa']),
],
);
const TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
TextSpan(text: 'Hello, *ãresaa'),
]);
final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(tester.takeException(), null);
expect(textSpanTree, equals(expectedTextSpanTree));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }),
);
}
| flutter/packages/flutter/test/widgets/spell_check_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/spell_check_test.dart",
"repo_id": "flutter",
"token_count": 5581
} | 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/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/platform.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/editable_text_utils.dart';
Finder findCupertinoOverflowNextButton() {
return find.byWidgetPredicate((Widget widget) {
return widget is CustomPaint && '${widget.painter?.runtimeType}' == '_RightCupertinoChevronPainter';
});
}
Finder findCupertinoOverflowBackButton() {
return find.byWidgetPredicate((Widget widget) {
return widget is CustomPaint && '${widget.painter?.runtimeType}' == '_LeftCupertinoChevronPainter';
});
}
Future<void> tapCupertinoOverflowNextButton(WidgetTester tester) async{
await tester.tapAt(tester.getCenter(findCupertinoOverflowNextButton()));
await tester.pumpAndSettle();
}
void expectNoCupertinoToolbar() {
expect(find.byType(CupertinoButton), findsNothing);
}
// Check that the Cupertino text selection toolbars show the expected buttons
// when the content is partially selected.
void expectCupertinoToolbarForPartialSelection() {
if (isContextMenuProvidedByPlatform) {
expectNoCupertinoToolbar();
return;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
expect(find.byType(CupertinoButton), findsNWidgets(5));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share...'), findsOneWidget);
expect(find.text('Select All'), findsOneWidget);
case TargetPlatform.iOS:
expect(find.byType(CupertinoButton), findsNWidgets(6));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share...'), findsOneWidget);
expect(find.text('Look Up'), findsOneWidget);
expect(find.text('Search Web'), findsOneWidget);
case TargetPlatform.macOS:
expect(find.byType(CupertinoButton), findsNWidgets(3));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(find.byType(CupertinoButton), findsNWidgets(4));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select All'), findsOneWidget);
}
}
// Check that the Cupertino text selection toolbar shows the expected buttons
// when the content is fully selected.
void expectCupertinoToolbarForFullSelection() {
if (isContextMenuProvidedByPlatform) {
expectNoCupertinoToolbar();
return;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
expect(find.byType(CupertinoButton), findsNWidgets(4));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share...'), findsOneWidget);
case TargetPlatform.iOS:
expect(find.byType(CupertinoButton), findsNWidgets(6));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share...'), findsOneWidget);
expect(find.text('Look Up'), findsOneWidget);
expect(find.text('Search Web'), findsOneWidget);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
expect(find.byType(CupertinoButton), findsNWidgets(3));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
}
}
// Check that the Cupertino text selection toolbar is correct for a collapsed selection.
void expectCupertinoToolbarForCollapsedSelection() {
if (isContextMenuProvidedByPlatform) {
expectNoCupertinoToolbar();
return;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
expect(find.byType(CupertinoButton), findsNWidgets(4));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share...'), findsOneWidget);
case TargetPlatform.iOS:
expect(find.byType(CupertinoButton), findsNWidgets(2));
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select All'), findsOneWidget);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
case TargetPlatform.macOS:
expect(find.byType(CupertinoButton), findsNWidgets(1));
expect(find.text('Paste'), findsOneWidget);
}
}
void expectNoMaterialToolbar() {
expect(find.byType(TextButton), findsNothing);
}
// Check that the Material text selection toolbars show the expected buttons
// when the content is partially selected.
void expectMaterialToolbarForPartialSelection() {
if (isContextMenuProvidedByPlatform) {
expectNoMaterialToolbar();
return;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
expect(find.byType(TextButton), findsNWidgets(5));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
case TargetPlatform.iOS:
case TargetPlatform.macOS:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(find.byType(TextButton), findsNWidgets(4));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
}
}
// Check that the Material text selection toolbar shows the expected buttons
// when the content is fully selected.
void expectMaterialToolbarForFullSelection() {
if (isContextMenuProvidedByPlatform) {
expectNoMaterialToolbar();
return;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
expect(find.byType(TextButton), findsNWidgets(4));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Share'), findsOneWidget);
case TargetPlatform.iOS:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
expect(find.byType(TextButton), findsNWidgets(3));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
}
}
Finder findMaterialOverflowNextButton() {
return find.byIcon(Icons.more_vert);
}
Finder findMaterialOverflowBackButton() {
return find.byIcon(Icons.arrow_back);
}
Future<void> tapMaterialOverflowNextButton(WidgetTester tester) async {
await tester.tapAt(tester.getCenter(findMaterialOverflowNextButton()));
await tester.pumpAndSettle();
}
| flutter/packages/flutter/test/widgets/text_selection_toolbar_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/text_selection_toolbar_utils.dart",
"repo_id": "flutter",
"token_count": 2576
} | 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'editable_text_utils.dart';
final FocusNode _focusNode = FocusNode(debugLabel: 'UndoHistory Node');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('UndoHistory', () {
Future<void> sendUndoRedo(WidgetTester tester, [bool redo = false]) {
return sendKeys(
tester,
<LogicalKeyboardKey>[
LogicalKeyboardKey.keyZ,
],
shortcutModifier: true,
shift: redo,
targetPlatform: defaultTargetPlatform,
);
}
Future<void> sendUndo(WidgetTester tester) => sendUndoRedo(tester);
Future<void> sendRedo(WidgetTester tester) => sendUndoRedo(tester, true);
testWidgets('allows undo and redo to be called programmatically from the UndoHistoryController', (WidgetTester tester) async {
final ValueNotifier<int> value = ValueNotifier<int>(0);
addTearDown(value.dispose);
final UndoHistoryController controller = UndoHistoryController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: UndoHistory<int>(
value: value,
controller: controller,
onTriggered: (int newValue) {
value.value = newValue;
},
focusNode: _focusNode,
child: Container(),
),
),
);
await tester.pump(const Duration(milliseconds: 500));
// Undo/redo have no effect if the value has never changed.
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 0);
controller.redo();
expect(value.value, 0);
_focusNode.requestFocus();
await tester.pump();
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 0);
controller.redo();
expect(value.value, 0);
value.value = 1;
// Wait for the throttling.
await tester.pump(const Duration(milliseconds: 500));
// Can undo/redo a single change.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 0);
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, true);
controller.redo();
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
value.value = 2;
await tester.pump(const Duration(milliseconds: 500));
// And can undo/redo multiple changes.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
controller.undo();
expect(value.value, 0);
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, true);
controller.redo();
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
controller.redo();
expect(value.value, 2);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
// Changing the value again clears the redo stack.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
value.value = 3;
await tester.pump(const Duration(milliseconds: 500));
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
}, variant: TargetPlatformVariant.all());
testWidgets('allows undo and redo to be called using the keyboard', (WidgetTester tester) async {
final ValueNotifier<int> value = ValueNotifier<int>(0);
addTearDown(value.dispose);
final UndoHistoryController controller = UndoHistoryController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: UndoHistory<int>(
controller: controller,
value: value,
onTriggered: (int newValue) {
value.value = newValue;
},
focusNode: _focusNode,
child: Focus(
focusNode: _focusNode,
child: Container(),
),
),
),
);
await tester.pump(const Duration(milliseconds: 500));
// Undo/redo have no effect if the value has never changed.
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, false);
await sendUndo(tester);
expect(value.value, 0);
await sendRedo(tester);
expect(value.value, 0);
_focusNode.requestFocus();
await tester.pump();
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, false);
await sendUndo(tester);
expect(value.value, 0);
await sendRedo(tester);
expect(value.value, 0);
value.value = 1;
// Wait for the throttling.
await tester.pump(const Duration(milliseconds: 500));
// Can undo/redo a single change.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
await sendUndo(tester);
expect(value.value, 0);
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, true);
await sendRedo(tester);
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
value.value = 2;
await tester.pump(const Duration(milliseconds: 500));
// And can undo/redo multiple changes.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
await sendUndo(tester);
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
await sendUndo(tester);
expect(value.value, 0);
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, true);
await sendRedo(tester);
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
await sendRedo(tester);
expect(value.value, 2);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
// Changing the value again clears the redo stack.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
await sendUndo(tester);
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
value.value = 3;
await tester.pump(const Duration(milliseconds: 500));
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
}, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended]
testWidgets('duplicate changes do not affect the undo history', (WidgetTester tester) async {
final ValueNotifier<int> value = ValueNotifier<int>(0);
addTearDown(value.dispose);
final UndoHistoryController controller = UndoHistoryController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: UndoHistory<int>(
controller: controller,
value: value,
onTriggered: (int newValue) {
value.value = newValue;
},
focusNode: _focusNode,
child: Container(),
),
),
);
_focusNode.requestFocus();
// Wait for the throttling.
await tester.pump(const Duration(milliseconds: 500));
value.value = 1;
// Wait for the throttling.
await tester.pump(const Duration(milliseconds: 500));
// Can undo/redo a single change.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 0);
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, true);
controller.redo();
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
// Changes that result in the same state won't be saved on the undo stack.
value.value = 1;
await tester.pump(const Duration(milliseconds: 500));
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 0);
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, true);
}, variant: TargetPlatformVariant.all());
testWidgets('ignores value changes pushed during onTriggered', (WidgetTester tester) async {
final ValueNotifier<int> value = ValueNotifier<int>(0);
addTearDown(value.dispose);
final UndoHistoryController controller = UndoHistoryController();
addTearDown(controller.dispose);
int Function(int newValue) valueToUse = (int value) => value;
final GlobalKey<UndoHistoryState<int>> key = GlobalKey<UndoHistoryState<int>>();
await tester.pumpWidget(
MaterialApp(
home: UndoHistory<int>(
key: key,
value: value,
controller: controller,
onTriggered: (int newValue) {
value.value = valueToUse(newValue);
},
focusNode: _focusNode,
child: Container(),
),
),
);
await tester.pump(const Duration(milliseconds: 500));
// Undo/redo have no effect if the value has never changed.
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 0);
controller.redo();
expect(value.value, 0);
_focusNode.requestFocus();
await tester.pump();
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, false);
controller.undo();
expect(value.value, 0);
controller.redo();
expect(value.value, 0);
value.value = 1;
// Wait for the throttling.
await tester.pump(const Duration(milliseconds: 500));
valueToUse = (int value) => 3;
expect(() => key.currentState!.undo(), throwsAssertionError);
}, variant: TargetPlatformVariant.all());
testWidgets('changes should send setUndoState to the UndoManagerConnection on iOS', (WidgetTester tester) async {
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.undoManager, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
final ValueNotifier<int> value = ValueNotifier<int>(0);
addTearDown(value.dispose);
final UndoHistoryController controller = UndoHistoryController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: UndoHistory<int>(
controller: controller,
value: value,
onTriggered: (int newValue) {
value.value = newValue;
},
focusNode: focusNode,
child: Focus(
focusNode: focusNode,
child: Container(),
),
),
),
);
await tester.pump();
focusNode.requestFocus();
await tester.pump();
// Wait for the throttling.
await tester.pump(const Duration(milliseconds: 500));
// Undo and redo should both be disabled.
MethodCall methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState');
expect(methodCall.method, 'UndoManager.setUndoState');
expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': false, 'canRedo': false});
// Making a change should enable undo.
value.value = 1;
await tester.pump(const Duration(milliseconds: 500));
methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState');
expect(methodCall.method, 'UndoManager.setUndoState');
expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': true, 'canRedo': false});
// Undo should remain enabled after another change.
value.value = 2;
await tester.pump(const Duration(milliseconds: 500));
methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState');
expect(methodCall.method, 'UndoManager.setUndoState');
expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': true, 'canRedo': false});
// Undo and redo should be enabled after one undo.
controller.undo();
methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState');
expect(methodCall.method, 'UndoManager.setUndoState');
expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': true, 'canRedo': true});
// Only redo should be enabled after a second undo.
controller.undo();
methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState');
expect(methodCall.method, 'UndoManager.setUndoState');
expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': false, 'canRedo': true});
}, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), skip: kIsWeb); // [intended]
testWidgets('handlePlatformUndo should undo or redo appropriately on iOS', (WidgetTester tester) async {
final ValueNotifier<int> value = ValueNotifier<int>(0);
addTearDown(value.dispose);
final UndoHistoryController controller = UndoHistoryController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: UndoHistory<int>(
controller: controller,
value: value,
onTriggered: (int newValue) {
value.value = newValue;
},
focusNode: _focusNode,
child: Focus(
focusNode: _focusNode,
child: Container(),
),
),
),
);
await tester.pump(const Duration(milliseconds: 500));
_focusNode.requestFocus();
await tester.pump();
// Undo/redo have no effect if the value has never changed.
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, false);
UndoManager.client!.handlePlatformUndo(UndoDirection.undo);
expect(value.value, 0);
UndoManager.client!.handlePlatformUndo(UndoDirection.redo);
expect(value.value, 0);
value.value = 1;
// Wait for the throttling.
await tester.pump(const Duration(milliseconds: 500));
// Can undo/redo a single change.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
UndoManager.client!.handlePlatformUndo(UndoDirection.undo);
expect(value.value, 0);
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, true);
UndoManager.client!.handlePlatformUndo(UndoDirection.redo);
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
value.value = 2;
await tester.pump(const Duration(milliseconds: 500));
// And can undo/redo multiple changes.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
UndoManager.client!.handlePlatformUndo(UndoDirection.undo);
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
UndoManager.client!.handlePlatformUndo(UndoDirection.undo);
expect(value.value, 0);
expect(controller.value.canUndo, false);
expect(controller.value.canRedo, true);
UndoManager.client!.handlePlatformUndo(UndoDirection.redo);
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
UndoManager.client!.handlePlatformUndo(UndoDirection.redo);
expect(value.value, 2);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
// Changing the value again clears the redo stack.
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
UndoManager.client!.handlePlatformUndo(UndoDirection.undo);
expect(value.value, 1);
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, true);
value.value = 3;
await tester.pump(const Duration(milliseconds: 500));
expect(controller.value.canUndo, true);
expect(controller.value.canRedo, false);
}, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), skip: kIsWeb); // [intended]
});
group('UndoHistoryController', () {
testWidgets('UndoHistoryController notifies onUndo listeners onUndo', (WidgetTester tester) async {
int calls = 0;
final UndoHistoryController controller = UndoHistoryController();
addTearDown(controller.dispose);
controller.onUndo.addListener(() {
calls++;
});
// Does not notify the listener if canUndo is false.
controller.undo();
expect(calls, 0);
// Does notify the listener if canUndo is true.
controller.value = const UndoHistoryValue(canUndo: true);
controller.undo();
expect(calls, 1);
});
testWidgets('UndoHistoryController notifies onRedo listeners onRedo', (WidgetTester tester) async {
int calls = 0;
final UndoHistoryController controller = UndoHistoryController();
addTearDown(controller.dispose);
controller.onRedo.addListener(() {
calls++;
});
// Does not notify the listener if canUndo is false.
controller.redo();
expect(calls, 0);
// Does notify the listener if canRedo is true.
controller.value = const UndoHistoryValue(canRedo: true);
controller.redo();
expect(calls, 1);
});
testWidgets('UndoHistoryController notifies listeners on value change', (WidgetTester tester) async {
int calls = 0;
final UndoHistoryController controller = UndoHistoryController(value: const UndoHistoryValue(canUndo: true));
addTearDown(controller.dispose);
controller.addListener(() {
calls++;
});
// Does not notify if the value is the same.
controller.value = const UndoHistoryValue(canUndo: true);
expect(calls, 0);
// Does notify if the value has changed.
controller.value = const UndoHistoryValue(canRedo: true);
expect(calls, 1);
});
});
}
| flutter/packages/flutter/test/widgets/undo_history_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/undo_history_test.dart",
"repo_id": "flutter",
"token_count": 7778
} | 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 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
// Changes made in https://github.com/flutter/flutter/pull/86198
SliverAppBar sliverAppBar = SliverAppBar();
sliverAppBar = SliverAppBar(systemOverlayStyle: SystemUiOverlayStyle.dark);
sliverAppBar = SliverAppBar(systemOverlayStyle: SystemUiOverlayStyle.light);
sliverAppBar = SliverAppBar(error: '');
sliverAppBar.systemOverlayStyle;
TextTheme myTextTheme = TextTheme();
SliverAppBar sliverAppBar = SliverAppBar();
sliverAppBar = SliverAppBar(toolbarTextStyle: myTextTheme.bodyMedium, titleTextStyle: myTextTheme.titleLarge);
SliverAppBar sliverAppBar = SliverAppBar();
sliverAppBar = SliverAppBar();
sliverAppBar = SliverAppBar();
sliverAppBar.backwardsCompatibility; // Removing field reference not supported.
}
| flutter/packages/flutter/test_fixes/material/sliver_app_bar.dart.expect/0 | {
"file_path": "flutter/packages/flutter/test_fixes/material/sliver_app_bar.dart.expect",
"repo_id": "flutter",
"token_count": 316
} | 697 |
include: ../analysis_options.yaml
linter:
rules:
avoid_print: false # This is a CLI tool, so printing to the console is fine.
| flutter/packages/flutter/test_private/analysis_options.yaml/0 | {
"file_path": "flutter/packages/flutter/test_private/analysis_options.yaml",
"repo_id": "flutter",
"token_count": 44
} | 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.
/// This library provides a Dart VM service extension that is required for
/// tests that use `package:flutter_driver` to drive applications from a
/// separate process, similar to Selenium (web), Espresso (Android) and UI
/// Automation (iOS).
///
/// The extension must be installed in the same process (isolate) with your
/// application.
///
/// To enable the extension call [enableFlutterDriverExtension] early in your
/// program, prior to running your application, e.g. before you call `runApp`.
///
/// Example:
///
/// import 'package:flutter/material.dart';
/// import 'package:flutter_driver/driver_extension.dart';
///
/// main() {
/// enableFlutterDriverExtension();
/// runApp(ExampleApp());
/// }
library flutter_driver_extension;
export 'src/common/deserialization_factory.dart';
export 'src/common/handler_factory.dart';
export 'src/extension/extension.dart';
| flutter/packages/flutter_driver/lib/driver_extension.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/driver_extension.dart",
"repo_id": "flutter",
"token_count": 317
} | 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 'message.dart';
/// A Flutter Driver command that requests a string representation of the layer tree.
class GetLayerTree extends Command {
/// Create a command to request a string representation of the layer tree.
const GetLayerTree({ super.timeout });
/// Deserializes this command from the value generated by [serialize].
GetLayerTree.deserialize(super.json) : super.deserialize();
@override
String get kind => 'get_layer_tree';
}
/// A string representation of the layer tree, the result of a
/// [FlutterDriver.getLayerTree] method.
class LayerTree extends Result {
/// Creates a [LayerTree] object with the given string representation.
const LayerTree(this.tree);
/// Deserializes the result from JSON.
LayerTree.fromJson(Map<String, dynamic> json) : tree = json['tree'] as String;
/// String representation of the layer tree.
final String? tree;
@override
Map<String, dynamic> toJson() => <String, dynamic>{
'tree': tree,
};
}
| flutter/packages/flutter_driver/lib/src/common/layer_tree.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/common/layer_tree.dart",
"repo_id": "flutter",
"token_count": 316
} | 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 'percentile_utils.dart';
import 'timeline.dart';
/// Key for RasterCache timeline events.
const String kRasterCacheEvent = 'RasterCache';
const String _kLayerCount = 'LayerCount';
const String _kLayerMemory = 'LayerMBytes';
const String _kPictureCount = 'PictureCount';
const String _kPictureMemory = 'PictureMBytes';
/// Summarizes [TimelineEvents]s corresponding to [kRasterCacheEvent] events.
///
/// A sample event (some fields have been omitted for brevity):
/// ```json
/// {
/// "name": "RasterCache",
/// "ts": 75598996256,
/// "ph": "C",
/// "args": {
/// "LayerCount": "1",
/// "LayerMBytes": "0.336491",
/// "PictureCount": "0",
/// "PictureMBytes": "0.000000",
/// }
/// },
/// ```
class RasterCacheSummarizer {
/// Creates a RasterCacheSummarizer given the timeline events.
RasterCacheSummarizer(this.rasterCacheEvents) {
for (final TimelineEvent event in rasterCacheEvents) {
assert(event.name == kRasterCacheEvent);
}
}
/// The raster cache events.
final List<TimelineEvent> rasterCacheEvents;
late final List<double> _layerCounts = _extractValues(_kLayerCount);
late final List<double> _layerMemories = _extractValues(_kLayerMemory);
late final List<double> _pictureCounts = _extractValues(_kPictureCount);
late final List<double> _pictureMemories = _extractValues(_kPictureMemory);
/// Computes the average of the `LayerCount` values over the cache events.
double computeAverageLayerCount() => _computeAverage(_layerCounts);
/// Computes the average of the `LayerMemory` values over the cache events.
double computeAverageLayerMemory() => _computeAverage(_layerMemories);
/// Computes the average of the `PictureCount` values over the cache events.
double computeAveragePictureCount() => _computeAverage(_pictureCounts);
/// Computes the average of the `PictureMemory` values over the cache events.
double computeAveragePictureMemory() => _computeAverage(_pictureMemories);
/// The [percentile]-th percentile `LayerCount` over the cache events.
double computePercentileLayerCount(double percentile) => _computePercentile(_layerCounts, percentile);
/// The [percentile]-th percentile `LayerMemory` over the cache events.
double computePercentileLayerMemory(double percentile) => _computePercentile(_layerMemories, percentile);
/// The [percentile]-th percentile `PictureCount` over the cache events.
double computePercentilePictureCount(double percentile) => _computePercentile(_pictureCounts, percentile);
/// The [percentile]-th percentile `PictureMemory` over the cache events.
double computePercentilePictureMemory(double percentile) => _computePercentile(_pictureMemories, percentile);
/// Computes the worst of the `LayerCount` values over the cache events.
double computeWorstLayerCount() => _computeWorst(_layerCounts);
/// Computes the worst of the `LayerMemory` values over the cache events.
double computeWorstLayerMemory() => _computeWorst(_layerMemories);
/// Computes the worst of the `PictureCount` values over the cache events.
double computeWorstPictureCount() => _computeWorst(_pictureCounts);
/// Computes the worst of the `PictureMemory` values over the cache events.
double computeWorstPictureMemory() => _computeWorst(_pictureMemories);
static double _computeAverage(List<double> values) {
if (values.isEmpty) {
return 0;
}
final double total = values.reduce((double a, double b) => a + b);
return total / values.length;
}
static double _computePercentile(List<double> values, double percentile) {
if (values.isEmpty) {
return 0;
}
return findPercentile(values, percentile);
}
static double _computeWorst(List<double> values) {
if (values.isEmpty) {
return 0;
}
values.sort();
return values.last;
}
List<double> _extractValues(String name) =>
rasterCacheEvents.map((TimelineEvent e) => _getValue(e, name)).toList();
double _getValue(TimelineEvent e, String name) {
assert(e.name == kRasterCacheEvent);
assert(e.arguments!.containsKey(name));
final dynamic valueString = e.arguments![name];
assert(valueString is String);
return double.parse(valueString as String);
}
}
| flutter/packages/flutter_driver/lib/src/driver/raster_cache_summarizer.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/driver/raster_cache_summarizer.dart",
"repo_id": "flutter",
"token_count": 1368
} | 701 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(gspencergoog): Remove this tag once this test's state leaks/test
// dependencies have been fixed.
// https://github.com/flutter/flutter/issues/85160
// Fails with "flutter test --test-randomize-ordering-seed=20210721"
@Tags(<String>['no-shuffle'])
library;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' hide TextInputAction;
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart' hide TextInputAction;
import 'package:flutter_driver/flutter_driver.dart';
import 'package:flutter_driver/src/extension/extension.dart';
import 'package:flutter_test/flutter_test.dart' hide TextInputAction;
import 'stubs/stub_command.dart';
import 'stubs/stub_command_extension.dart';
import 'stubs/stub_finder.dart';
import 'stubs/stub_finder_extension.dart';
Future<void> silenceDriverLogger(AsyncCallback callback) async {
final DriverLogCallback oldLogger = driverLog;
driverLog = (String source, String message) { };
try {
await callback();
} finally {
driverLog = oldLogger;
}
}
void main() {
group('waitUntilNoTransientCallbacks', () {
late FlutterDriverExtension driverExtension;
Map<String, dynamic>? result;
int messageId = 0;
final List<String?> log = <String?>[];
setUp(() {
result = null;
driverExtension = FlutterDriverExtension((String? message) async { log.add(message); return (messageId += 1).toString(); }, false, true);
});
testWidgets('returns immediately when transient callback queue is empty', (WidgetTester tester) async {
driverExtension.call(const WaitForCondition(NoTransientCallbacks()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
await tester.idle();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets('waits until no transient callbacks', (WidgetTester tester) async {
SchedulerBinding.instance.scheduleFrameCallback((_) {
// Intentionally blank. We only care about existence of a callback.
});
driverExtension.call(const WaitForCondition(NoTransientCallbacks()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// Nothing should happen until the next frame.
await tester.idle();
expect(result, isNull);
// NOW we should receive the result.
await tester.pump();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets('handler', (WidgetTester tester) async {
expect(log, isEmpty);
final Map<String, dynamic> response = await driverExtension.call(const RequestData('hello').serialize());
final RequestDataResult result = RequestDataResult.fromJson(response['response'] as Map<String, dynamic>);
expect(log, <String>['hello']);
expect(result.message, '1');
});
});
group('waitForCondition', () {
late FlutterDriverExtension driverExtension;
Map<String, dynamic>? result;
int messageId = 0;
final List<String?> log = <String?>[];
setUp(() {
result = null;
driverExtension = FlutterDriverExtension((String? message) async { log.add(message); return (messageId += 1).toString(); }, false, true);
});
testWidgets('waiting for NoTransientCallbacks returns immediately when transient callback queue is empty', (WidgetTester tester) async {
driverExtension.call(const WaitForCondition(NoTransientCallbacks()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
await tester.idle();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets('waiting for NoTransientCallbacks returns until no transient callbacks', (WidgetTester tester) async {
SchedulerBinding.instance.scheduleFrameCallback((_) {
// Intentionally blank. We only care about existence of a callback.
});
driverExtension.call(const WaitForCondition(NoTransientCallbacks()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// Nothing should happen until the next frame.
await tester.idle();
expect(result, isNull);
// NOW we should receive the result.
await tester.pump();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets('waiting for NoPendingFrame returns immediately when frame is synced', (
WidgetTester tester) async {
driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
await tester.idle();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets('waiting for NoPendingFrame returns until no pending scheduled frame', (WidgetTester tester) async {
SchedulerBinding.instance.scheduleFrame();
driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// Nothing should happen until the next frame.
await tester.idle();
expect(result, isNull);
// NOW we should receive the result.
await tester.pump();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waiting for combined conditions returns immediately', (WidgetTester tester) async {
const SerializableWaitCondition combinedCondition =
CombinedCondition(<SerializableWaitCondition>[NoTransientCallbacks(), NoPendingFrame()]);
driverExtension.call(const WaitForCondition(combinedCondition).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
await tester.idle();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waiting for combined conditions returns until no transient callbacks', (WidgetTester tester) async {
SchedulerBinding.instance.scheduleFrame();
SchedulerBinding.instance.scheduleFrameCallback((_) {
// Intentionally blank. We only care about existence of a callback.
});
const SerializableWaitCondition combinedCondition =
CombinedCondition(<SerializableWaitCondition>[NoTransientCallbacks(), NoPendingFrame()]);
driverExtension.call(const WaitForCondition(combinedCondition).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// Nothing should happen until the next frame.
await tester.idle();
expect(result, isNull);
// NOW we should receive the result.
await tester.pump();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waiting for combined conditions returns until no pending scheduled frame', (WidgetTester tester) async {
SchedulerBinding.instance.scheduleFrame();
SchedulerBinding.instance.scheduleFrameCallback((_) {
// Intentionally blank. We only care about existence of a callback.
});
const SerializableWaitCondition combinedCondition =
CombinedCondition(<SerializableWaitCondition>[NoPendingFrame(), NoTransientCallbacks()]);
driverExtension.call(const WaitForCondition(combinedCondition).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// Nothing should happen until the next frame.
await tester.idle();
expect(result, isNull);
// NOW we should receive the result.
await tester.pump();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waiting for NoPendingPlatformMessages returns immediately when there are no platform messages', (WidgetTester tester) async {
driverExtension
.call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
await tester.idle();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waiting for NoPendingPlatformMessages returns until a single method channel call returns', (WidgetTester tester) async {
const MethodChannel channel = MethodChannel('helloChannel', JSONMethodCodec());
const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
tester.binding.defaultBinaryMessenger.setMockMessageHandler(
'helloChannel', (ByteData? message) {
return Future<ByteData>.delayed(
const Duration(milliseconds: 10),
() => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
});
channel.invokeMethod<String>('sayHello', 'hello');
driverExtension
.call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// The channel message are delayed for 10 milliseconds, so nothing happens yet.
await tester.pump(const Duration(milliseconds: 5));
expect(result, isNull);
// Now we receive the result.
await tester.pump(const Duration(milliseconds: 5));
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waiting for NoPendingPlatformMessages returns until both method channel calls return', (WidgetTester tester) async {
const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
// Configures channel 1
const MethodChannel channel1 = MethodChannel('helloChannel1', JSONMethodCodec());
tester.binding.defaultBinaryMessenger.setMockMessageHandler(
'helloChannel1', (ByteData? message) {
return Future<ByteData>.delayed(
const Duration(milliseconds: 10),
() => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
});
// Configures channel 2
const MethodChannel channel2 = MethodChannel('helloChannel2', JSONMethodCodec());
tester.binding.defaultBinaryMessenger.setMockMessageHandler(
'helloChannel2', (ByteData? message) {
return Future<ByteData>.delayed(
const Duration(milliseconds: 20),
() => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
});
channel1.invokeMethod<String>('sayHello', 'hello');
channel2.invokeMethod<String>('sayHello', 'hello');
driverExtension
.call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// Neither of the channel responses is received, so nothing happens yet.
await tester.pump(const Duration(milliseconds: 5));
expect(result, isNull);
// Result of channel 1 is received, but channel 2 is still pending, so still waiting.
await tester.pump(const Duration(milliseconds: 10));
expect(result, isNull);
// Both of the results are received. Now we receive the result.
await tester.pump(const Duration(milliseconds: 30));
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waiting for NoPendingPlatformMessages returns until new method channel call returns', (WidgetTester tester) async {
const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
// Configures channel 1
const MethodChannel channel1 = MethodChannel('helloChannel1', JSONMethodCodec());
tester.binding.defaultBinaryMessenger.setMockMessageHandler(
'helloChannel1', (ByteData? message) {
return Future<ByteData>.delayed(
const Duration(milliseconds: 10),
() => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
});
// Configures channel 2
const MethodChannel channel2 = MethodChannel('helloChannel2', JSONMethodCodec());
tester.binding.defaultBinaryMessenger.setMockMessageHandler(
'helloChannel2', (ByteData? message) {
return Future<ByteData>.delayed(
const Duration(milliseconds: 20),
() => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
});
channel1.invokeMethod<String>('sayHello', 'hello');
// Calls the waiting API before the second channel message is sent.
driverExtension
.call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// The first channel message is not received, so nothing happens yet.
await tester.pump(const Duration(milliseconds: 5));
expect(result, isNull);
channel2.invokeMethod<String>('sayHello', 'hello');
// Result of channel 1 is received, but channel 2 is still pending, so still waiting.
await tester.pump(const Duration(milliseconds: 15));
expect(result, isNull);
// Both of the results are received. Now we receive the result.
await tester.pump(const Duration(milliseconds: 10));
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waiting for NoPendingPlatformMessages returns until both old and new method channel calls return', (WidgetTester tester) async {
const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
// Configures channel 1
const MethodChannel channel1 = MethodChannel('helloChannel1', JSONMethodCodec());
tester.binding.defaultBinaryMessenger.setMockMessageHandler(
'helloChannel1', (ByteData? message) {
return Future<ByteData>.delayed(
const Duration(milliseconds: 20),
() => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
});
// Configures channel 2
const MethodChannel channel2 = MethodChannel('helloChannel2', JSONMethodCodec());
tester.binding.defaultBinaryMessenger.setMockMessageHandler(
'helloChannel2', (ByteData? message) {
return Future<ByteData>.delayed(
const Duration(milliseconds: 10),
() => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
});
channel1.invokeMethod<String>('sayHello', 'hello');
driverExtension
.call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// The first channel message is not received, so nothing happens yet.
await tester.pump(const Duration(milliseconds: 5));
expect(result, isNull);
channel2.invokeMethod<String>('sayHello', 'hello');
// Result of channel 2 is received, but channel 1 is still pending, so still waiting.
await tester.pump(const Duration(milliseconds: 10));
expect(result, isNull);
// Now we receive the result.
await tester.pump(const Duration(milliseconds: 5));
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
});
group('getSemanticsId', () {
late FlutterDriverExtension driverExtension;
setUp(() {
driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
});
testWidgets('works when semantics are enabled', (WidgetTester tester) async {
final SemanticsHandle semantics = tester.ensureSemantics();
await tester.pumpWidget(
const Text('hello', textDirection: TextDirection.ltr));
final Map<String, String> arguments = GetSemanticsId(const ByText('hello')).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
final GetSemanticsIdResult result = GetSemanticsIdResult.fromJson(response['response'] as Map<String, dynamic>);
expect(result.id, 1);
semantics.dispose();
});
testWidgets('throws state error if no data is found', (WidgetTester tester) async {
await tester.pumpWidget(
const Text('hello', textDirection: TextDirection.ltr));
final Map<String, String> arguments = GetSemanticsId(const ByText('hello')).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
expect(response['isError'], true);
expect(response['response'], contains('Bad state: No semantics data found'));
}, semanticsEnabled: false);
testWidgets('throws state error multiple matches are found', (WidgetTester tester) async {
final SemanticsHandle semantics = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(children: const <Widget>[
SizedBox(width: 100.0, height: 100.0, child: Text('hello')),
SizedBox(width: 100.0, height: 100.0, child: Text('hello')),
]),
),
);
final Map<String, String> arguments = GetSemanticsId(const ByText('hello')).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
expect(response['isError'], true);
expect(response['response'], contains('Bad state: Found more than one element with the same ID'));
semantics.dispose();
});
});
testWidgets('getOffset', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
Future<Offset> getOffset(OffsetType offset) async {
final Map<String, String> arguments = GetOffset(ByValueKey(1), offset).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
final GetOffsetResult result = GetOffsetResult.fromJson(response['response'] as Map<String, dynamic>);
return Offset(result.dx, result.dy);
}
await tester.pumpWidget(
Align(
alignment: Alignment.topLeft,
child: Transform.translate(
offset: const Offset(40, 30),
child: const SizedBox(
key: ValueKey<int>(1),
width: 100,
height: 120,
),
),
),
);
expect(await getOffset(OffsetType.topLeft), const Offset(40, 30));
expect(await getOffset(OffsetType.topRight), const Offset(40 + 100.0, 30));
expect(await getOffset(OffsetType.bottomLeft), const Offset(40, 30 + 120.0));
expect(await getOffset(OffsetType.bottomRight), const Offset(40 + 100.0, 30 + 120.0));
expect(await getOffset(OffsetType.center), const Offset(40 + (100 / 2), 30 + (120 / 2)));
});
testWidgets('getText', (WidgetTester tester) async {
await silenceDriverLogger(() async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
Future<String?> getTextInternal(SerializableFinder search) async {
final Map<String, String> arguments = GetText(search, timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> result = await driverExtension.call(arguments);
if (result['isError'] as bool) {
return null;
}
return GetTextResult.fromJson(result['response'] as Map<String, dynamic>).text;
}
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body:Column(
key: const ValueKey<String>('column'),
children: <Widget>[
const Text('Hello1', key: ValueKey<String>('text1')),
SizedBox(
height: 25.0,
child: RichText(
key: const ValueKey<String>('text2'),
text: const TextSpan(text: 'Hello2'),
),
),
SizedBox(
height: 25.0,
child: EditableText(
key: const ValueKey<String>('text3'),
controller: TextEditingController(text: 'Hello3'),
focusNode: FocusNode(),
style: const TextStyle(),
cursorColor: Colors.red,
backgroundCursorColor: Colors.black,
),
),
SizedBox(
height: 25.0,
child: TextField(
key: const ValueKey<String>('text4'),
controller: TextEditingController(text: 'Hello4'),
),
),
SizedBox(
height: 25.0,
child: TextFormField(
key: const ValueKey<String>('text5'),
controller: TextEditingController(text: 'Hello5'),
),
),
SizedBox(
height: 25.0,
child: RichText(
key: const ValueKey<String>('text6'),
text: const TextSpan(children: <TextSpan>[
TextSpan(text: 'Hello'),
TextSpan(text: ', '),
TextSpan(text: 'World'),
TextSpan(text: '!'),
]),
),
),
],
))
)
);
expect(await getTextInternal(ByValueKey('text1')), 'Hello1');
expect(await getTextInternal(ByValueKey('text2')), 'Hello2');
expect(await getTextInternal(ByValueKey('text3')), 'Hello3');
expect(await getTextInternal(ByValueKey('text4')), 'Hello4');
expect(await getTextInternal(ByValueKey('text5')), 'Hello5');
expect(await getTextInternal(ByValueKey('text6')), 'Hello, World!');
// Check if error thrown for other types
final Map<String, String> arguments = GetText(ByValueKey('column'), timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
expect(response['isError'], true);
expect(response['response'], contains('is currently not supported by getText'));
});
});
testWidgets('descendant finder', (WidgetTester tester) async {
await silenceDriverLogger(() async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
Future<String?> getDescendantText({ String? of, bool matchRoot = false}) async {
final Map<String, String> arguments = GetText(Descendant(
of: ByValueKey(of),
matching: ByValueKey('text2'),
matchRoot: matchRoot,
), timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> result = await driverExtension.call(arguments);
if (result['isError'] as bool) {
return null;
}
return GetTextResult.fromJson(result['response'] as Map<String, dynamic>).text;
}
await tester.pumpWidget(
const MaterialApp(
home: Column(
key: ValueKey<String>('column'),
children: <Widget>[
Text('Hello1', key: ValueKey<String>('text1')),
Text('Hello2', key: ValueKey<String>('text2')),
Text('Hello3', key: ValueKey<String>('text3')),
],
)
)
);
expect(await getDescendantText(of: 'column'), 'Hello2');
expect(await getDescendantText(of: 'column', matchRoot: true), 'Hello2');
expect(await getDescendantText(of: 'text2', matchRoot: true), 'Hello2');
// Find nothing
Future<String?> result = getDescendantText(of: 'text1', matchRoot: true);
await tester.pump(const Duration(seconds: 2));
expect(await result, null);
result = getDescendantText(of: 'text2');
await tester.pump(const Duration(seconds: 2));
expect(await result, null);
});
});
testWidgets('descendant finder firstMatchOnly', (WidgetTester tester) async {
await silenceDriverLogger(() async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
Future<String?> getDescendantText() async {
final Map<String, String> arguments = GetText(Descendant(
of: ByValueKey('column'),
matching: const ByType('Text'),
firstMatchOnly: true,
), timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> result = await driverExtension.call(arguments);
if (result['isError'] as bool) {
return null;
}
return GetTextResult.fromJson(result['response'] as Map<String, dynamic>).text;
}
await tester.pumpWidget(
const MaterialApp(
home: Column(
key: ValueKey<String>('column'),
children: <Widget>[
Text('Hello1', key: ValueKey<String>('text1')),
Text('Hello2', key: ValueKey<String>('text2')),
Text('Hello3', key: ValueKey<String>('text3')),
],
),
),
);
expect(await getDescendantText(), 'Hello1');
});
});
testWidgets('ancestor finder', (WidgetTester tester) async {
await silenceDriverLogger(() async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
Future<Offset?> getAncestorTopLeft({ String? of, String? matching, bool matchRoot = false}) async {
final Map<String, String> arguments = GetOffset(Ancestor(
of: ByValueKey(of),
matching: ByValueKey(matching),
matchRoot: matchRoot,
), OffsetType.topLeft, timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
if (response['isError'] as bool) {
return null;
}
final GetOffsetResult result = GetOffsetResult.fromJson(response['response'] as Map<String, dynamic>);
return Offset(result.dx, result.dy);
}
await tester.pumpWidget(
const MaterialApp(
home: Center(
child: SizedBox(
key: ValueKey<String>('parent'),
height: 100,
width: 100,
child: Center(
child: Row(
children: <Widget>[
SizedBox(
key: ValueKey<String>('leftchild'),
width: 25,
height: 25,
),
SizedBox(
key: ValueKey<String>('rightchild'),
width: 25,
height: 25,
),
],
),
),
)
),
)
);
expect(
await getAncestorTopLeft(of: 'leftchild', matching: 'parent'),
const Offset((800 - 100) / 2, (600 - 100) / 2),
);
expect(
await getAncestorTopLeft(of: 'leftchild', matching: 'parent', matchRoot: true),
const Offset((800 - 100) / 2, (600 - 100) / 2),
);
expect(
await getAncestorTopLeft(of: 'parent', matching: 'parent', matchRoot: true),
const Offset((800 - 100) / 2, (600 - 100) / 2),
);
// Find nothing
Future<Offset?> result = getAncestorTopLeft(of: 'leftchild', matching: 'leftchild');
await tester.pump(const Duration(seconds: 2));
expect(await result, null);
result = getAncestorTopLeft(of: 'leftchild', matching: 'rightchild');
await tester.pump(const Duration(seconds: 2));
expect(await result, null);
});
});
testWidgets('ancestor finder firstMatchOnly', (WidgetTester tester) async {
await silenceDriverLogger(() async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
Future<Offset?> getAncestorTopLeft() async {
final Map<String, String> arguments = GetOffset(Ancestor(
of: ByValueKey('leaf'),
matching: const ByType('SizedBox'),
firstMatchOnly: true,
), OffsetType.topLeft, timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
if (response['isError'] as bool) {
return null;
}
final GetOffsetResult result = GetOffsetResult.fromJson(response['response'] as Map<String, dynamic>);
return Offset(result.dx, result.dy);
}
await tester.pumpWidget(
const MaterialApp(
home: Center(
child: SizedBox(
height: 200,
width: 200,
child: Center(
child: SizedBox(
height: 100,
width: 100,
child: Center(
child: SizedBox(
key: ValueKey<String>('leaf'),
height: 50,
width: 50,
),
),
),
),
),
),
),
);
expect(
await getAncestorTopLeft(),
const Offset((800 - 100) / 2, (600 - 100) / 2),
);
});
});
testWidgets('GetDiagnosticsTree', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
Future<Map<String, dynamic>> getDiagnosticsTree(DiagnosticsType type, SerializableFinder finder, { int depth = 0, bool properties = true }) async {
final Map<String, String> arguments = GetDiagnosticsTree(finder, type, subtreeDepth: depth, includeProperties: properties).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
final DiagnosticsTreeResult result = DiagnosticsTreeResult(response['response'] as Map<String, dynamic>);
return result.json;
}
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Text('Hello World', key: ValueKey<String>('Text'))
),
),
);
// Widget
Map<String, dynamic> result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'));
expect(result['children'], isNull); // depth: 0
expect(result['widgetRuntimeType'], 'Text');
List<Map<String, dynamic>> properties = (result['properties']! as List<Object>).cast<Map<String, dynamic>>();
Map<String, dynamic> stringProperty = properties.singleWhere((Map<String, dynamic> property) => property['name'] == 'data');
expect(stringProperty['description'], '"Hello World"');
expect(stringProperty['propertyType'], 'String');
result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), properties: false);
expect(result['widgetRuntimeType'], 'Text');
expect(result['properties'], isNull); // properties: false
result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 1);
List<Map<String, dynamic>> children = (result['children']! as List<Object>).cast<Map<String, dynamic>>();
expect(children.single['children'], isNull);
result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 100);
children = (result['children']! as List<Object>).cast<Map<String, dynamic>>();
expect(children.single['children'], isEmpty);
// RenderObject
result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'));
expect(result['children'], isNull); // depth: 0
expect(result['properties'], isNotNull);
expect(result['description'], startsWith('RenderParagraph'));
result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), properties: false);
expect(result['properties'], isNull); // properties: false
expect(result['description'], startsWith('RenderParagraph'));
result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 1);
children = (result['children']! as List<Object>).cast<Map<String, dynamic>>();
final Map<String, dynamic> textSpan = children.single;
expect(textSpan['description'], 'TextSpan');
properties = (textSpan['properties']! as List<Object>).cast<Map<String, dynamic>>();
stringProperty = properties.singleWhere((Map<String, dynamic> property) => property['name'] == 'text');
expect(stringProperty['description'], '"Hello World"');
expect(stringProperty['propertyType'], 'String');
expect(children.single['children'], isNull);
result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 100);
children = (result['children']! as List<Object>).cast<Map<String, dynamic>>();
expect(children.single['children'], isEmpty);
});
group('enableTextEntryEmulation', () {
late FlutterDriverExtension driverExtension;
Future<Map<String, dynamic>> enterText() async {
final Map<String, String> arguments = const EnterText('foo').serialize();
final Map<String, dynamic> result = await driverExtension.call(arguments);
return result;
}
const Widget testWidget = MaterialApp(
home: Material(
child: Center(
child: TextField(
key: ValueKey<String>('foo'),
autofocus: true,
),
),
),
);
testWidgets('enableTextEntryEmulation false', (WidgetTester tester) async {
driverExtension = FlutterDriverExtension((String? arg) async => '', true, false);
await tester.pumpWidget(testWidget);
final Map<String, dynamic> enterTextResult = await enterText();
expect(enterTextResult['isError'], isTrue);
});
testWidgets('enableTextEntryEmulation true', (WidgetTester tester) async {
driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
await tester.pumpWidget(testWidget);
final Map<String, dynamic> enterTextResult = await enterText();
expect(enterTextResult['isError'], isFalse);
});
});
group('extension finders', () {
final Widget debugTree = Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Column(
key: const ValueKey<String>('Column'),
children: <Widget>[
const Text('Foo', key: ValueKey<String>('Text1')),
const Text('Bar', key: ValueKey<String>('Text2')),
TextButton(
key: const ValueKey<String>('Button'),
onPressed: () {},
child: const Text('Whatever'),
),
],
),
),
);
testWidgets('unknown extension finder', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension(
(String? arg) async => '',
true,
true,
finders: <FinderExtension>[],
);
Future<Map<String, dynamic>> getText(SerializableFinder finder) async {
final Map<String, String> arguments = GetText(finder, timeout: const Duration(seconds: 1)).serialize();
return driverExtension.call(arguments);
}
await tester.pumpWidget(debugTree);
final Map<String, dynamic> result = await getText(StubFinder('Text1'));
expect(result['isError'], true);
expect(result['response'] is String, true);
expect(result['response'] as String?, contains('Unsupported search specification type Stub'));
});
testWidgets('simple extension finder', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension(
(String? arg) async => '',
true,
true,
finders: <FinderExtension>[
StubFinderExtension(),
],
);
Future<GetTextResult> getText(SerializableFinder finder) async {
final Map<String, String> arguments = GetText(finder, timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
return GetTextResult.fromJson(response['response'] as Map<String, dynamic>);
}
await tester.pumpWidget(debugTree);
final GetTextResult result = await getText(StubFinder('Text1'));
expect(result.text, 'Foo');
});
testWidgets('complex extension finder', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension(
(String? arg) async => '',
true,
true,
finders: <FinderExtension>[
StubFinderExtension(),
],
);
Future<GetTextResult> getText(SerializableFinder finder) async {
final Map<String, String> arguments = GetText(finder, timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
return GetTextResult.fromJson(response['response'] as Map<String, dynamic>);
}
await tester.pumpWidget(debugTree);
final GetTextResult result = await getText(Descendant(of: StubFinder('Column'), matching: StubFinder('Text1')));
expect(result.text, 'Foo');
});
testWidgets('extension finder with command', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension(
(String? arg) async => '',
true,
true,
finders: <FinderExtension>[
StubFinderExtension(),
],
);
Future<Map<String, dynamic>> tap(SerializableFinder finder) async {
final Map<String, String> arguments = Tap(finder, timeout: const Duration(seconds: 1)).serialize();
return driverExtension.call(arguments);
}
await tester.pumpWidget(debugTree);
final Map<String, dynamic> result = await tap(StubFinder('Button'));
expect(result['isError'], false);
});
});
group('extension commands', () {
int invokes = 0;
void stubCallback() => invokes++;
final Widget debugTree = Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Column(
children: <Widget>[
TextButton(
key: const ValueKey<String>('Button'),
onPressed: stubCallback,
child: const Text('Whatever'),
),
],
),
),
);
setUp(() {
invokes = 0;
});
testWidgets('unknown extension command', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension(
(String? arg) async => '',
true,
true,
commands: <CommandExtension>[],
);
Future<Map<String, dynamic>> invokeCommand(SerializableFinder finder, int times) async {
final Map<String, String> arguments = StubNestedCommand(finder, times).serialize();
return driverExtension.call(arguments);
}
await tester.pumpWidget(debugTree);
final Map<String, dynamic> result = await invokeCommand(ByValueKey('Button'), 10);
expect(result['isError'], true);
expect(result['response'] is String, true);
expect(result['response'] as String?, contains('Unsupported command kind StubNestedCommand'));
});
testWidgets('nested command', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension(
(String? arg) async => '',
true,
true,
commands: <CommandExtension>[
StubNestedCommandExtension(),
],
);
Future<StubCommandResult> invokeCommand(SerializableFinder finder, int times) async {
await driverExtension.call(const SetFrameSync(false).serialize()); // disable frame sync for test to avoid lock
final Map<String, String> arguments = StubNestedCommand(finder, times, timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
final Map<String, dynamic> commandResponse = response['response'] as Map<String, dynamic>;
return StubCommandResult(commandResponse['resultParam'] as String);
}
await tester.pumpWidget(debugTree);
const int times = 10;
final StubCommandResult result = await invokeCommand(ByValueKey('Button'), times);
expect(result.resultParam, 'stub response');
expect(invokes, times);
});
testWidgets('prober command', (WidgetTester tester) async {
final FlutterDriverExtension driverExtension = FlutterDriverExtension(
(String? arg) async => '',
true,
true,
commands: <CommandExtension>[
StubProberCommandExtension(),
],
);
Future<StubCommandResult> invokeCommand(SerializableFinder finder, int times) async {
await driverExtension.call(const SetFrameSync(false).serialize()); // disable frame sync for test to avoid lock
final Map<String, String> arguments = StubProberCommand(finder, times, timeout: const Duration(seconds: 1)).serialize();
final Map<String, dynamic> response = await driverExtension.call(arguments);
final Map<String, dynamic> commandResponse = response['response'] as Map<String, dynamic>;
return StubCommandResult(commandResponse['resultParam'] as String);
}
await tester.pumpWidget(debugTree);
const int times = 10;
final StubCommandResult result = await invokeCommand(ByValueKey('Button'), times);
expect(result.resultParam, 'stub response');
expect(invokes, times);
});
});
group('waitForTappable', () {
late FlutterDriverExtension driverExtension;
Future<Map<String, dynamic>> waitForTappable() async {
final SerializableFinder finder = ByValueKey('widgetOne');
final Map<String, String> arguments = WaitForTappable(finder).serialize();
final Map<String, dynamic> result = await driverExtension.call(arguments);
return result;
}
const Widget testWidget = MaterialApp(
home: Material(
child: Column(children: <Widget> [
Text('Hello ', key: Key('widgetOne')),
SizedBox.shrink(
child: Text('World!', key: Key('widgetTwo')),
),
]),
),
);
testWidgets('returns true when widget is tappable', (
WidgetTester tester) async {
driverExtension = FlutterDriverExtension((String? arg) async => '', true, false);
await tester.pumpWidget(testWidget);
final Map<String, dynamic> waitForTappableResult = await waitForTappable();
expect(waitForTappableResult['isError'], isFalse);
});
});
group('waitUntilFrameSync', () {
late FlutterDriverExtension driverExtension;
Map<String, dynamic>? result;
setUp(() {
driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
result = null;
});
testWidgets('returns immediately when frame is synced', (
WidgetTester tester) async {
driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
await tester.idle();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waits until no transient callbacks', (WidgetTester tester) async {
SchedulerBinding.instance.scheduleFrameCallback((_) {
// Intentionally blank. We only care about existence of a callback.
});
driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// Nothing should happen until the next frame.
await tester.idle();
expect(result, isNull);
// NOW we should receive the result.
await tester.pump();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
testWidgets(
'waits until no pending scheduled frame', (WidgetTester tester) async {
SchedulerBinding.instance.scheduleFrame();
driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
.then<void>(expectAsync1((Map<String, dynamic> r) {
result = r;
}));
// Nothing should happen until the next frame.
await tester.idle();
expect(result, isNull);
// NOW we should receive the result.
await tester.pump();
expect(
result,
<String, dynamic>{
'isError': false,
'response': <String, dynamic>{},
},
);
});
});
group('sendTextInputAction', () {
late FlutterDriverExtension driverExtension;
Future<void> sendAction(TextInputAction action) async {
final Map<String, String> arguments = SendTextInputAction(action).serialize();
await driverExtension.call(arguments);
}
MaterialApp testWidget(TextEditingController controller) => MaterialApp(
home: Material(
child: Center(
child: TextField(
key: const ValueKey<String>('foo'),
autofocus: true,
controller: controller,
onSubmitted: (_) {
controller.value = const TextEditingValue(text: 'bar');
},
),
),
),
);
testWidgets('press done trigger onSubmitted and change value', (WidgetTester tester) async {
driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
final TextEditingController controller = TextEditingController(
text: 'foo',
);
await tester.pumpWidget(testWidget(controller));
expect(controller.value.text, 'foo');
await sendAction(TextInputAction.done);
expectSync(controller.value.text, 'bar');
});
});
}
| flutter/packages/flutter_driver/test/src/real_tests/extension_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test/src/real_tests/extension_test.dart",
"repo_id": "flutter",
"token_count": 19354
} | 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.
/// Localizations for the Flutter library.
library flutter_localizations;
export 'src/cupertino_localizations.dart';
export 'src/l10n/generated_cupertino_localizations.dart';
export 'src/l10n/generated_material_localizations.dart';
export 'src/l10n/generated_widgets_localizations.dart';
export 'src/material_localizations.dart';
export 'src/widgets_localizations.dart';
| flutter/packages/flutter_localizations/lib/flutter_localizations.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/flutter_localizations.dart",
"repo_id": "flutter",
"token_count": 163
} | 703 |
{
"datePickerHourSemanticsLabelOne": "$hour tepat",
"datePickerHourSemanticsLabelOther": "$hour tepat",
"datePickerMinuteSemanticsLabelOne": "1 menit",
"datePickerMinuteSemanticsLabelOther": "$minute menit",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "Hari ini",
"alertDialogLabel": "Notifikasi",
"timerPickerHourLabelOne": "jam",
"timerPickerHourLabelOther": "jam",
"timerPickerMinuteLabelOne": "mnt.",
"timerPickerMinuteLabelOther": "mnt.",
"timerPickerSecondLabelOne": "dtk.",
"timerPickerSecondLabelOther": "dtk.",
"cutButtonLabel": "Potong",
"copyButtonLabel": "Salin",
"pasteButtonLabel": "Tempel",
"selectAllButtonLabel": "Pilih Semua",
"tabSemanticsLabel": "Tab $tabIndex dari $tabCount",
"modalBarrierDismissLabel": "Tutup",
"searchTextFieldPlaceholderLabel": "Telusuri",
"noSpellCheckReplacementsLabel": "Penggantian Tidak Ditemukan",
"menuDismissLabel": "Tutup menu",
"lookUpButtonLabel": "Cari",
"searchWebButtonLabel": "Telusuri di Web",
"shareButtonLabel": "Bagikan...",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_id.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_id.arb",
"repo_id": "flutter",
"token_count": 431
} | 704 |
{
"datePickerHourSemanticsLabelOne": "$hour वाजता",
"datePickerHourSemanticsLabelOther": "$hour वाजता",
"datePickerMinuteSemanticsLabelOne": "एक मिनिट",
"datePickerMinuteSemanticsLabelOther": "$minute मिनिटे",
"datePickerDateOrder": "mdy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"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_mr.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_mr.arb",
"repo_id": "flutter",
"token_count": 637
} | 705 |
{
"datePickerHourSemanticsLabelTwo": "$hour",
"datePickerHourSemanticsLabelFew": "$hour",
"datePickerMinuteSemanticsLabelTwo": "$minute minuti",
"datePickerMinuteSemanticsLabelFew": "$minute minute",
"timerPickerHourLabelTwo": "ure",
"timerPickerHourLabelFew": "ure",
"timerPickerMinuteLabelTwo": "min",
"timerPickerMinuteLabelFew": "min",
"timerPickerSecondLabelTwo": "s",
"timerPickerSecondLabelFew": "s",
"datePickerHourSemanticsLabelOne": "$hour",
"datePickerHourSemanticsLabelOther": "$hour",
"datePickerMinuteSemanticsLabelOne": "1 minuta",
"datePickerMinuteSemanticsLabelOther": "$minute minut",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "DOP.",
"postMeridiemAbbreviation": "POP.",
"todayLabel": "Danes",
"alertDialogLabel": "Opozorilo",
"timerPickerHourLabelOne": "ura",
"timerPickerHourLabelOther": "ure",
"timerPickerMinuteLabelOne": "min",
"timerPickerMinuteLabelOther": "min",
"timerPickerSecondLabelOne": "s",
"timerPickerSecondLabelOther": "s",
"cutButtonLabel": "Izreži",
"copyButtonLabel": "Kopiraj",
"pasteButtonLabel": "Prilepi",
"selectAllButtonLabel": "Izberi vse",
"tabSemanticsLabel": "Zavihek $tabIndex od $tabCount",
"modalBarrierDismissLabel": "Opusti",
"searchTextFieldPlaceholderLabel": "Iskanje",
"noSpellCheckReplacementsLabel": "Ni zamenjav",
"menuDismissLabel": "Opusti meni",
"lookUpButtonLabel": "Pogled gor",
"searchWebButtonLabel": "Iskanje v spletu",
"shareButtonLabel": "Deli …",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sl.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sl.arb",
"repo_id": "flutter",
"token_count": 576
} | 706 |
{
"searchWebButtonLabel": "搜尋",
"shareButtonLabel": "分享…",
"lookUpButtonLabel": "查詢",
"noSpellCheckReplacementsLabel": "找不到替換字詞",
"menuDismissLabel": "閂選單",
"searchTextFieldPlaceholderLabel": "搜尋",
"tabSemanticsLabel": "$tabCount 個分頁中嘅第 $tabIndex 個",
"datePickerHourSemanticsLabelOne": "$hour 點",
"datePickerHourSemanticsLabelOther": "$hour 點",
"datePickerMinuteSemanticsLabelOne": "1 分鐘",
"datePickerMinuteSemanticsLabelOther": "$minute 分鐘",
"datePickerDateOrder": "ymd",
"datePickerDateTimeOrder": "date_dayPeriod_time",
"anteMeridiemAbbreviation": "上午",
"postMeridiemAbbreviation": "下午",
"todayLabel": "今天",
"alertDialogLabel": "通知",
"timerPickerHourLabelOne": "小時",
"timerPickerHourLabelOther": "小時",
"timerPickerMinuteLabelOne": "分鐘",
"timerPickerMinuteLabelOther": "分鐘",
"timerPickerSecondLabelOne": "秒",
"timerPickerSecondLabelOther": "秒",
"cutButtonLabel": "剪下",
"copyButtonLabel": "複製",
"pasteButtonLabel": "貼上",
"selectAllButtonLabel": "全選",
"modalBarrierDismissLabel": "拒絕"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_zh_HK.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_zh_HK.arb",
"repo_id": "flutter",
"token_count": 486
} | 707 |
{
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"openAppDrawerTooltip": "Obre el menú de navegació",
"backButtonTooltip": "Enrere",
"closeButtonTooltip": "Tanca",
"deleteButtonTooltip": "Suprimeix",
"nextMonthTooltip": "Mes següent",
"previousMonthTooltip": "Mes anterior",
"nextPageTooltip": "Pàgina següent",
"firstPageTooltip": "Primera pàgina",
"lastPageTooltip": "Darrera pàgina",
"previousPageTooltip": "Pàgina anterior",
"showMenuTooltip": "Mostra el menú",
"aboutListTileTitle": "Sobre $applicationName",
"licensesPageTitle": "Llicències",
"pageRowsInfoTitle": "$firstRow-$lastRow de $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow-$lastRow d'aproximadament $rowCount",
"rowsPerPageTitle": "Files per pàgina:",
"tabLabel": "Pestanya $tabIndex de $tabCount",
"selectedRowCountTitleOne": "S'ha seleccionat 1 element",
"selectedRowCountTitleOther": "S'han seleccionat $selectedRowCount elements",
"cancelButtonLabel": "Cancel·la",
"closeButtonLabel": "Tanca",
"continueButtonLabel": "Continua",
"copyButtonLabel": "Copia",
"cutButtonLabel": "Retalla",
"scanTextButtonLabel": "Escaneja text",
"okButtonLabel": "D'ACORD",
"pasteButtonLabel": "Enganxa",
"selectAllButtonLabel": "Selecciona-ho tot",
"viewLicensesButtonLabel": "Mostra les llicències",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "Selecciona les hores",
"timePickerMinuteModeAnnouncement": "Selecciona els minuts",
"modalBarrierDismissLabel": "Ignora",
"signedInLabel": "Sessió iniciada",
"hideAccountsLabel": "Amaga els comptes",
"showAccountsLabel": "Mostra els comptes",
"drawerLabel": "Menú de navegació",
"popupMenuLabel": "Menú emergent",
"dialogLabel": "Diàleg",
"alertDialogLabel": "Alerta",
"searchFieldLabel": "Cerca",
"reorderItemToStart": "Mou al principi",
"reorderItemToEnd": "Mou al final",
"reorderItemUp": "Mou amunt",
"reorderItemDown": "Mou avall",
"reorderItemLeft": "Mou cap a l'esquerra",
"reorderItemRight": "Mou cap a la dreta",
"expandedIconTapHint": "Replega",
"collapsedIconTapHint": "Desplega",
"remainingTextFieldCharacterCountOne": "Queda 1 caràcter",
"remainingTextFieldCharacterCountOther": "Queden $remainingCount caràcters",
"refreshIndicatorSemanticLabel": "Actualitza",
"moreButtonTooltip": "Més",
"dateSeparator": "/",
"dateHelpText": "mm/dd/aaaa",
"selectYearSemanticsLabel": "Selecciona un any",
"unspecifiedDate": "Data",
"unspecifiedDateRange": "Interval de dates",
"dateInputLabel": "Introdueix una data",
"dateRangeStartLabel": "Data d'inici",
"dateRangeEndLabel": "Data de finalització",
"dateRangeStartDateSemanticLabel": "Data d'inici $fullDate",
"dateRangeEndDateSemanticLabel": "Data de finalització $fullDate",
"invalidDateFormatLabel": "El format no és vàlid.",
"invalidDateRangeLabel": "L'interval no és vàlid.",
"dateOutOfRangeLabel": "Fora de l'abast.",
"saveButtonLabel": "Desa",
"datePickerHelpText": "Selecciona la data",
"dateRangePickerHelpText": "Selecciona l'interval",
"calendarModeButtonLabel": "Canvia al calendari",
"inputDateModeButtonLabel": "Canvia a introducció de text",
"timePickerDialHelpText": "Selecciona l'hora",
"timePickerInputHelpText": "Introdueix l'hora",
"timePickerHourLabel": "Hora",
"timePickerMinuteLabel": "Minut",
"invalidTimeLabel": "Introdueix una hora vàlida",
"dialModeButtonLabel": "Canvia al mode de selector de dial",
"inputTimeModeButtonLabel": "Canvia al mode d'introducció de text",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 llicència",
"licensesPackageDetailTextOther": "$licenseCount llicències",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "Alt Gr",
"keyboardKeyBackspace": "Retrocés",
"keyboardKeyCapsLock": "Bloq Maj",
"keyboardKeyChannelDown": "Canal següent",
"keyboardKeyChannelUp": "Canal anterior",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Supr",
"keyboardKeyEject": "Expulsa",
"keyboardKeyEnd": "Fi",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Inici",
"keyboardKeyInsert": "Inser",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Bloq Núm",
"keyboardKeyNumpad1": "Núm. 1",
"keyboardKeyNumpad2": "Núm. 2",
"keyboardKeyNumpad3": "Núm. 3",
"keyboardKeyNumpad4": "Núm. 4",
"keyboardKeyNumpad5": "Núm. 5",
"keyboardKeyNumpad6": "Núm. 6",
"keyboardKeyNumpad7": "Núm. 7",
"keyboardKeyNumpad8": "Núm. 8",
"keyboardKeyNumpad9": "Núm. 9",
"keyboardKeyNumpad0": "Núm. 0",
"keyboardKeyNumpadAdd": "Núm. +",
"keyboardKeyNumpadComma": "Núm. ,",
"keyboardKeyNumpadDecimal": "Núm. .",
"keyboardKeyNumpadDivide": "Núm. /",
"keyboardKeyNumpadEnter": "Núm. Retorn",
"keyboardKeyNumpadEqual": "Núm. =",
"keyboardKeyNumpadMultiply": "Núm. *",
"keyboardKeyNumpadParenLeft": "Núm. (",
"keyboardKeyNumpadParenRight": "Núm. )",
"keyboardKeyNumpadSubtract": "Núm. -",
"keyboardKeyPageDown": "Av Pàg",
"keyboardKeyPageUp": "Re Pàg",
"keyboardKeyPower": "Engegada",
"keyboardKeyPowerOff": "Apagada",
"keyboardKeyPrintScreen": "Impr Pant",
"keyboardKeyScrollLock": "Bloq Despl",
"keyboardKeySelect": "Selecciona",
"keyboardKeySpace": "Espai",
"keyboardKeyMetaMacOs": "Ordre",
"keyboardKeyMetaWindows": "Windows",
"menuBarMenuLabel": "Menú de la barra de menú",
"currentDateLabel": "Avui",
"scrimLabel": "Fons atenuat",
"bottomSheetLabel": "Full inferior",
"scrimOnTapHint": "Tanca $modalRouteContentName",
"keyboardKeyShift": "Maj",
"expansionTileExpandedHint": "fes doble toc per replegar",
"expansionTileCollapsedHint": "fes doble toc per desplegar",
"expansionTileExpandedTapHint": "Replega",
"expansionTileCollapsedTapHint": "Desplega per obtenir més informació",
"expandedHint": "S'ha replegat",
"collapsedHint": "S'ha desplegat",
"menuDismissLabel": "Ignora el menú",
"lookUpButtonLabel": "Mira amunt",
"searchWebButtonLabel": "Cerca al web",
"shareButtonLabel": "Comparteix...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_ca.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ca.arb",
"repo_id": "flutter",
"token_count": 2403
} | 708 |
{
"scriptCategory": "English-like",
"timeOfDayFormat": "H:mm",
"openAppDrawerTooltip": "Abrir el menú de navegación",
"backButtonTooltip": "Atrás",
"closeButtonTooltip": "Cerrar",
"deleteButtonTooltip": "Eliminar",
"nextMonthTooltip": "Mes siguiente",
"previousMonthTooltip": "Mes anterior",
"nextPageTooltip": "Página siguiente",
"previousPageTooltip": "Página anterior",
"firstPageTooltip": "Primera página",
"lastPageTooltip": "Última página",
"showMenuTooltip": "Mostrar menú",
"aboutListTileTitle": "Sobre $applicationName",
"licensesPageTitle": "Licencias",
"pageRowsInfoTitle": "$firstRow‑$lastRow de $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow‑$lastRow de aproximadamente $rowCount",
"rowsPerPageTitle": "Filas por página:",
"tabLabel": "Pestaña $tabIndex de $tabCount",
"selectedRowCountTitleZero": "No se han seleccionado elementos",
"selectedRowCountTitleOne": "1 elemento seleccionado",
"selectedRowCountTitleOther": "$selectedRowCount elementos seleccionados",
"cancelButtonLabel": "Cancelar",
"closeButtonLabel": "Cerrar",
"continueButtonLabel": "Continuar",
"copyButtonLabel": "Copiar",
"cutButtonLabel": "Cortar",
"scanTextButtonLabel": "Escanear texto",
"okButtonLabel": "ACEPTAR",
"pasteButtonLabel": "Pegar",
"selectAllButtonLabel": "Seleccionar todo",
"viewLicensesButtonLabel": "Ver licencias",
"anteMeridiemAbbreviation": "a. m.",
"postMeridiemAbbreviation": "p. m.",
"timePickerHourModeAnnouncement": "Seleccionar horas",
"timePickerMinuteModeAnnouncement": "Seleccionar minutos",
"signedInLabel": "Sesión iniciada",
"hideAccountsLabel": "Ocultar cuentas",
"showAccountsLabel": "Mostrar cuentas",
"modalBarrierDismissLabel": "Cerrar",
"drawerLabel": "Menú de navegación",
"popupMenuLabel": "Menú emergente",
"dialogLabel": "Cuadro de diálogo",
"alertDialogLabel": "Alerta",
"searchFieldLabel": "Buscar",
"reorderItemToStart": "Mover al principio",
"reorderItemToEnd": "Mover al final",
"reorderItemUp": "Mover hacia arriba",
"reorderItemDown": "Mover hacia abajo",
"reorderItemLeft": "Mover hacia la izquierda",
"reorderItemRight": "Mover hacia la derecha",
"expandedIconTapHint": "Ocultar",
"collapsedIconTapHint": "Mostrar",
"remainingTextFieldCharacterCountOne": "Queda 1 carácter.",
"remainingTextFieldCharacterCountOther": "Quedan $remainingCount caracteres",
"refreshIndicatorSemanticLabel": "Actualizar",
"moreButtonTooltip": "Más",
"dateSeparator": "/",
"dateHelpText": "dd/mm/aaaa",
"selectYearSemanticsLabel": "Seleccionar año",
"unspecifiedDate": "Fecha",
"unspecifiedDateRange": "Periodo",
"dateInputLabel": "Introduce una fecha",
"dateRangeStartLabel": "Fecha de inicio",
"dateRangeEndLabel": "Fecha de finalización",
"dateRangeStartDateSemanticLabel": "Fecha de inicio $fullDate",
"dateRangeEndDateSemanticLabel": "Fecha de finalización $fullDate",
"invalidDateFormatLabel": "Formato no válido.",
"invalidDateRangeLabel": "Periodo no válido.",
"dateOutOfRangeLabel": "Fuera del periodo válido.",
"saveButtonLabel": "Guardar",
"datePickerHelpText": "Seleccionar fecha",
"dateRangePickerHelpText": "Seleccionar periodo",
"calendarModeButtonLabel": "Cambiar a calendario",
"inputDateModeButtonLabel": "Cambiar a cuadro de texto",
"timePickerDialHelpText": "Seleccionar hora",
"timePickerInputHelpText": "Introducir hora",
"timePickerHourLabel": "Hora",
"timePickerMinuteLabel": "Minuto",
"invalidTimeLabel": "Indica una hora válida",
"dialModeButtonLabel": "Cambiar al modo de selección de hora",
"inputTimeModeButtonLabel": "Cambiar al modo de introducción de texto",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 licencia",
"licensesPackageDetailTextOther": "$licenseCount licencias",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "Alt Gr",
"keyboardKeyBackspace": "Retroceso",
"keyboardKeyCapsLock": "Bloq Mayús",
"keyboardKeyChannelDown": "Canal siguiente",
"keyboardKeyChannelUp": "Canal anterior",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Supr",
"keyboardKeyEject": "Expulsar",
"keyboardKeyEnd": "Fin",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Inicio",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Bloq Num",
"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 Intro",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyPageDown": "Av Pág",
"keyboardKeyPageUp": "Re Pág",
"keyboardKeyPower": "Encendido",
"keyboardKeyPowerOff": "Apagado",
"keyboardKeyPrintScreen": "Impr Pant",
"keyboardKeyScrollLock": "Bloq Despl",
"keyboardKeySelect": "Selección",
"keyboardKeySpace": "Espacio",
"keyboardKeyMetaMacOs": "Comando",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Menú de la barra de menú",
"currentDateLabel": "Hoy",
"scrimLabel": "Sombreado",
"bottomSheetLabel": "Hoja inferior",
"scrimOnTapHint": "Cerrar $modalRouteContentName",
"keyboardKeyShift": "Mayús",
"expansionTileExpandedHint": "toca dos veces para contraer",
"expansionTileCollapsedHint": "toca dos veces para desplegar",
"expansionTileExpandedTapHint": "Contraer",
"expansionTileCollapsedTapHint": "Desplegar para ver más detalles",
"expandedHint": "Contraído",
"collapsedHint": "Desplegado",
"menuDismissLabel": "Cerrar menú",
"lookUpButtonLabel": "Buscador visual",
"searchWebButtonLabel": "Buscar en la Web",
"shareButtonLabel": "Compartir...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_es.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_es.arb",
"repo_id": "flutter",
"token_count": 2365
} | 709 |
{
"scriptCategory": "dense",
"timeOfDayFormat": "ah:mm",
"openAppDrawerTooltip": "नेविगेशन मेन्यू खोलें",
"backButtonTooltip": "वापस जाएं",
"closeButtonTooltip": "बंद करें",
"deleteButtonTooltip": "मिटाएं",
"nextMonthTooltip": "अगला महीना",
"previousMonthTooltip": "पिछला महीना",
"nextPageTooltip": "अगला पेज",
"previousPageTooltip": "पिछला पेज",
"firstPageTooltip": "पहला पेज",
"lastPageTooltip": "आखिरी पेज",
"showMenuTooltip": "मेन्यू दिखाएं",
"aboutListTileTitle": "$applicationName के बारे में जानकारी",
"licensesPageTitle": "लाइसेंस",
"pageRowsInfoTitle": "$rowCount का $firstRow–$lastRow",
"pageRowsInfoTitleApproximate": "$rowCount में से करीब $firstRow–$lastRow",
"rowsPerPageTitle": "हर पेज में पंक्तियों की संख्या:",
"tabLabel": "$tabCount का टैब $tabIndex",
"selectedRowCountTitleOne": "1 चीज़ चुनी गई",
"selectedRowCountTitleOther": "$selectedRowCount चीज़ें चुनी गईं",
"cancelButtonLabel": "रद्द करें",
"closeButtonLabel": "बंद करें",
"continueButtonLabel": "जारी रखें",
"copyButtonLabel": "कॉपी करें",
"cutButtonLabel": "काटें",
"scanTextButtonLabel": "टेक्स्ट स्कैन करें",
"okButtonLabel": "ठीक है",
"pasteButtonLabel": "चिपकाएं",
"selectAllButtonLabel": "सभी को चुनें",
"viewLicensesButtonLabel": "लाइसेंस देखें",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "घंटे के हिसाब से समय चुनें",
"timePickerMinuteModeAnnouncement": "मिनट के हिसाब से समय चुनें",
"modalBarrierDismissLabel": "खारिज करें",
"signedInLabel": "साइन इन किया हुआ है",
"hideAccountsLabel": "खाते छिपाएं",
"showAccountsLabel": "खाते दिखाएं",
"drawerLabel": "नेविगेशन मेन्यू",
"popupMenuLabel": "पॉपअप मेन्यू",
"dialogLabel": "डायलॉग",
"alertDialogLabel": "अलर्ट",
"searchFieldLabel": "खोजें",
"reorderItemToStart": "शुरुआत पर ले जाएं",
"reorderItemToEnd": "आखिर में ले जाएं",
"reorderItemUp": "ऊपर ले जाएं",
"reorderItemDown": "नीचे ले जाएं",
"reorderItemLeft": "बाएं ले जाएं",
"reorderItemRight": "दाएं ले जाएं",
"expandedIconTapHint": "छोटा करें",
"collapsedIconTapHint": "बड़ा करें",
"remainingTextFieldCharacterCountOne": "एक वर्ण आैर डाला जा सकता है",
"remainingTextFieldCharacterCountOther": "$remainingCount वर्ण आैर डाले जा सकते हैं",
"refreshIndicatorSemanticLabel": "रीफ़्रेश करें",
"moreButtonTooltip": "ज़्यादा",
"dateSeparator": "/",
"dateHelpText": "dd/mm/yyyy",
"selectYearSemanticsLabel": "साल चुनें",
"unspecifiedDate": "तारीख",
"unspecifiedDateRange": "तारीख की सीमा",
"dateInputLabel": "तारीख डालें",
"dateRangeStartLabel": "पेमेंट करने की तारीख",
"dateRangeEndLabel": "खत्म होने की तारीख",
"dateRangeStartDateSemanticLabel": "शुरू होने की तारीख $fullDate",
"dateRangeEndDateSemanticLabel": "खत्म होने की तारीख $fullDate",
"invalidDateFormatLabel": "अमान्य फ़ॉर्मैट.",
"invalidDateRangeLabel": "तारीख की अमान्य सीमा.",
"dateOutOfRangeLabel": "सीमा से ज़्यादा.",
"saveButtonLabel": "सेव करें",
"datePickerHelpText": "तारीख चुनें",
"dateRangePickerHelpText": "रेंज चुनें",
"calendarModeButtonLabel": "कैलेंडर पर जाएं",
"inputDateModeButtonLabel": "इनपुट पर जाएं",
"timePickerDialHelpText": "समय चुनें",
"timePickerInputHelpText": "समय डालें",
"timePickerHourLabel": "घंटा",
"timePickerMinuteLabel": "मिनट",
"invalidTimeLabel": "मान्य समय डालें",
"dialModeButtonLabel": "डायल पिकर मोड पर स्विच करें",
"inputTimeModeButtonLabel": "टेक्स्ट के इनपुट मोड पर स्विच करें",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 लाइसेंस",
"licensesPackageDetailTextOther": "$licenseCount लाइसेंस",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Channel Down",
"keyboardKeyChannelUp": "Channel Up",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Eject",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyNumpad0": "Num 0",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEnter": "Num Enter",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "Power",
"keyboardKeyPowerOff": "Power Off",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Select",
"keyboardKeySpace": "Space",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "मेन्यू बार का मेन्यू",
"currentDateLabel": "आज",
"scrimLabel": "स्क्रिम",
"bottomSheetLabel": "बॉटम शीट",
"scrimOnTapHint": "$modalRouteContentName को बंद करें",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "छोटा करने के लिए दो बार टैप करें",
"expansionTileCollapsedHint": "बड़ा करने के लिए दो बार टैप करें",
"expansionTileExpandedTapHint": "छोटा करें",
"expansionTileCollapsedTapHint": "ज़्यादा जानकारी के लिए बड़ा करें",
"expandedHint": "छोटा किया गया",
"collapsedHint": "बड़ा किया गया",
"menuDismissLabel": "मेन्यू खारिज करें",
"lookUpButtonLabel": "लुक अप बटन",
"searchWebButtonLabel": "वेब पर खोजें",
"shareButtonLabel": "शेयर करें…",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_hi.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_hi.arb",
"repo_id": "flutter",
"token_count": 3741
} | 710 |
{
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"openAppDrawerTooltip": "Atvērt navigācijas izvēlni",
"backButtonTooltip": "Atpakaļ",
"closeButtonTooltip": "Aizvērt",
"deleteButtonTooltip": "Dzēst",
"nextMonthTooltip": "Nākamais mēnesis",
"previousMonthTooltip": "Iepriekšējais mēnesis",
"nextPageTooltip": "Nākamā lapa",
"previousPageTooltip": "Iepriekšējā lapa",
"firstPageTooltip": "Pirmā lapa",
"lastPageTooltip": "Pēdējā lapa",
"showMenuTooltip": "Rādīt izvēlni",
"aboutListTileTitle": "Par $applicationName",
"licensesPageTitle": "Licences",
"pageRowsInfoTitle": "$firstRow.–$lastRow. no $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow.–$lastRow. no aptuveni $rowCount",
"rowsPerPageTitle": "Rindas lapā:",
"tabLabel": "$tabIndex. cilne no $tabCount",
"selectedRowCountTitleZero": "Nav atlasītu vienumu",
"selectedRowCountTitleOne": "Atlasīts 1 vienums",
"selectedRowCountTitleOther": "Atlasīti $selectedRowCount vienumi",
"cancelButtonLabel": "Atcelt",
"closeButtonLabel": "Aizvērt",
"continueButtonLabel": "Turpināt",
"copyButtonLabel": "Kopēt",
"cutButtonLabel": "Izgriezt",
"scanTextButtonLabel": "Skenēt tekstu",
"okButtonLabel": "LABI",
"pasteButtonLabel": "Ielīmēt",
"selectAllButtonLabel": "Atlasīt visu",
"viewLicensesButtonLabel": "Skatīt licences",
"anteMeridiemAbbreviation": "priekšpusdienā",
"postMeridiemAbbreviation": "pēcpusdienā",
"timePickerHourModeAnnouncement": "Atlasiet stundas",
"timePickerMinuteModeAnnouncement": "Atlasiet minūtes",
"modalBarrierDismissLabel": "Nerādīt",
"signedInLabel": "Esat pierakstījies",
"hideAccountsLabel": "Slēpt kontus",
"showAccountsLabel": "Rādīt kontus",
"drawerLabel": "Navigācijas izvēlne",
"popupMenuLabel": "Uznirstošā izvēlne",
"dialogLabel": "Dialoglodziņš",
"alertDialogLabel": "Brīdinājums",
"searchFieldLabel": "Meklēt",
"reorderItemToStart": "Pārvietot uz sākumu",
"reorderItemToEnd": "Pārvietot uz beigām",
"reorderItemUp": "Pārvietot uz augšu",
"reorderItemDown": "Pārvietot uz leju",
"reorderItemLeft": "Pārvietot pa kreisi",
"reorderItemRight": "Pārvietot pa labi",
"expandedIconTapHint": "Sakļaut",
"collapsedIconTapHint": "Izvērst",
"remainingTextFieldCharacterCountZero": "Nav atlikusi neviena rakstzīme.",
"remainingTextFieldCharacterCountOne": "Atlikusi 1 rakstzīme.",
"remainingTextFieldCharacterCountOther": "Atlikušas $remainingCount rakstzīmes.",
"refreshIndicatorSemanticLabel": "Atsvaidzināt",
"moreButtonTooltip": "Vairāk",
"dateSeparator": ".",
"dateHelpText": "dd/mm/gggg",
"selectYearSemanticsLabel": "Atlasiet gadu",
"unspecifiedDate": "Datums",
"unspecifiedDateRange": "Datumu diapazons",
"dateInputLabel": "Ievadiet datumu",
"dateRangeStartLabel": "Sākuma datums",
"dateRangeEndLabel": "Beigu datums",
"dateRangeStartDateSemanticLabel": "Sākuma datums: $fullDate",
"dateRangeEndDateSemanticLabel": "Beigu datums: $fullDate",
"invalidDateFormatLabel": "Nederīgs formāts.",
"invalidDateRangeLabel": "Nederīgs diapazons.",
"dateOutOfRangeLabel": "Ārpus diapazona.",
"saveButtonLabel": "Saglabāt",
"datePickerHelpText": "Atlasiet datumu",
"dateRangePickerHelpText": "Atlasiet diapazonu",
"calendarModeButtonLabel": "Pārslēgties uz kalendāru",
"inputDateModeButtonLabel": "Pārslēgties uz ievadi",
"timePickerDialHelpText": "Atlasiet laiku",
"timePickerInputHelpText": "Ievadiet laiku",
"timePickerHourLabel": "Stunda",
"timePickerMinuteLabel": "Minūte",
"invalidTimeLabel": "Ievadiet derīgu laiku.",
"dialModeButtonLabel": "Pārslēgties uz ciparnīcas atlasītāja režīmu",
"inputTimeModeButtonLabel": "Pārslēgties uz teksta ievades režīmu",
"licensesPackageDetailTextZero": "Nav licenču",
"licensesPackageDetailTextOne": "1 licence",
"licensesPackageDetailTextOther": "$licenseCount licences",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Nākamais kanāls",
"keyboardKeyChannelUp": "Iepriekšējais kanāls",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Izstumt",
"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": "Ieslēgt",
"keyboardKeyPowerOff": "Izslēgt",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Atlasīt",
"keyboardKeySpace": "Atstarpes taustiņš",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Windows",
"menuBarMenuLabel": "Izvēļņu joslas izvēlne",
"currentDateLabel": "Šodien",
"scrimLabel": "Pārklājums",
"bottomSheetLabel": "Ekrāna apakšdaļas lapa",
"scrimOnTapHint": "Aizvērt $modalRouteContentName",
"keyboardKeyShift": "Pārslēgšanas taustiņš",
"expansionTileExpandedHint": "dubultskāriens, lai sakļautu",
"expansionTileCollapsedHint": "dubultskāriens, lai izvērstu",
"expansionTileExpandedTapHint": "Sakļaut",
"expansionTileCollapsedTapHint": "Izvērst, lai iegūtu plašāku informāciju",
"expandedHint": "Sakļauts",
"collapsedHint": "Izvērsts",
"menuDismissLabel": "Nerādīt izvēlni",
"lookUpButtonLabel": "Meklēt",
"searchWebButtonLabel": "Meklēt tīmeklī",
"shareButtonLabel": "Kopīgot…",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_lv.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_lv.arb",
"repo_id": "flutter",
"token_count": 2622
} | 711 |
{
"searchWebButtonLabel": "Pesquisar na Web",
"shareButtonLabel": "Partilhar…",
"scanTextButtonLabel": "Digitalizar texto",
"lookUpButtonLabel": "Procurar",
"menuDismissLabel": "Ignorar menu",
"expansionTileExpandedHint": "toque duas vezes para reduzir",
"expansionTileCollapsedHint": "toque duas vezes para expandir",
"expansionTileExpandedTapHint": "Reduzir",
"expansionTileCollapsedTapHint": "Expandir para obter mais detalhes",
"expandedHint": "Reduzido",
"collapsedHint": "Expandido",
"scrimLabel": "Scrim",
"bottomSheetLabel": "Secção inferior",
"scrimOnTapHint": "Fechar $modalRouteContentName",
"currentDateLabel": "Hoje",
"keyboardKeyShift": "Shift",
"menuBarMenuLabel": "Menu da barra de menu",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyChannelDown": "Canal anterior",
"keyboardKeyBackspace": "Retrocesso",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad0": "Num 0",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyInsert": "Inserir",
"keyboardKeyHome": "Início",
"keyboardKeyEnd": "Fim",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyFn": "Fn",
"keyboardKeyEscape": "Esc",
"keyboardKeyEject": "Ejetar",
"keyboardKeyDelete": "Del",
"keyboardKeyControl": "Ctrl",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyChannelUp": "Canal seguinte",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeySelect": "Selecionar",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyAlt": "Alt",
"keyboardKeyMeta": "Meta",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyPageDown": "PgDown",
"keyboardKeySpace": "Espaço",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyPowerOff": "Desligar",
"keyboardKeyPower": "Alimentação",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyNumpadEnter": "Num Enter",
"dialModeButtonLabel": "Mude para o modo de seletor de mostrador",
"licensesPackageDetailTextOne": "1 licença",
"timePickerDialHelpText": "Selecionar hora",
"timePickerInputHelpText": "Introduzir hora",
"timePickerHourLabel": "Hora",
"timePickerMinuteLabel": "Minuto",
"invalidTimeLabel": "Introduza uma hora válida.",
"licensesPackageDetailTextOther": "$licenseCount licenças",
"inputTimeModeButtonLabel": "Mude para o método de introdução de texto",
"dateSeparator": "/",
"dateInputLabel": "Introduzir data",
"calendarModeButtonLabel": "Mude para o calendário",
"dateRangePickerHelpText": "Selecionar intervalo",
"datePickerHelpText": "Selecionar data",
"saveButtonLabel": "Guardar",
"dateOutOfRangeLabel": "Fora do intervalo.",
"invalidDateRangeLabel": "Intervalo inválido.",
"invalidDateFormatLabel": "Formato inválido.",
"dateRangeEndDateSemanticLabel": "Data de conclusão: $fullDate",
"dateRangeStartDateSemanticLabel": "Data de início: $fullDate",
"dateRangeEndLabel": "Data de conclusão",
"dateRangeStartLabel": "Data de início",
"inputDateModeButtonLabel": "Mude para a introdução",
"unspecifiedDateRange": "Intervalo de datas",
"unspecifiedDate": "Data",
"selectYearSemanticsLabel": "Selecionar ano",
"dateHelpText": "dd/mm/aaaa",
"moreButtonTooltip": "Mais",
"tabLabel": "Separador $tabIndex de $tabCount",
"showAccountsLabel": "Mostrar contas",
"hideAccountsLabel": "Ocultar contas",
"signedInLabel": "Com sessão iniciada",
"timePickerMinuteModeAnnouncement": "Selecionar minutos",
"timePickerHourModeAnnouncement": "Selecionar horas",
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"openAppDrawerTooltip": "Abrir menu de navegação",
"backButtonTooltip": "Voltar",
"closeButtonTooltip": "Fechar",
"deleteButtonTooltip": "Eliminar",
"nextMonthTooltip": "Mês seguinte",
"previousMonthTooltip": "Mês anterior",
"nextPageTooltip": "Página seguinte",
"previousPageTooltip": "Página anterior",
"firstPageTooltip": "Primeira página",
"lastPageTooltip": "Última página",
"showMenuTooltip": "Mostrar menu",
"aboutListTileTitle": "Acerca de $applicationName",
"licensesPageTitle": "Licenças",
"pageRowsInfoTitle": "$firstRow a $lastRow de $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow a $lastRow de cerca de $rowCount",
"rowsPerPageTitle": "Linhas por página:",
"selectedRowCountTitleOne": "1 item selecionado",
"selectedRowCountTitleOther": "$selectedRowCount itens selecionados",
"cancelButtonLabel": "Cancelar",
"closeButtonLabel": "Fechar",
"continueButtonLabel": "Continuar",
"copyButtonLabel": "Copiar",
"cutButtonLabel": "Cortar",
"okButtonLabel": "OK",
"pasteButtonLabel": "Colar",
"selectAllButtonLabel": "Selecionar tudo",
"viewLicensesButtonLabel": "Ver licenças",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"modalBarrierDismissLabel": "Ignorar",
"drawerLabel": "Menu de navegação",
"popupMenuLabel": "Menu pop-up",
"dialogLabel": "Caixa de diálogo",
"alertDialogLabel": "Alerta",
"searchFieldLabel": "Pesquisar",
"reorderItemToStart": "Mover para o início",
"reorderItemToEnd": "Mover para o fim",
"reorderItemUp": "Mover para cima",
"reorderItemDown": "Mover para baixo",
"reorderItemLeft": "Mover para a esquerda",
"reorderItemRight": "Mover para a direita",
"expandedIconTapHint": "Reduzir",
"collapsedIconTapHint": "Expandir",
"remainingTextFieldCharacterCountOne": "Resta 1 caráter",
"remainingTextFieldCharacterCountOther": "Restam $remainingCount carateres",
"refreshIndicatorSemanticLabel": "Atualizar"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_pt_PT.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_pt_PT.arb",
"repo_id": "flutter",
"token_count": 2263
} | 712 |
{
"licensesPackageDetailTextFew": "$licenseCount ліцензії",
"licensesPackageDetailTextMany": "$licenseCount ліцензій",
"remainingTextFieldCharacterCountFew": "Залишилося $remainingCount символи",
"remainingTextFieldCharacterCountMany": "Залишилося $remainingCount символів",
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"selectedRowCountTitleFew": "Вибрано $selectedRowCount елементи",
"selectedRowCountTitleMany": "Вибрано $selectedRowCount елементів",
"openAppDrawerTooltip": "Відкрити меню навігації",
"backButtonTooltip": "Назад",
"closeButtonTooltip": "Закрити",
"deleteButtonTooltip": "Видалити",
"nextMonthTooltip": "Наступний місяць",
"previousMonthTooltip": "Попередній місяць",
"nextPageTooltip": "Наступна сторінка",
"previousPageTooltip": "Попередня сторінка",
"firstPageTooltip": "Перша сторінка",
"lastPageTooltip": "Остання сторінка",
"showMenuTooltip": "Показати меню",
"aboutListTileTitle": "Про додаток $applicationName",
"licensesPageTitle": "Ліцензії",
"pageRowsInfoTitle": "$firstRow–$lastRow з $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow з приблизно $rowCount",
"rowsPerPageTitle": "Рядків на сторінці:",
"tabLabel": "Вкладка $tabIndex з $tabCount",
"selectedRowCountTitleOne": "Вибрано 1 елемент",
"selectedRowCountTitleOther": "Вибрано $selectedRowCount елемента",
"cancelButtonLabel": "Скасувати",
"closeButtonLabel": "Закрити",
"continueButtonLabel": "Продовжити",
"copyButtonLabel": "Копіювати",
"cutButtonLabel": "Вирізати",
"scanTextButtonLabel": "Відсканувати текст",
"okButtonLabel": "OK",
"pasteButtonLabel": "Вставити",
"selectAllButtonLabel": "Вибрати всі",
"viewLicensesButtonLabel": "Переглянути ліцензії",
"anteMeridiemAbbreviation": "дп",
"postMeridiemAbbreviation": "пп",
"timePickerHourModeAnnouncement": "Виберіть години",
"timePickerMinuteModeAnnouncement": "Виберіть хвилини",
"modalBarrierDismissLabel": "Закрити",
"signedInLabel": "Ви ввійшли",
"hideAccountsLabel": "Сховати облікові записи",
"showAccountsLabel": "Показати облікові записи",
"drawerLabel": "Меню навігації",
"popupMenuLabel": "Спливаюче меню",
"dialogLabel": "Вікно",
"alertDialogLabel": "Сповіщення",
"searchFieldLabel": "Пошук",
"reorderItemToStart": "Перемістити на початок",
"reorderItemToEnd": "Перемістити в кінець",
"reorderItemUp": "Перемістити вгору",
"reorderItemDown": "Перемістити вниз",
"reorderItemLeft": "Перемістити ліворуч",
"reorderItemRight": "Перемістити праворуч",
"expandedIconTapHint": "Згорнути",
"collapsedIconTapHint": "Розгорнути",
"remainingTextFieldCharacterCountOne": "Залишився 1 символ",
"remainingTextFieldCharacterCountOther": "Залишилося $remainingCount символу",
"refreshIndicatorSemanticLabel": "Оновити",
"moreButtonTooltip": "Інші",
"dateSeparator": ".",
"dateHelpText": "дд.мм.рррр",
"selectYearSemanticsLabel": "Виберіть рік",
"unspecifiedDate": "Дата",
"unspecifiedDateRange": "Діапазон дат",
"dateInputLabel": "Введіть дату",
"dateRangeStartLabel": "Дата початку",
"dateRangeEndLabel": "Дата завершення",
"dateRangeStartDateSemanticLabel": "Дата початку $fullDate",
"dateRangeEndDateSemanticLabel": "Дата завершення $fullDate",
"invalidDateFormatLabel": "Недійсний формат.",
"invalidDateRangeLabel": "Недійсний діапазон.",
"dateOutOfRangeLabel": "За межами діапазону.",
"saveButtonLabel": "Зберегти",
"datePickerHelpText": "Вибрати дату",
"dateRangePickerHelpText": "Вибрати діапазон дат",
"calendarModeButtonLabel": "Перейти до календаря",
"inputDateModeButtonLabel": "Ввести вручну",
"timePickerDialHelpText": "Вибрати час",
"timePickerInputHelpText": "Ввести час",
"timePickerHourLabel": "Години",
"timePickerMinuteLabel": "Хвилини",
"invalidTimeLabel": "Введіть дійсний час",
"dialModeButtonLabel": "Перейти в режим вибору на циферблаті",
"inputTimeModeButtonLabel": "Перейти в режим введення цифр",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 ліцензія",
"licensesPackageDetailTextOther": "$licenseCount ліцензії",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Канал униз",
"keyboardKeyChannelUp": "Канал угору",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Вийняти",
"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_uk.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_uk.arb",
"repo_id": "flutter",
"token_count": 3599
} | 713 |
{
"reorderItemToStart": "Pomjerite na početak",
"reorderItemToEnd": "Pomjerite na kraj",
"reorderItemUp": "Pomjeri nagore",
"reorderItemDown": "Pomjeri nadolje",
"reorderItemLeft": "Pomjeri lijevo",
"reorderItemRight": "Pomjeri desno"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_bs.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_bs.arb",
"repo_id": "flutter",
"token_count": 112
} | 714 |
{
"reorderItemToStart": "העברה להתחלה",
"reorderItemToEnd": "העברה לסוף",
"reorderItemUp": "העברה למעלה",
"reorderItemDown": "העברה למטה",
"reorderItemLeft": "העברה שמאלה",
"reorderItemRight": "העברה ימינה"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_he.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_he.arb",
"repo_id": "flutter",
"token_count": 142
} | 715 |
{
"reorderItemToStart": "Perkelti į pradžią",
"reorderItemToEnd": "Perkelti į pabaigą",
"reorderItemUp": "Perkelti aukštyn",
"reorderItemDown": "Perkelti žemyn",
"reorderItemLeft": "Perkelti kairėn",
"reorderItemRight": "Perkelti dešinėn"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_lt.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_lt.arb",
"repo_id": "flutter",
"token_count": 126
} | 716 |
{
"reorderItemToStart": "Mover para o início",
"reorderItemToEnd": "Mover para o final",
"reorderItemUp": "Mover para cima",
"reorderItemDown": "Mover para baixo",
"reorderItemLeft": "Mover para a esquerda",
"reorderItemRight": "Mover para a direita"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_pt.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_pt.arb",
"repo_id": "flutter",
"token_count": 103
} | 717 |
{
"reorderItemToStart": "Başa taşı",
"reorderItemToEnd": "Sona taşı",
"reorderItemUp": "Yukarı taşı",
"reorderItemDown": "Aşağı taşı",
"reorderItemLeft": "Sola taşı",
"reorderItemRight": "Sağa taşı"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_tr.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_tr.arb",
"repo_id": "flutter",
"token_count": 103
} | 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/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:intl/intl.dart' as intl;
void main() {
late DateTime firstDate;
late DateTime lastDate;
late DateTime initialDate;
setUp(() {
firstDate = DateTime(2001);
lastDate = DateTime(2031, DateTime.december, 31);
initialDate = DateTime(2016, DateTime.january, 15);
});
group(CalendarDatePicker, () {
final intl.NumberFormat arabicNumbers = intl.NumberFormat('0', 'ar');
final Map<Locale, Map<String, dynamic>> testLocales = <Locale, Map<String, dynamic>>{
// Tests the default.
const Locale('en', 'US'): <String, dynamic>{
'textDirection': TextDirection.ltr,
'expectedDaysOfWeek': <String>['S', 'M', 'T', 'W', 'T', 'F', 'S'],
'expectedDaysOfMonth': List<String>.generate(30, (int i) => '${i + 1}'),
'expectedMonthYearHeader': 'September 2017',
},
// Tests a different first day of week.
const Locale('ru', 'RU'): <String, dynamic>{
'textDirection': TextDirection.ltr,
'expectedDaysOfWeek': <String>['В', 'П', 'В', 'С', 'Ч', 'П', 'С',],
'expectedDaysOfMonth': List<String>.generate(30, (int i) => '${i + 1}'),
'expectedMonthYearHeader': 'сентябрь 2017 г.',
},
const Locale('ro', 'RO'): <String, dynamic>{
'textDirection': TextDirection.ltr,
'expectedDaysOfWeek': <String>['D', 'L', 'M', 'M', 'J', 'V', 'S'],
'expectedDaysOfMonth': List<String>.generate(30, (int i) => '${i + 1}'),
'expectedMonthYearHeader': 'septembrie 2017',
},
// Tests RTL.
const Locale('ar', 'AR'): <String, dynamic>{
'textDirection': TextDirection.rtl,
'expectedDaysOfWeek': <String>['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
'expectedDaysOfMonth': List<String>.generate(30, (int i) => arabicNumbers.format(i + 1)),
'expectedMonthYearHeader': 'سبتمبر ٢٠١٧',
},
};
for (final Locale locale in testLocales.keys) {
testWidgets('shows dates for $locale', (WidgetTester tester) async {
final List<String> expectedDaysOfWeek = testLocales[locale]!['expectedDaysOfWeek'] as List<String>;
final List<String> expectedDaysOfMonth = testLocales[locale]!['expectedDaysOfMonth'] as List<String>;
final String expectedMonthYearHeader = testLocales[locale]!['expectedMonthYearHeader'] as String;
final TextDirection textDirection = testLocales[locale]!['textDirection'] as TextDirection;
final DateTime baseDate = DateTime(2017, 9, 27);
await _pumpBoilerplate(tester, CalendarDatePicker(
initialDate: baseDate,
firstDate: baseDate.subtract(const Duration(days: 90)),
lastDate: baseDate.add(const Duration(days: 90)),
onDateChanged: (DateTime newValue) {},
), locale: locale, textDirection: textDirection);
expect(find.text(expectedMonthYearHeader), findsOneWidget);
for (final String dayOfWeek in expectedDaysOfWeek) {
expect(find.text(dayOfWeek), findsWidgets);
}
Offset? previousCellOffset;
for (final String dayOfMonth in expectedDaysOfMonth) {
final Finder dayCell = find.descendant(of: find.byType(GridView), matching: find.text(dayOfMonth));
expect(dayCell, findsOneWidget);
// Check that cells are correctly positioned relative to each other,
// taking text direction into account.
final Offset offset = tester.getCenter(dayCell);
if (previousCellOffset != null) {
if (textDirection == TextDirection.ltr) {
expect(offset.dx > previousCellOffset.dx && offset.dy == previousCellOffset.dy || offset.dy > previousCellOffset.dy, true);
} else {
expect(offset.dx < previousCellOffset.dx && offset.dy == previousCellOffset.dy || offset.dy > previousCellOffset.dy, true);
}
}
previousCellOffset = offset;
}
});
}
});
testWidgets('Material2 - locale parameter overrides ambient locale', (WidgetTester tester) async {
Widget buildFrame() {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
locale: const Locale('en', 'US'),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('fr', 'CA'),
],
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Material(
child: Builder(
builder: (BuildContext context) {
return TextButton(
onPressed: () async {
await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
locale: const Locale('fr', 'CA'),
);
},
child: const Text('X'),
);
},
),
),
);
}
Element getPicker() => tester.element(find.byType(CalendarDatePicker));
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(
Localizations.localeOf(getPicker()),
const Locale('fr', 'CA'),
);
expect(
Directionality.of(getPicker()),
TextDirection.ltr,
);
await tester.tap(find.text('ANNULER'));
});
testWidgets('Material3 - locale parameter overrides ambient locale', (WidgetTester tester) async {
Widget buildFrame() {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
locale: const Locale('en', 'US'),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('fr', 'CA'),
],
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Material(
child: Builder(
builder: (BuildContext context) {
return TextButton(
onPressed: () async {
await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
locale: const Locale('fr', 'CA'),
);
},
child: const Text('X'),
);
},
),
),
);
}
Element getPicker() => tester.element(find.byType(CalendarDatePicker));
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(
Localizations.localeOf(getPicker()),
const Locale('fr', 'CA'),
);
expect(
Directionality.of(getPicker()),
TextDirection.ltr,
);
await tester.tap(find.text('Annuler'));
});
testWidgets('Material2 - textDirection parameter overrides ambient textDirection', (WidgetTester tester) async {
Widget buildFrame() {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
locale: const Locale('en', 'US'),
home: Material(
child: Builder(
builder: (BuildContext context) {
return TextButton(
onPressed: () async {
await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
textDirection: TextDirection.rtl,
);
},
child: const Text('X'),
);
},
),
),
);
}
Element getPicker() => tester.element(find.byType(CalendarDatePicker));
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(
Directionality.of(getPicker()),
TextDirection.rtl,
);
await tester.tap(find.text('CANCEL'));
});
testWidgets('Material3 - textDirection parameter overrides ambient textDirection', (WidgetTester tester) async {
Widget buildFrame() {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
locale: const Locale('en', 'US'),
home: Material(
child: Builder(
builder: (BuildContext context) {
return TextButton(
onPressed: () async {
await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
textDirection: TextDirection.rtl,
);
},
child: const Text('X'),
);
},
),
),
);
}
Element getPicker() => tester.element(find.byType(CalendarDatePicker));
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(
Directionality.of(getPicker()),
TextDirection.rtl,
);
await tester.tap(find.text('Cancel'));
});
testWidgets('Material2 - textDirection parameter takes precedence over locale parameter', (WidgetTester tester) async {
Widget buildFrame() {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
locale: const Locale('en', 'US'),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('fr', 'CA'),
],
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Material(
child: Builder(
builder: (BuildContext context) {
return TextButton(
onPressed: () async {
await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
locale: const Locale('fr', 'CA'),
textDirection: TextDirection.rtl,
);
},
child: const Text('X'),
);
},
),
),
);
}
Element getPicker() => tester.element(find.byType(CalendarDatePicker));
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(
Localizations.localeOf(getPicker()),
const Locale('fr', 'CA'),
);
expect(
Directionality.of(getPicker()),
TextDirection.rtl,
);
await tester.tap(find.text('ANNULER'));
});
testWidgets('Material3 - textDirection parameter takes precedence over locale parameter', (WidgetTester tester) async {
Widget buildFrame() {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
locale: const Locale('en', 'US'),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('fr', 'CA'),
],
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Material(
child: Builder(
builder: (BuildContext context) {
return TextButton(
onPressed: () async {
await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
locale: const Locale('fr', 'CA'),
textDirection: TextDirection.rtl,
);
},
child: const Text('X'),
);
},
),
),
);
}
Element getPicker() => tester.element(find.byType(CalendarDatePicker));
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pumpAndSettle(const Duration(seconds: 1));
expect(
Localizations.localeOf(getPicker()),
const Locale('fr', 'CA'),
);
expect(
Directionality.of(getPicker()),
TextDirection.rtl,
);
await tester.tap(find.text('Annuler'));
});
group("locale fonts don't overflow layout", () {
// Test screen layouts in various locales to ensure the fonts used
// don't overflow the layout
// Common screen size roughly based on a Pixel 1
const Size kCommonScreenSizePortrait = Size(1070, 1770);
const Size kCommonScreenSizeLandscape = Size(1770, 1070);
Future<void> showPicker(WidgetTester tester, Locale locale, Size size) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (BuildContext context) {
return Localizations(
locale: locale,
delegates: GlobalMaterialLocalizations.delegates,
child: TextButton(
child: const Text('X'),
onPressed: () {
showDatePicker(
context: context,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
);
},
),
);
},
),
)
);
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
}
// Regression test for https://github.com/flutter/flutter/issues/20171
testWidgets('common screen size - portrait - Chinese', (WidgetTester tester) async {
await showPicker(tester, const Locale('zh', 'CN'), kCommonScreenSizePortrait);
expect(tester.takeException(), isNull);
});
testWidgets('common screen size - landscape - Chinese', (WidgetTester tester) async {
await showPicker(tester, const Locale('zh', 'CN'), kCommonScreenSizeLandscape);
expect(tester.takeException(), isNull);
});
testWidgets('common screen size - portrait - Japanese', (WidgetTester tester) async {
await showPicker(tester, const Locale('ja', 'JA'), kCommonScreenSizePortrait);
expect(tester.takeException(), isNull);
});
testWidgets('common screen size - landscape - Japanese', (WidgetTester tester) async {
await showPicker(tester, const Locale('ja', 'JA'), kCommonScreenSizeLandscape);
expect(tester.takeException(), isNull);
});
});
}
Future<void> _pumpBoilerplate(
WidgetTester tester,
Widget child, {
Locale locale = const Locale('en', 'US'),
TextDirection textDirection = TextDirection.ltr,
}) async {
await tester.pumpWidget(MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Localizations(
locale: locale,
delegates: GlobalMaterialLocalizations.delegates,
child: Material(
child: child,
),
),
),
));
}
| flutter/packages/flutter_localizations/test/material/date_picker_test.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/test/material/date_picker_test.dart",
"repo_id": "flutter",
"token_count": 6995
} | 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.
import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'binding.dart';
import 'test_async_utils.dart';
import 'widget_tester.dart';
// A tuple of `key` and `location` from Web's `KeyboardEvent` class.
//
// See [RawKeyEventDataWeb]'s `key` and `location` fields for details.
@immutable
class _WebKeyLocationPair {
const _WebKeyLocationPair(this.key, this.location);
final String key;
final int location;
}
// TODO(gspencergoog): Replace this with more robust key simulation code once
// the new key event code is in.
// https://github.com/flutter/flutter/issues/33521
// This code can only simulate keys which appear in the key maps.
String? _keyLabel(LogicalKeyboardKey key) {
final String keyLabel = key.keyLabel;
if (keyLabel.length == 1) {
return keyLabel.toLowerCase();
}
return null;
}
/// A class that serves as a namespace for a bunch of keyboard-key generation
/// utilities.
abstract final class KeyEventSimulator {
// Look up a synonym key, and just return the left version of it.
static LogicalKeyboardKey _getKeySynonym(LogicalKeyboardKey origKey) {
if (origKey == LogicalKeyboardKey.shift) {
return LogicalKeyboardKey.shiftLeft;
}
if (origKey == LogicalKeyboardKey.alt) {
return LogicalKeyboardKey.altLeft;
}
if (origKey == LogicalKeyboardKey.meta) {
return LogicalKeyboardKey.metaLeft;
}
if (origKey == LogicalKeyboardKey.control) {
return LogicalKeyboardKey.controlLeft;
}
return origKey;
}
static bool _osIsSupported(String platform) {
switch (platform) {
case 'android':
case 'fuchsia':
case 'macos':
case 'linux':
case 'web':
case 'ios':
case 'windows':
return true;
}
return false;
}
static int _getScanCode(PhysicalKeyboardKey key, String platform) {
assert(_osIsSupported(platform), 'Platform $platform not supported for key simulation');
late Map<int, PhysicalKeyboardKey> map;
switch (platform) {
case 'android':
map = kAndroidToPhysicalKey;
case 'fuchsia':
map = kFuchsiaToPhysicalKey;
case 'macos':
map = kMacOsToPhysicalKey;
case 'ios':
map = kIosToPhysicalKey;
case 'linux':
map = kLinuxToPhysicalKey;
case 'windows':
map = kWindowsToPhysicalKey;
case 'web':
// web doesn't have int type code
return -1;
}
int? scanCode;
for (final int code in map.keys) {
if (key.usbHidUsage == map[code]!.usbHidUsage) {
scanCode = code;
break;
}
}
assert(scanCode != null, 'Physical key for $key not found in $platform scanCode map');
return scanCode!;
}
static int _getKeyCode(LogicalKeyboardKey key, String platform) {
assert(_osIsSupported(platform), 'Platform $platform not supported for key simulation');
if (kIsWeb) {
// web doesn't have int type code. This check is used to treeshake
// keyboard map code.
return -1;
} else {
late Map<int, LogicalKeyboardKey> map;
switch (platform) {
case 'android':
map = kAndroidToLogicalKey;
case 'fuchsia':
map = kFuchsiaToLogicalKey;
case 'macos':
// macOS doesn't do key codes, just scan codes.
return -1;
case 'ios':
// iOS doesn't do key codes, just scan codes.
return -1;
case 'web':
// web doesn't have int type code.
return -1;
case 'linux':
map = kGlfwToLogicalKey;
case 'windows':
map = kWindowsToLogicalKey;
}
int? keyCode;
for (final int code in map.keys) {
if (key.keyId == map[code]!.keyId) {
keyCode = code;
break;
}
}
assert(keyCode != null, 'Key $key not found in $platform keyCode map');
return keyCode!;
}
}
static PhysicalKeyboardKey _inferPhysicalKey(LogicalKeyboardKey key) {
PhysicalKeyboardKey? result;
for (final PhysicalKeyboardKey physicalKey in PhysicalKeyboardKey.knownPhysicalKeys) {
if (physicalKey.debugName == key.debugName) {
result = physicalKey;
break;
}
}
assert(result != null, 'Unable to infer physical key for $key');
return result!;
}
static _WebKeyLocationPair _getWebKeyLocation(LogicalKeyboardKey key, String keyLabel) {
String? result;
for (final MapEntry<String, List<LogicalKeyboardKey?>> entry in kWebLocationMap.entries) {
final int foundIndex = entry.value.lastIndexOf(key);
// If foundIndex is -1, then the key is not defined in kWebLocationMap.
// If foundIndex is 0, then the key is in the standard part of the keyboard,
// but we have to check `keyLabel` to see if it's remapped or modified.
if (foundIndex != -1 && foundIndex != 0) {
return _WebKeyLocationPair(entry.key, foundIndex);
}
}
if (keyLabel.isNotEmpty) {
return _WebKeyLocationPair(keyLabel, 0);
}
for (final String code in kWebToLogicalKey.keys) {
if (key.keyId == kWebToLogicalKey[code]!.keyId) {
result = code;
break;
}
}
assert(result != null, 'Key $key not found in web keyCode map');
return _WebKeyLocationPair(result!, 0);
}
static String _getWebCode(PhysicalKeyboardKey key) {
String? result;
for (final MapEntry<String, PhysicalKeyboardKey> entry in kWebToPhysicalKey.entries) {
if (entry.value.usbHidUsage == key.usbHidUsage) {
result = entry.key;
break;
}
}
assert(result != null, 'Key $key not found in web code map');
return result!;
}
static PhysicalKeyboardKey _findPhysicalKeyByPlatform(LogicalKeyboardKey key, String platform) {
assert(_osIsSupported(platform), 'Platform $platform not supported for key simulation');
late Map<dynamic, PhysicalKeyboardKey> map;
if (kIsWeb) {
// This check is used to treeshake keymap code.
map = kWebToPhysicalKey;
} else {
switch (platform) {
case 'android':
map = kAndroidToPhysicalKey;
case 'fuchsia':
map = kFuchsiaToPhysicalKey;
case 'macos':
map = kMacOsToPhysicalKey;
case 'ios':
map = kIosToPhysicalKey;
case 'linux':
map = kLinuxToPhysicalKey;
case 'web':
map = kWebToPhysicalKey;
case 'windows':
map = kWindowsToPhysicalKey;
}
}
PhysicalKeyboardKey? result;
for (final PhysicalKeyboardKey physicalKey in map.values) {
if (key.debugName == physicalKey.debugName) {
result = physicalKey;
break;
}
}
assert(result != null, 'Physical key for $key not found in $platform physical key map');
return result!;
}
/// Get a raw key data map given a [LogicalKeyboardKey] and a platform.
static Map<String, dynamic> getKeyData(
LogicalKeyboardKey key, {
required String platform,
bool isDown = true,
PhysicalKeyboardKey? physicalKey,
String? character,
}) {
assert(_osIsSupported(platform), 'Platform $platform not supported for key simulation');
key = _getKeySynonym(key);
// Find a suitable physical key if none was supplied.
physicalKey ??= _findPhysicalKeyByPlatform(key, platform);
assert(key.debugName != null);
final Map<String, dynamic> result = <String, dynamic>{
'type': isDown ? 'keydown' : 'keyup',
'keymap': platform,
};
final String resultCharacter = character ?? _keyLabel(key) ?? '';
void assignWeb() {
final _WebKeyLocationPair keyLocation = _getWebKeyLocation(key, resultCharacter);
final PhysicalKeyboardKey actualPhysicalKey = physicalKey ?? _inferPhysicalKey(key);
result['code'] = _getWebCode(actualPhysicalKey);
result['key'] = keyLocation.key;
result['location'] = keyLocation.location;
result['metaState'] = _getWebModifierFlags(key, isDown);
}
if (kIsWeb) {
assignWeb();
return result;
}
final int keyCode = _getKeyCode(key, platform);
final int scanCode = _getScanCode(physicalKey, platform);
switch (platform) {
case 'android':
result['keyCode'] = keyCode;
if (resultCharacter.isNotEmpty) {
result['codePoint'] = resultCharacter.codeUnitAt(0);
result['character'] = resultCharacter;
}
result['scanCode'] = scanCode;
result['metaState'] = _getAndroidModifierFlags(key, isDown);
case 'fuchsia':
result['hidUsage'] = physicalKey.usbHidUsage;
if (resultCharacter.isNotEmpty) {
result['codePoint'] = resultCharacter.codeUnitAt(0);
}
result['modifiers'] = _getFuchsiaModifierFlags(key, isDown);
case 'linux':
result['toolkit'] = 'glfw';
result['keyCode'] = keyCode;
result['scanCode'] = scanCode;
result['modifiers'] = _getGlfwModifierFlags(key, isDown);
result['unicodeScalarValues'] = resultCharacter.isNotEmpty ? resultCharacter.codeUnitAt(0) : 0;
case 'macos':
result['keyCode'] = scanCode;
if (resultCharacter.isNotEmpty) {
result['characters'] = resultCharacter;
result['charactersIgnoringModifiers'] = resultCharacter;
}
result['modifiers'] = _getMacOsModifierFlags(key, isDown);
case 'ios':
result['keyCode'] = scanCode;
result['characters'] = resultCharacter;
result['charactersIgnoringModifiers'] = resultCharacter;
result['modifiers'] = _getIOSModifierFlags(key, isDown);
case 'windows':
result['keyCode'] = keyCode;
result['scanCode'] = scanCode;
if (resultCharacter.isNotEmpty) {
result['characterCodePoint'] = resultCharacter.codeUnitAt(0);
}
result['modifiers'] = _getWindowsModifierFlags(key, isDown);
case 'web':
assignWeb();
}
return result;
}
static int _getAndroidModifierFlags(LogicalKeyboardKey newKey, bool isDown) {
int result = 0;
final Set<LogicalKeyboardKey> pressed = RawKeyboard.instance.keysPressed;
if (isDown) {
pressed.add(newKey);
} else {
pressed.remove(newKey);
}
if (pressed.contains(LogicalKeyboardKey.shiftLeft)) {
result |= RawKeyEventDataAndroid.modifierLeftShift | RawKeyEventDataAndroid.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.shiftRight)) {
result |= RawKeyEventDataAndroid.modifierRightShift | RawKeyEventDataAndroid.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.metaLeft)) {
result |= RawKeyEventDataAndroid.modifierLeftMeta | RawKeyEventDataAndroid.modifierMeta;
}
if (pressed.contains(LogicalKeyboardKey.metaRight)) {
result |= RawKeyEventDataAndroid.modifierRightMeta | RawKeyEventDataAndroid.modifierMeta;
}
if (pressed.contains(LogicalKeyboardKey.controlLeft)) {
result |= RawKeyEventDataAndroid.modifierLeftControl | RawKeyEventDataAndroid.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.controlRight)) {
result |= RawKeyEventDataAndroid.modifierRightControl | RawKeyEventDataAndroid.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.altLeft)) {
result |= RawKeyEventDataAndroid.modifierLeftAlt | RawKeyEventDataAndroid.modifierAlt;
}
if (pressed.contains(LogicalKeyboardKey.altRight)) {
result |= RawKeyEventDataAndroid.modifierRightAlt | RawKeyEventDataAndroid.modifierAlt;
}
if (pressed.contains(LogicalKeyboardKey.fn)) {
result |= RawKeyEventDataAndroid.modifierFunction;
}
if (pressed.contains(LogicalKeyboardKey.scrollLock)) {
result |= RawKeyEventDataAndroid.modifierScrollLock;
}
if (pressed.contains(LogicalKeyboardKey.numLock)) {
result |= RawKeyEventDataAndroid.modifierNumLock;
}
if (pressed.contains(LogicalKeyboardKey.capsLock)) {
result |= RawKeyEventDataAndroid.modifierCapsLock;
}
return result;
}
static int _getGlfwModifierFlags(LogicalKeyboardKey newKey, bool isDown) {
int result = 0;
final Set<LogicalKeyboardKey> pressed = RawKeyboard.instance.keysPressed;
if (isDown) {
pressed.add(newKey);
} else {
pressed.remove(newKey);
}
if (pressed.contains(LogicalKeyboardKey.shiftLeft) || pressed.contains(LogicalKeyboardKey.shiftRight)) {
result |= GLFWKeyHelper.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.metaLeft) || pressed.contains(LogicalKeyboardKey.metaRight)) {
result |= GLFWKeyHelper.modifierMeta;
}
if (pressed.contains(LogicalKeyboardKey.controlLeft) || pressed.contains(LogicalKeyboardKey.controlRight)) {
result |= GLFWKeyHelper.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.altLeft) || pressed.contains(LogicalKeyboardKey.altRight)) {
result |= GLFWKeyHelper.modifierAlt;
}
if (pressed.contains(LogicalKeyboardKey.capsLock)) {
result |= GLFWKeyHelper.modifierCapsLock;
}
return result;
}
static int _getWindowsModifierFlags(LogicalKeyboardKey newKey, bool isDown) {
int result = 0;
final Set<LogicalKeyboardKey> pressed = RawKeyboard.instance.keysPressed;
if (isDown) {
pressed.add(newKey);
} else {
pressed.remove(newKey);
}
if (pressed.contains(LogicalKeyboardKey.shift)) {
result |= RawKeyEventDataWindows.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.shiftLeft)) {
result |= RawKeyEventDataWindows.modifierLeftShift;
}
if (pressed.contains(LogicalKeyboardKey.shiftRight)) {
result |= RawKeyEventDataWindows.modifierRightShift;
}
if (pressed.contains(LogicalKeyboardKey.metaLeft)) {
result |= RawKeyEventDataWindows.modifierLeftMeta;
}
if (pressed.contains(LogicalKeyboardKey.metaRight)) {
result |= RawKeyEventDataWindows.modifierRightMeta;
}
if (pressed.contains(LogicalKeyboardKey.control)) {
result |= RawKeyEventDataWindows.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.controlLeft)) {
result |= RawKeyEventDataWindows.modifierLeftControl;
}
if (pressed.contains(LogicalKeyboardKey.controlRight)) {
result |= RawKeyEventDataWindows.modifierRightControl;
}
if (pressed.contains(LogicalKeyboardKey.alt)) {
result |= RawKeyEventDataWindows.modifierAlt;
}
if (pressed.contains(LogicalKeyboardKey.altLeft)) {
result |= RawKeyEventDataWindows.modifierLeftAlt;
}
if (pressed.contains(LogicalKeyboardKey.altRight)) {
result |= RawKeyEventDataWindows.modifierRightAlt;
}
if (pressed.contains(LogicalKeyboardKey.capsLock)) {
result |= RawKeyEventDataWindows.modifierCaps;
}
if (pressed.contains(LogicalKeyboardKey.numLock)) {
result |= RawKeyEventDataWindows.modifierNumLock;
}
if (pressed.contains(LogicalKeyboardKey.scrollLock)) {
result |= RawKeyEventDataWindows.modifierScrollLock;
}
return result;
}
static int _getFuchsiaModifierFlags(LogicalKeyboardKey newKey, bool isDown) {
int result = 0;
final Set<LogicalKeyboardKey> pressed = RawKeyboard.instance.keysPressed;
if (isDown) {
pressed.add(newKey);
} else {
pressed.remove(newKey);
}
if (pressed.contains(LogicalKeyboardKey.shiftLeft)) {
result |= RawKeyEventDataFuchsia.modifierLeftShift;
}
if (pressed.contains(LogicalKeyboardKey.shiftRight)) {
result |= RawKeyEventDataFuchsia.modifierRightShift;
}
if (pressed.contains(LogicalKeyboardKey.metaLeft)) {
result |= RawKeyEventDataFuchsia.modifierLeftMeta;
}
if (pressed.contains(LogicalKeyboardKey.metaRight)) {
result |= RawKeyEventDataFuchsia.modifierRightMeta;
}
if (pressed.contains(LogicalKeyboardKey.controlLeft)) {
result |= RawKeyEventDataFuchsia.modifierLeftControl;
}
if (pressed.contains(LogicalKeyboardKey.controlRight)) {
result |= RawKeyEventDataFuchsia.modifierRightControl;
}
if (pressed.contains(LogicalKeyboardKey.altLeft)) {
result |= RawKeyEventDataFuchsia.modifierLeftAlt;
}
if (pressed.contains(LogicalKeyboardKey.altRight)) {
result |= RawKeyEventDataFuchsia.modifierRightAlt;
}
if (pressed.contains(LogicalKeyboardKey.capsLock)) {
result |= RawKeyEventDataFuchsia.modifierCapsLock;
}
return result;
}
static int _getWebModifierFlags(LogicalKeyboardKey newKey, bool isDown) {
int result = 0;
final Set<LogicalKeyboardKey> pressed = RawKeyboard.instance.keysPressed;
if (isDown) {
pressed.add(newKey);
} else {
pressed.remove(newKey);
}
if (pressed.contains(LogicalKeyboardKey.shiftLeft)) {
result |= RawKeyEventDataWeb.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.shiftRight)) {
result |= RawKeyEventDataWeb.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.metaLeft)) {
result |= RawKeyEventDataWeb.modifierMeta;
}
if (pressed.contains(LogicalKeyboardKey.metaRight)) {
result |= RawKeyEventDataWeb.modifierMeta;
}
if (pressed.contains(LogicalKeyboardKey.controlLeft)) {
result |= RawKeyEventDataWeb.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.controlRight)) {
result |= RawKeyEventDataWeb.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.altLeft)) {
result |= RawKeyEventDataWeb.modifierAlt;
}
if (pressed.contains(LogicalKeyboardKey.altRight)) {
result |= RawKeyEventDataWeb.modifierAlt;
}
if (pressed.contains(LogicalKeyboardKey.capsLock)) {
result |= RawKeyEventDataWeb.modifierCapsLock;
}
if (pressed.contains(LogicalKeyboardKey.numLock)) {
result |= RawKeyEventDataWeb.modifierNumLock;
}
if (pressed.contains(LogicalKeyboardKey.scrollLock)) {
result |= RawKeyEventDataWeb.modifierScrollLock;
}
return result;
}
static int _getMacOsModifierFlags(LogicalKeyboardKey newKey, bool isDown) {
int result = 0;
final Set<LogicalKeyboardKey> pressed = RawKeyboard.instance.keysPressed;
if (isDown) {
pressed.add(newKey);
} else {
pressed.remove(newKey);
}
if (pressed.contains(LogicalKeyboardKey.shiftLeft)) {
result |= RawKeyEventDataMacOs.modifierLeftShift | RawKeyEventDataMacOs.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.shiftRight)) {
result |= RawKeyEventDataMacOs.modifierRightShift | RawKeyEventDataMacOs.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.metaLeft)) {
result |= RawKeyEventDataMacOs.modifierLeftCommand | RawKeyEventDataMacOs.modifierCommand;
}
if (pressed.contains(LogicalKeyboardKey.metaRight)) {
result |= RawKeyEventDataMacOs.modifierRightCommand | RawKeyEventDataMacOs.modifierCommand;
}
if (pressed.contains(LogicalKeyboardKey.controlLeft)) {
result |= RawKeyEventDataMacOs.modifierLeftControl | RawKeyEventDataMacOs.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.controlRight)) {
result |= RawKeyEventDataMacOs.modifierRightControl | RawKeyEventDataMacOs.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.altLeft)) {
result |= RawKeyEventDataMacOs.modifierLeftOption | RawKeyEventDataMacOs.modifierOption;
}
if (pressed.contains(LogicalKeyboardKey.altRight)) {
result |= RawKeyEventDataMacOs.modifierRightOption | RawKeyEventDataMacOs.modifierOption;
}
final Set<LogicalKeyboardKey> functionKeys = <LogicalKeyboardKey>{
LogicalKeyboardKey.f1,
LogicalKeyboardKey.f2,
LogicalKeyboardKey.f3,
LogicalKeyboardKey.f4,
LogicalKeyboardKey.f5,
LogicalKeyboardKey.f6,
LogicalKeyboardKey.f7,
LogicalKeyboardKey.f8,
LogicalKeyboardKey.f9,
LogicalKeyboardKey.f10,
LogicalKeyboardKey.f11,
LogicalKeyboardKey.f12,
LogicalKeyboardKey.f13,
LogicalKeyboardKey.f14,
LogicalKeyboardKey.f15,
LogicalKeyboardKey.f16,
LogicalKeyboardKey.f17,
LogicalKeyboardKey.f18,
LogicalKeyboardKey.f19,
LogicalKeyboardKey.f20,
LogicalKeyboardKey.f21,
};
if (pressed.intersection(functionKeys).isNotEmpty) {
result |= RawKeyEventDataMacOs.modifierFunction;
}
if (pressed.intersection(kMacOsNumPadMap.values.toSet()).isNotEmpty) {
result |= RawKeyEventDataMacOs.modifierNumericPad;
}
if (pressed.contains(LogicalKeyboardKey.capsLock)) {
result |= RawKeyEventDataMacOs.modifierCapsLock;
}
return result;
}
static int _getIOSModifierFlags(LogicalKeyboardKey newKey, bool isDown) {
int result = 0;
final Set<LogicalKeyboardKey> pressed = RawKeyboard.instance.keysPressed;
if (isDown) {
pressed.add(newKey);
} else {
pressed.remove(newKey);
}
if (pressed.contains(LogicalKeyboardKey.shiftLeft)) {
result |= RawKeyEventDataIos.modifierLeftShift | RawKeyEventDataIos.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.shiftRight)) {
result |= RawKeyEventDataIos.modifierRightShift | RawKeyEventDataIos.modifierShift;
}
if (pressed.contains(LogicalKeyboardKey.metaLeft)) {
result |= RawKeyEventDataIos.modifierLeftCommand | RawKeyEventDataIos.modifierCommand;
}
if (pressed.contains(LogicalKeyboardKey.metaRight)) {
result |= RawKeyEventDataIos.modifierRightCommand | RawKeyEventDataIos.modifierCommand;
}
if (pressed.contains(LogicalKeyboardKey.controlLeft)) {
result |= RawKeyEventDataIos.modifierLeftControl | RawKeyEventDataIos.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.controlRight)) {
result |= RawKeyEventDataIos.modifierRightControl | RawKeyEventDataIos.modifierControl;
}
if (pressed.contains(LogicalKeyboardKey.altLeft)) {
result |= RawKeyEventDataIos.modifierLeftOption | RawKeyEventDataIos.modifierOption;
}
if (pressed.contains(LogicalKeyboardKey.altRight)) {
result |= RawKeyEventDataIos.modifierRightOption | RawKeyEventDataIos.modifierOption;
}
final Set<LogicalKeyboardKey> functionKeys = <LogicalKeyboardKey>{
LogicalKeyboardKey.f1,
LogicalKeyboardKey.f2,
LogicalKeyboardKey.f3,
LogicalKeyboardKey.f4,
LogicalKeyboardKey.f5,
LogicalKeyboardKey.f6,
LogicalKeyboardKey.f7,
LogicalKeyboardKey.f8,
LogicalKeyboardKey.f9,
LogicalKeyboardKey.f10,
LogicalKeyboardKey.f11,
LogicalKeyboardKey.f12,
LogicalKeyboardKey.f13,
LogicalKeyboardKey.f14,
LogicalKeyboardKey.f15,
LogicalKeyboardKey.f16,
LogicalKeyboardKey.f17,
LogicalKeyboardKey.f18,
LogicalKeyboardKey.f19,
LogicalKeyboardKey.f20,
LogicalKeyboardKey.f21,
};
if (pressed.intersection(functionKeys).isNotEmpty) {
result |= RawKeyEventDataIos.modifierFunction;
}
if (pressed.intersection(kMacOsNumPadMap.values.toSet()).isNotEmpty) {
result |= RawKeyEventDataIos.modifierNumericPad;
}
if (pressed.contains(LogicalKeyboardKey.capsLock)) {
result |= RawKeyEventDataIos.modifierCapsLock;
}
return result;
}
static Future<bool> _simulateKeyEventByRawEvent(ValueGetter<Map<String, dynamic>> buildKeyData) async {
return TestAsyncUtils.guard<bool>(() async {
final Completer<bool> result = Completer<bool>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(buildKeyData()),
(ByteData? data) {
if (data == null) {
result.complete(false);
return;
}
final Map<String, Object?> decoded = SystemChannels.keyEvent.codec.decodeMessage(data)! as Map<String, dynamic>;
result.complete(decoded['handled']! as bool);
}
);
return result.future;
});
}
static final Map<String, PhysicalKeyboardKey> _debugNameToPhysicalKey = (() {
final Map<String, PhysicalKeyboardKey> result = <String, PhysicalKeyboardKey>{};
for (final PhysicalKeyboardKey key in PhysicalKeyboardKey.knownPhysicalKeys) {
final String? debugName = key.debugName;
if (debugName != null) {
result[debugName] = key;
}
}
return result;
})();
static PhysicalKeyboardKey _findPhysicalKey(LogicalKeyboardKey key) {
final PhysicalKeyboardKey? result = _debugNameToPhysicalKey[key.debugName];
assert(result != null, 'Physical key for $key not found in known physical keys');
return result!;
}
static const KeyDataTransitMode _defaultTransitMode = KeyDataTransitMode.keyDataThenRawKeyData;
// The simulation transit mode for [simulateKeyDownEvent], [simulateKeyUpEvent],
// and [simulateKeyRepeatEvent].
//
// Simulation transit mode is the mode that simulated key events are constructed
// and delivered. For detailed introduction, see [KeyDataTransitMode] and
// its values.
//
// The `_transitMode` defaults to [KeyDataTransitMode.keyDataThenRawKeyData], and can
// be overridden with [debugKeyEventSimulatorTransitModeOverride]. In widget tests, it
// is often set with [KeySimulationModeVariant].
static KeyDataTransitMode get _transitMode {
KeyDataTransitMode? result;
assert(() {
result = debugKeyEventSimulatorTransitModeOverride;
return true;
}());
return result ?? _defaultTransitMode;
}
/// Returns the transit mode that simulated key events are constructed
/// and delivered. For detailed introduction, see [KeyDataTransitMode]
/// and its values.
@visibleForTesting
static KeyDataTransitMode get transitMode => _transitMode;
static String get _defaultPlatform => kIsWeb ? 'web' : defaultTargetPlatform.name.toLowerCase();
/// Simulates sending a hardware key down event.
///
/// This only simulates key presses coming from a physical keyboard, not from a
/// soft keyboard.
///
/// Specify `platform` as one of the platforms allowed in
/// [Platform.operatingSystem] to make the event appear to be from that type of
/// system. Defaults to "web" on web, and the operating system name based on
/// [defaultTargetPlatform] everywhere else.
///
/// Keys that are down when the test completes are cleared after each test.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// * [simulateKeyUpEvent] to simulate the corresponding key up event.
static Future<bool> simulateKeyDownEvent(
LogicalKeyboardKey key, {
String? platform,
PhysicalKeyboardKey? physicalKey,
String? character,
}) async {
Future<bool> simulateByRawEvent() {
return _simulateKeyEventByRawEvent(() {
platform ??= _defaultPlatform;
return getKeyData(key, platform: platform!, physicalKey: physicalKey, character: character);
});
}
switch (_transitMode) {
case KeyDataTransitMode.rawKeyData:
return simulateByRawEvent();
case KeyDataTransitMode.keyDataThenRawKeyData:
final LogicalKeyboardKey logicalKey = _getKeySynonym(key);
final bool resultByKeyEvent = ServicesBinding.instance.keyEventManager.handleKeyData(
ui.KeyData(
type: ui.KeyEventType.down,
physical: (physicalKey ?? _findPhysicalKey(logicalKey)).usbHidUsage,
logical: logicalKey.keyId,
timeStamp: Duration.zero,
character: character ?? _keyLabel(key),
synthesized: false,
),
);
return (await simulateByRawEvent()) || resultByKeyEvent;
}
}
/// Simulates sending a hardware key up event through the system channel.
///
/// This only simulates key presses coming from a physical keyboard, not from a
/// soft keyboard.
///
/// Specify `platform` as one of the platforms allowed in
/// [Platform.operatingSystem] to make the event appear to be from that type of
/// system. Defaults to "web" on web, and the operating system name based on
/// [defaultTargetPlatform] everywhere else.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// * [simulateKeyDownEvent] to simulate the corresponding key down event.
static Future<bool> simulateKeyUpEvent(
LogicalKeyboardKey key, {
String? platform,
PhysicalKeyboardKey? physicalKey,
}) async {
Future<bool> simulateByRawEvent() {
return _simulateKeyEventByRawEvent(() {
platform ??= _defaultPlatform;
return getKeyData(key, platform: platform!, isDown: false, physicalKey: physicalKey);
});
}
switch (_transitMode) {
case KeyDataTransitMode.rawKeyData:
return simulateByRawEvent();
case KeyDataTransitMode.keyDataThenRawKeyData:
final LogicalKeyboardKey logicalKey = _getKeySynonym(key);
final bool resultByKeyEvent = ServicesBinding.instance.keyEventManager.handleKeyData(
ui.KeyData(
type: ui.KeyEventType.up,
physical: (physicalKey ?? _findPhysicalKey(logicalKey)).usbHidUsage,
logical: logicalKey.keyId,
timeStamp: Duration.zero,
character: null,
synthesized: false,
),
);
return (await simulateByRawEvent()) || resultByKeyEvent;
}
}
/// Simulates sending a hardware key repeat event through the system channel.
///
/// This only simulates key presses coming from a physical keyboard, not from a
/// soft keyboard.
///
/// Specify `platform` as one of the platforms allowed in
/// [Platform.operatingSystem] to make the event appear to be from that type of
/// system. Defaults to "web" on web, and the operating system name based on
/// [defaultTargetPlatform] everywhere else.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// * [simulateKeyDownEvent] to simulate the corresponding key down event.
static Future<bool> simulateKeyRepeatEvent(
LogicalKeyboardKey key, {
String? platform,
PhysicalKeyboardKey? physicalKey,
String? character,
}) async {
Future<bool> simulateByRawEvent() {
return _simulateKeyEventByRawEvent(() {
platform ??= _defaultPlatform;
return getKeyData(key, platform: platform!, physicalKey: physicalKey, character: character);
});
}
switch (_transitMode) {
case KeyDataTransitMode.rawKeyData:
return simulateByRawEvent();
case KeyDataTransitMode.keyDataThenRawKeyData:
final LogicalKeyboardKey logicalKey = _getKeySynonym(key);
final bool resultByKeyEvent = ServicesBinding.instance.keyEventManager.handleKeyData(
ui.KeyData(
type: ui.KeyEventType.repeat,
physical: (physicalKey ?? _findPhysicalKey(logicalKey)).usbHidUsage,
logical: logicalKey.keyId,
timeStamp: Duration.zero,
character: character ?? _keyLabel(key),
synthesized: false,
),
);
return (await simulateByRawEvent()) || resultByKeyEvent;
}
}
}
/// Simulates sending a hardware key down event through the system channel.
///
/// It is intended for use in writing tests.
///
/// This only simulates key presses coming from a physical keyboard, not from a
/// soft keyboard, and it can only simulate keys that appear in the key maps
/// such as [kAndroidToLogicalKey], [kMacOsToPhysicalKey], etc.
///
/// Specify `platform` as one of the platforms allowed in
/// [Platform.operatingSystem] to make the event appear to be from that type of
/// system. Defaults to "web" on web, and the operating system name based on
/// [defaultTargetPlatform] everywhere else.
///
/// Keys that are down when the test completes are cleared after each test.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// * [simulateKeyUpEvent] and [simulateKeyRepeatEvent] to simulate the
/// corresponding key up and repeat event.
Future<bool> simulateKeyDownEvent(
LogicalKeyboardKey key, {
String? platform,
PhysicalKeyboardKey? physicalKey,
String? character,
}) async {
final bool handled = await KeyEventSimulator.simulateKeyDownEvent(key, platform: platform, physicalKey: physicalKey, character: character);
final ServicesBinding binding = ServicesBinding.instance;
if (!handled && binding is TestWidgetsFlutterBinding) {
await binding.testTextInput.handleKeyDownEvent(key);
}
return handled;
}
/// Simulates sending a hardware key up event through the system channel.
///
/// It is intended for use in writing tests.
///
/// This only simulates key presses coming from a physical keyboard, not from a
/// soft keyboard, and it can only simulate keys that appear in the key maps
/// such as [kAndroidToLogicalKey], [kMacOsToPhysicalKey], etc.
///
/// Specify `platform` as one of the platforms allowed in
/// [Platform.operatingSystem] to make the event appear to be from that type of
/// system. Defaults to "web" on web, and the operating system name based on
/// [defaultTargetPlatform] everywhere else.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// * [simulateKeyDownEvent] and [simulateKeyRepeatEvent] to simulate the
/// corresponding key down and repeat event.
Future<bool> simulateKeyUpEvent(
LogicalKeyboardKey key, {
String? platform,
PhysicalKeyboardKey? physicalKey,
}) async {
final bool handled = await KeyEventSimulator.simulateKeyUpEvent(key, platform: platform, physicalKey: physicalKey);
final ServicesBinding binding = ServicesBinding.instance;
if (!handled && binding is TestWidgetsFlutterBinding) {
await binding.testTextInput.handleKeyUpEvent(key);
}
return handled;
}
/// Simulates sending a hardware key repeat event through the system channel.
///
/// This only simulates key presses coming from a physical keyboard, not from a
/// soft keyboard.
///
/// Specify `platform` as one of the platforms allowed in
/// [Platform.operatingSystem] to make the event appear to be from that type of
/// system. Defaults to "web" on web, and the operating system name based on
/// [defaultTargetPlatform] everywhere else.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// - [simulateKeyDownEvent] and [simulateKeyUpEvent] to simulate the
/// corresponding key down and up event.
Future<bool> simulateKeyRepeatEvent(
LogicalKeyboardKey key, {
String? platform,
PhysicalKeyboardKey? physicalKey,
String? character,
}) {
return KeyEventSimulator.simulateKeyRepeatEvent(key, platform: platform, physicalKey: physicalKey, character: character);
}
/// A [TestVariant] that runs tests with transit modes set to different values
/// of [KeyDataTransitMode].
@Deprecated(
'No longer supported. Transit mode is always key data only. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
class KeySimulatorTransitModeVariant extends TestVariant<KeyDataTransitMode> {
/// Creates a [KeySimulatorTransitModeVariant] that tests the given [values].
@Deprecated(
'No longer supported. Transit mode is always key data only. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
const KeySimulatorTransitModeVariant(this.values);
/// Creates a [KeySimulatorTransitModeVariant] for each value option of
/// [KeyDataTransitMode].
@Deprecated(
'No longer supported. Transit mode is always key data only. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
KeySimulatorTransitModeVariant.all()
: this(KeyDataTransitMode.values.toSet());
/// Creates a [KeySimulatorTransitModeVariant] that only contains
/// [KeyDataTransitMode.keyDataThenRawKeyData].
@Deprecated(
'No longer supported. Transit mode is always key data only. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
KeySimulatorTransitModeVariant.keyDataThenRawKeyData()
: this(<KeyDataTransitMode>{KeyDataTransitMode.keyDataThenRawKeyData});
/// Creates a [KeySimulatorTransitModeVariant] that only contains
/// [KeyDataTransitMode.rawKeyData].
@Deprecated(
'No longer supported. Transit mode is always key data only. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
KeySimulatorTransitModeVariant.rawKeyData()
: this(<KeyDataTransitMode>{KeyDataTransitMode.rawKeyData});
@override
final Set<KeyDataTransitMode> values;
@override
String describeValue(KeyDataTransitMode value) {
switch (value) {
case KeyDataTransitMode.rawKeyData:
return 'RawKeyEvent';
case KeyDataTransitMode.keyDataThenRawKeyData:
return 'ui.KeyData then RawKeyEvent';
}
}
@override
Future<KeyDataTransitMode?> setUp(KeyDataTransitMode value) async {
final KeyDataTransitMode? previousSetting = debugKeyEventSimulatorTransitModeOverride;
debugKeyEventSimulatorTransitModeOverride = value;
return previousSetting;
}
@override
Future<void> tearDown(KeyDataTransitMode value, KeyDataTransitMode? memento) async {
// ignore: invalid_use_of_visible_for_testing_member
RawKeyboard.instance.clearKeysPressed();
// ignore: invalid_use_of_visible_for_testing_member
HardwareKeyboard.instance.clearState();
// ignore: invalid_use_of_visible_for_testing_member
ServicesBinding.instance.keyEventManager.clearState();
debugKeyEventSimulatorTransitModeOverride = memento;
}
}
| flutter/packages/flutter_test/lib/src/event_simulation.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/event_simulation.dart",
"repo_id": "flutter",
"token_count": 13885
} | 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/foundation.dart';
import 'package:stack_trace/stack_trace.dart' as stack_trace;
import 'package:test_api/scaffolding.dart' as test_package;
/// Signature for the [reportTestException] callback.
typedef TestExceptionReporter = void Function(FlutterErrorDetails details, String testDescription);
/// A function that is called by the test framework when an unexpected error
/// occurred during a test.
///
/// This function is responsible for reporting the error to the user such that
/// the user can easily diagnose what failed when inspecting the test results.
/// It is also responsible for reporting the error to the test framework itself
/// in order to cause the test to fail.
///
/// This function is pluggable to handle the cases where tests are run in
/// contexts _other_ than via `flutter test`.
TestExceptionReporter get reportTestException => _reportTestException;
TestExceptionReporter _reportTestException = _defaultTestExceptionReporter;
set reportTestException(TestExceptionReporter handler) {
_reportTestException = handler;
}
void _defaultTestExceptionReporter(FlutterErrorDetails errorDetails, String testDescription) {
FlutterError.dumpErrorToConsole(errorDetails, forceReport: true);
// test_package.registerException actually just calls the current zone's error handler (that
// is to say, _parentZone's handleUncaughtError function). FakeAsync doesn't add one of those,
// but the test package does, that's how the test package tracks errors. So really we could
// get the same effect here by calling that error handler directly or indeed just throwing.
// However, we call registerException because that's the semantically correct thing...
String additional = '';
if (testDescription.isNotEmpty) {
additional = '\nThe test description was: $testDescription';
}
test_package.registerException('Test failed. See exception logs above.$additional', _emptyStackTrace);
}
final StackTrace _emptyStackTrace = stack_trace.Chain(const <stack_trace.Trace>[]);
| flutter/packages/flutter_test/lib/src/test_exception_reporter.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/test_exception_reporter.dart",
"repo_id": "flutter",
"token_count": 545
} | 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 'dart:io';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Initializes httpOverrides and testTextInput', () async {
expect(HttpOverrides.current, null);
final TestWidgetsFlutterBinding binding = CustomBindings();
expect(WidgetsBinding.instance, isA<CustomBindings>());
expect(binding.testTextInput.isRegistered, false);
expect(HttpOverrides.current, null);
});
}
class CustomBindings extends AutomatedTestWidgetsFlutterBinding {
@override
bool get overrideHttpClient => false;
@override
bool get registerTestTextInput => false;
}
| flutter/packages/flutter_test/test/integration_bindings_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/integration_bindings_test.dart",
"repo_id": "flutter",
"token_count": 251
} | 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/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('stack manipulation: reportExpectCall', () {
try {
expect(false, isTrue);
fail('unexpectedly did not throw');
} catch (e, stack) {
final List<DiagnosticsNode> information = <DiagnosticsNode>[];
expect(reportExpectCall(stack, information), 4);
final TextTreeRenderer renderer = TextTreeRenderer();
final List<String> lines = information.map((DiagnosticsNode node) => renderer.render(node).trimRight()).join('\n').split('\n');
expect(lines[0], 'This was caught by the test expectation on the following line:');
expect(lines[1], matches(r'^ .*stack_manipulation_test.dart line [0-9]+$'));
}
final List<DiagnosticsNode> information = <DiagnosticsNode>[];
expect(reportExpectCall(StackTrace.current, information), 0);
expect(information, isEmpty);
});
}
| flutter/packages/flutter_test/test/stack_manipulation_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/stack_manipulation_test.dart",
"repo_id": "flutter",
"token_count": 376
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'utils/memory_leak_tests.dart';
class _TestExecution {
_TestExecution(
{required this.settings, required this.settingName, required this.test});
final String settingName;
final LeakTesting settings;
final LeakTestCase test;
String get name => '${test.name}, $settingName';
}
final List<_TestExecution> _testExecutions = <_TestExecution>[];
void main() {
LeakTesting.collectedLeaksReporter = _verifyLeaks;
LeakTesting.enable();
LeakTesting.settings = LeakTesting.settings
.withTrackedAll()
.withTracked(allNotDisposed: true, experimentalAllNotGCed: true)
.withIgnored(
createdByTestHelpers: true,
testHelperExceptions: <RegExp>[
RegExp(RegExp.escape(memoryLeakTestsFilePath()))
],
);
for (final LeakTestCase test in memoryLeakTests) {
for (final MapEntry<String,
LeakTesting Function(LeakTesting settings)> settingsCase
in leakTestingSettingsCases.entries) {
final LeakTesting settings = settingsCase.value(LeakTesting.settings);
if (settings.leakDiagnosticConfig.collectRetainingPathForNotGCed) {
// Retaining path requires vm to be started, so skipping.
continue;
}
final _TestExecution execution = _TestExecution(
settingName: settingsCase.key, test: test, settings: settings);
_testExecutions.add(execution);
testWidgets(execution.name, experimentalLeakTesting: settings,
(WidgetTester tester) async {
await test.body((Widget widget, [Duration? duration]) => tester.pumpWidget(widget, duration: duration), tester.runAsync);
});
}
}
}
void _verifyLeaks(Leaks leaks) {
for (final _TestExecution execution in _testExecutions) {
final Leaks testLeaks = leaks.byPhase[execution.name] ?? Leaks.empty();
execution.test.verifyLeaks(testLeaks, execution.settings,
testDescription: execution.name);
}
}
| flutter/packages/flutter_test/test/widget_tester_leaks_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/widget_tester_leaks_test.dart",
"repo_id": "flutter",
"token_count": 787
} | 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.
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('test', (WidgetTester tester) async {
// This call will be unchanged
// Changes made in https://github.com/flutter/flutter/pull/89952
}, timeout: Timeout(Duration(hours: 1)));
testWidgets('test', (WidgetTester tester) async {
// The `timeout` will remain unchanged, but `initialTimeout` will be removed
// Changes made in https://github.com/flutter/flutter/pull/89952
},
timeout: Timeout(Duration(minutes: 45)),
initialTimeout: Duration(minutes: 30));
testWidgets('test', (WidgetTester tester) async {
// initialTimeout will be wrapped in a Timeout and changed to `timeout`
// Changes made in https://github.com/flutter/flutter/pull/89952
}, initialTimeout: Duration(seconds: 30));
}
| flutter/packages/flutter_test/test_fixes/flutter_test/widget_tester.dart/0 | {
"file_path": "flutter/packages/flutter_test/test_fixes/flutter_test/widget_tester.dart",
"repo_id": "flutter",
"token_count": 301
} | 725 |
# package:test configuration
# https://github.com/dart-lang/test/blob/master/pkgs/test/doc/configuration.md
# Some of our tests take an absurdly long time to run, and on some
# hosts they can take even longer due to the host suddenly being
# overloaded. For this reason, we set the test timeout to
# significantly more than it would be by default, and we never set the
# timeouts in the tests themselves.
#
# For the `test/general.shard` specifically, the `dev/bots/test.dart` script
# overrides this, reducing it to only 2000ms. Unit tests must run fast!
timeout: 15m
tags:
# This tag tells the test framework to not shuffle the test order according to
# the --test-randomize-ordering-seed for the suites that have this tag.
no-shuffle:
allow_test_randomization: false
| flutter/packages/flutter_tools/dart_test.yaml/0 | {
"file_path": "flutter/packages/flutter_tools/dart_test.yaml",
"repo_id": "flutter",
"token_count": 222
} | 726 |
/* groovylint-disable LineLength, UnnecessaryGString, UnnecessaryGetter */
// 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 com.android.build.OutputFile
import groovy.json.JsonGenerator
import groovy.xml.QName
import java.nio.file.Paths
import org.apache.tools.ant.taskdefs.condition.Os
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.Task
import org.gradle.api.file.CopySpec
import org.gradle.api.file.FileCollection
import org.gradle.api.logging.LogLevel
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFiles
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.bundling.Jar
import org.gradle.internal.os.OperatingSystem
/**
* For apps only. Provides the flutter extension used in the app-level Gradle
* build file (app/build.gradle or app/build.gradle.kts).
*
* The versions specified here should match the values in
* packages/flutter_tools/lib/src/android/gradle_utils.dart, so when bumping,
* make sure to update the versions specified there.
*
* Learn more about extensions in Gradle:
* * https://docs.gradle.org/8.0.2/userguide/custom_plugins.html#sec:getting_input_from_the_build
*/
class FlutterExtension {
/** Sets the compileSdkVersion used by default in Flutter app projects. */
public final int compileSdkVersion = 34
/** Sets the minSdkVersion used by default in Flutter app projects. */
public final int minSdkVersion = 21
/**
* Sets the targetSdkVersion used by default in Flutter app projects.
* targetSdkVersion should always be the latest available stable version.
*
* See https://developer.android.com/guide/topics/manifest/uses-sdk-element.
*/
public final int targetSdkVersion = 34
/**
* Sets the ndkVersion used by default in Flutter app projects.
* Chosen as default version of the AGP version below as found in
* https://developer.android.com/studio/projects/install-ndk#default-ndk-per-agp.
*/
public final String ndkVersion = "23.1.7779620"
/**
* Specifies the relative directory to the Flutter project directory.
* In an app project, this is ../.. since the app's Gradle build file is under android/app.
*/
String source = "../.."
/** Allows to override the target file. Otherwise, the target is lib/main.dart. */
String target
/** The versionCode that was read from app's local.properties. */
public String flutterVersionCode = null
/** The versionName that was read from app's local.properties. */
public String flutterVersionName = null
/** Returns flutterVersionCode as an integer with error handling. */
public Integer versionCode() {
if (flutterVersionCode == null) {
throw new GradleException("flutterVersionCode must not be null.")
}
if (!flutterVersionCode.isNumber()) {
throw new GradleException("flutterVersionCode must be an integer.")
}
return flutterVersionCode.toInteger()
}
/** Returns flutterVersionName with error handling. */
public String versionName() {
if (flutterVersionName == null) {
throw new GradleException("flutterVersionName must not be null.")
}
return flutterVersionName
}
}
// This buildscript block supplies dependencies for this file's own import
// declarations above. It exists solely for compatibility with projects that
// have not migrated to declaratively apply the Flutter Gradle Plugin;
// for those that have, FGP's `build.gradle.kts` takes care of this.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
// When bumping, also update:
// * ndkVersion in FlutterExtension in packages/flutter_tools/gradle/src/main/groovy/flutter.groovy
// * AGP version in the buildscript block in packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts
// * AGP version constants in packages/flutter_tools/lib/src/android/gradle_utils.dart
// * AGP version in dependencies block in packages/flutter_tools/gradle/build.gradle.kts
classpath("com.android.tools.build:gradle:7.3.0")
}
}
/**
* Some apps don't set default compile options.
* Apps can change these values in the app-level Gradle build file
* (android/app/build.gradle or android/app/build.gradle.kts).
* This just ensures that default values are set.
*/
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
apply plugin: FlutterPlugin
class FlutterPlugin implements Plugin<Project> {
private static final String DEFAULT_MAVEN_HOST = "https://storage.googleapis.com"
/** The platforms that can be passed to the `--Ptarget-platform` flag. */
private static final String PLATFORM_ARM32 = "android-arm"
private static final String PLATFORM_ARM64 = "android-arm64"
private static final String PLATFORM_X86 = "android-x86"
private static final String PLATFORM_X86_64 = "android-x64"
/** The ABI architectures supported by Flutter. */
private static final String ARCH_ARM32 = "armeabi-v7a"
private static final String ARCH_ARM64 = "arm64-v8a"
private static final String ARCH_X86 = "x86"
private static final String ARCH_X86_64 = "x86_64"
private static final String INTERMEDIATES_DIR = "intermediates"
/** Maps platforms to ABI architectures. */
private static final Map PLATFORM_ARCH_MAP = [
(PLATFORM_ARM32) : ARCH_ARM32,
(PLATFORM_ARM64) : ARCH_ARM64,
(PLATFORM_X86) : ARCH_X86,
(PLATFORM_X86_64) : ARCH_X86_64,
]
/**
* The version code that gives each ABI a value.
* For each APK variant, use the following versions to override the version of the Universal APK.
* Otherwise, the Play Store will complain that the APK variants have the same version.
*/
private static final Map<String, Integer> ABI_VERSION = [
(ARCH_ARM32) : 1,
(ARCH_ARM64) : 2,
(ARCH_X86) : 3,
(ARCH_X86_64) : 4,
]
/** When split is enabled, multiple APKs are generated per each ABI. */
private static final List DEFAULT_PLATFORMS = [
PLATFORM_ARM32,
PLATFORM_ARM64,
PLATFORM_X86_64,
]
private final static String propLocalEngineRepo = "local-engine-repo"
private final static String propProcessResourcesProvider = "processResourcesProvider"
/**
* The name prefix for flutter builds. This is used to identify gradle tasks
* where we expect the flutter tool to provide any error output, and skip the
* standard Gradle error output in the FlutterEventLogger. If you change this,
* be sure to change any instances of this string in symbols in the code below
* to match.
*/
static final String FLUTTER_BUILD_PREFIX = "flutterBuild"
private Project project
private File flutterRoot
private File flutterExecutable
private String localEngine
private String localEngineHost
private String localEngineSrcPath
private Properties localProperties
private String engineVersion
private String engineRealm
private List<Map<String, Object>> pluginList
private List<Map<String, Object>> pluginDependencies
/**
* Flutter Docs Website URLs for help messages.
*/
private final String kWebsiteDeploymentAndroidBuildConfig = "https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration"
@Override
void apply(Project project) {
this.project = project
Project rootProject = project.rootProject
if (isFlutterAppProject()) {
rootProject.tasks.register("generateLockfiles") {
rootProject.subprojects.each { subproject ->
String gradlew = (OperatingSystem.current().isWindows()) ?
"${rootProject.projectDir}/gradlew.bat" : "${rootProject.projectDir}/gradlew"
rootProject.exec {
workingDir(rootProject.projectDir)
executable(gradlew)
args(":${subproject.name}:dependencies", "--write-locks")
}
}
}
}
String flutterRootPath = resolveProperty("flutter.sdk", System.env.FLUTTER_ROOT)
if (flutterRootPath == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file or with a FLUTTER_ROOT environment variable.")
}
flutterRoot = project.file(flutterRootPath)
if (!flutterRoot.isDirectory()) {
throw new GradleException("flutter.sdk must point to the Flutter SDK directory")
}
engineVersion = useLocalEngine()
? "+" // Match any version since there's only one.
: "1.0.0-" + Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.version").toFile().text.trim()
engineRealm = Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.realm").toFile().text.trim()
if (engineRealm) {
engineRealm = engineRealm + "/"
}
// Configure the Maven repository.
String hostedRepository = System.env.FLUTTER_STORAGE_BASE_URL ?: DEFAULT_MAVEN_HOST
String repository = useLocalEngine()
? project.property(propLocalEngineRepo)
: "$hostedRepository/${engineRealm}download.flutter.io"
rootProject.allprojects {
repositories {
maven {
url(repository)
}
}
}
// Load shared gradle functions
project.apply from: Paths.get(flutterRoot.absolutePath, "packages", "flutter_tools", "gradle", "src", "main", "groovy", "native_plugin_loader.groovy")
FlutterExtension extension = project.extensions.create("flutter", FlutterExtension)
Properties localProperties = new Properties()
File localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader("UTF-8") { reader ->
localProperties.load(reader)
}
}
Object flutterVersionCode = localProperties.getProperty("flutter.versionCode")
if (flutterVersionCode == null) {
flutterVersionCode = "1"
}
extension.flutterVersionCode = flutterVersionCode
Object flutterVersionName = localProperties.getProperty("flutter.versionName")
if (flutterVersionName == null) {
flutterVersionName = "1.0"
}
extension.flutterVersionName = flutterVersionName
this.addFlutterTasks(project)
// By default, assembling APKs generates fat APKs if multiple platforms are passed.
// Configuring split per ABI allows to generate separate APKs for each abi.
// This is a noop when building a bundle.
if (shouldSplitPerAbi()) {
project.android {
splits {
abi {
// Enables building multiple APKs per ABI.
enable(true)
// Resets the list of ABIs that Gradle should create APKs for to none.
reset()
// Specifies that we do not want to also generate a universal APK that includes all ABIs.
universalApk(false)
}
}
}
}
final String propDeferredComponentNames = "deferred-component-names"
if (project.hasProperty(propDeferredComponentNames)) {
String[] componentNames = project.property(propDeferredComponentNames).split(",").collect {":${it}"}
project.android {
dynamicFeatures = componentNames
}
}
getTargetPlatforms().each { targetArch ->
String abiValue = PLATFORM_ARCH_MAP[targetArch]
project.android {
if (shouldSplitPerAbi()) {
splits {
abi {
include(abiValue)
}
}
}
}
}
String flutterExecutableName = Os.isFamily(Os.FAMILY_WINDOWS) ? "flutter.bat" : "flutter"
flutterExecutable = Paths.get(flutterRoot.absolutePath, "bin", flutterExecutableName).toFile()
// Validate that the provided Gradle, Java, AGP, and KGP versions are all within our
// supported range.
// TODO(gmackall) Dependency version checking is currently implemented as an additional
// Gradle plugin because we can't import it from Groovy code. As part of the Groovy
// -> Kotlin migration, we should remove this complexity and perform the checks inside
// of the main Flutter Gradle Plugin.
// See https://github.com/flutter/flutter/issues/121541#issuecomment-1920363687.
final Boolean shouldSkipDependencyChecks = project.hasProperty("skipDependencyChecks") && project.getProperty("skipDependencyChecks");
if (!shouldSkipDependencyChecks) {
try {
final String dependencyCheckerPluginPath = Paths.get(flutterRoot.absolutePath,
"packages", "flutter_tools", "gradle", "src", "main", "kotlin",
"dependency_version_checker.gradle.kts")
project.apply from: dependencyCheckerPluginPath
} catch (Exception ignored) {
project.logger.error("Warning: Flutter was unable to detect project Gradle, Java, " +
"AGP, and KGP versions. Skipping dependency version checking. Error was: "
+ ignored)
}
}
// Use Kotlin DSL to handle baseApplicationName logic due to Groovy dynamic dispatch bug.
project.apply from: Paths.get(flutterRoot.absolutePath, "packages", "flutter_tools", "gradle", "src", "main", "kotlin", "flutter.gradle.kts")
String flutterProguardRules = Paths.get(flutterRoot.absolutePath, "packages", "flutter_tools",
"gradle", "flutter_proguard_rules.pro")
project.android.buildTypes {
// Add profile build type.
profile {
initWith(debug)
if (it.hasProperty("matchingFallbacks")) {
matchingFallbacks = ["debug", "release"]
}
}
// TODO(garyq): Shrinking is only false for multi apk split aot builds, where shrinking is not allowed yet.
// This limitation has been removed experimentally in gradle plugin version 4.2, so we can remove
// this check when we upgrade to 4.2+ gradle. Currently, deferred components apps may see
// increased app size due to this.
if (shouldShrinkResources(project)) {
release {
// Enables code shrinking, obfuscation, and optimization for only
// your project's release build type.
minifyEnabled(true)
// Enables resource shrinking, which is performed by the Android Gradle plugin.
// The resource shrinker can't be used for libraries.
shrinkResources(isBuiltAsApp(project))
// Fallback to `android/app/proguard-rules.pro`.
// This way, custom Proguard rules can be configured as needed.
proguardFiles(project.android.getDefaultProguardFile("proguard-android.txt"), flutterProguardRules, "proguard-rules.pro")
}
}
}
if (useLocalEngine()) {
// This is required to pass the local engine to flutter build aot.
String engineOutPath = project.property("local-engine-out")
File engineOut = project.file(engineOutPath)
if (!engineOut.isDirectory()) {
throw new GradleException("local-engine-out must point to a local engine build")
}
localEngine = engineOut.name
localEngineSrcPath = engineOut.parentFile.parent
String engineHostOutPath = project.property("local-engine-host-out")
File engineHostOut = project.file(engineHostOutPath)
if (!engineHostOut.isDirectory()) {
throw new GradleException("local-engine-host-out must point to a local engine host build")
}
localEngineHost = engineHostOut.name
}
project.android.buildTypes.all(this.&addFlutterDependencies)
}
private static Boolean shouldShrinkResources(Project project) {
final String propShrink = "shrink"
if (project.hasProperty(propShrink)) {
return project.property(propShrink).toBoolean()
}
return true
}
private static String toCamelCase(List<String> parts) {
if (parts.empty) {
return ""
}
return "${parts[0]}${parts[1..-1].collect { it.capitalize() }.join('')}"
}
private static Properties readPropertiesIfExist(File propertiesFile) {
Properties result = new Properties()
if (propertiesFile.exists()) {
propertiesFile.withReader("UTF-8") { reader -> result.load(reader) }
}
return result
}
private static Boolean isBuiltAsApp(Project project) {
// Projects are built as applications when the they use the `com.android.application`
// plugin.
return project.plugins.hasPlugin("com.android.application")
}
private static void addApiDependencies(Project project, String variantName, Object dependency, Closure config = null) {
String configuration
// `compile` dependencies are now `api` dependencies.
if (project.getConfigurations().findByName("api")) {
configuration = "${variantName}Api"
} else {
configuration = "${variantName}Compile"
}
project.dependencies.add(configuration, dependency, config)
}
// Add a task that can be called on flutter projects that prints the Java version used in Gradle.
//
// Format of the output of this task can be used in debugging what version of Java Gradle is using.
// Not recommended for use in time sensitive commands like `flutter run` or `flutter build` as
// Gradle is slower than we want. Particularly in light of https://github.com/flutter/flutter/issues/119196.
private static void addTaskForJavaVersion(Project project) {
// Warning: the name of this task is used by other code. Change with caution.
project.tasks.register("javaVersion") {
description "Print the current java version used by gradle. "
"see: https://docs.gradle.org/current/javadoc/org/gradle/api/JavaVersion.html"
doLast {
println(JavaVersion.current())
}
}
}
// Add a task that can be called on Flutter projects that prints the available build variants
// in Gradle.
//
// This task prints variants in this format:
//
// BuildVariant: debug
// BuildVariant: release
// BuildVariant: profile
//
// Format of the output of this task is used by `AndroidProject.getBuildVariants`.
private static void addTaskForPrintBuildVariants(Project project) {
// Warning: The name of this task is used by `AndroidProject.getBuildVariants`.
project.tasks.register("printBuildVariants") {
description "Prints out all build variants for this Android project"
doLast {
project.android.applicationVariants.all { variant ->
println "BuildVariant: ${variant.name}"
}
}
}
}
// Add a task that can be called on Flutter projects that outputs app link related project
// settings into a json file.
//
// See https://developer.android.com/training/app-links/ for more information about app link.
//
// The json will be saved in path stored in outputPath parameter.
//
// An example json:
// {
// applicationId: "com.example.app",
// deeplinks: [
// {"scheme":"http", "host":"example.com", "path":".*"},
// {"scheme":"https","host":"example.com","path":".*"}
// ]
// }
//
// The output file is parsed and used by devtool.
private static void addTasksForOutputsAppLinkSettings(Project project) {
project.android.applicationVariants.all { variant ->
// Warning: The name of this task is used by AndroidBuilder.outputsAppLinkSettings
project.tasks.register("output${variant.name.capitalize()}AppLinkSettings") {
description "stores app links settings for the given build variant of this Android project into a json file."
variant.outputs.all { output ->
// Deeplinks are defined in AndroidManifest.xml and is only available after
// `processResourcesProvider`.
Object processResources = output.hasProperty(propProcessResourcesProvider) ?
output.processResourcesProvider.get() : output.processResources
dependsOn processResources.name
}
doLast {
AppLinkSettings appLinkSettings = new AppLinkSettings()
appLinkSettings.applicationId = variant.applicationId
appLinkSettings.deeplinks = [] as Set<Deeplink>
variant.outputs.all { output ->
Object processResources = output.hasProperty(propProcessResourcesProvider) ?
output.processResourcesProvider.get() : output.processResources
def manifest = new XmlParser().parse(processResources.manifestFile)
manifest.application.activity.each { activity ->
activity."meta-data".each { metadata ->
boolean nameAttribute = metadata.attributes().find { it.key == 'android:name' }?.value == 'flutter_deeplinking_enabled'
boolean valueAttribute = metadata.attributes().find { it.key == 'android:value' }?.value == 'true'
if (nameAttribute && valueAttribute) {
appLinkSettings.deeplinkingFlagEnabled = true
}
}
activity."intent-filter".each { appLinkIntent ->
// Print out the host attributes in data tags.
Set<String> schemes = [] as Set<String>
Set<String> hosts = [] as Set<String>
Set<String> paths = [] as Set<String>
IntentFilterCheck intentFilterCheck = new IntentFilterCheck()
if (appLinkIntent.attributes().find { it.key == 'android:autoVerify' }?.value == 'true') {
intentFilterCheck.hasAutoVerify = true
}
appLinkIntent.'action'.each { action ->
if (action.attributes().find { it.key == 'android:name' }?.value == 'android.intent.action.VIEW') {
intentFilterCheck.hasActionView = true
}
}
appLinkIntent.'category'.each { category ->
if (category.attributes().find { it.key == 'android:name' }?.value == 'android.intent.category.DEFAULT') {
intentFilterCheck.hasDefaultCategory = true
}
if (category.attributes().find { it.key == 'android:name' }?.value == 'android.intent.category.BROWSABLE') {
intentFilterCheck.hasBrowsableCategory = true
}
}
appLinkIntent.data.each { data ->
data.attributes().each { entry ->
if (entry.key instanceof QName) {
switch (entry.key.getLocalPart()) {
case "scheme":
schemes.add(entry.value)
break
case "host":
hosts.add(entry.value)
break
case "pathAdvancedPattern":
case "pathPattern":
case "path":
paths.add(entry.value)
break
case "pathPrefix":
paths.add("${entry.value}.*")
break
case "pathSuffix":
paths.add(".*${entry.value}")
break
}
}
}
}
schemes.each { scheme ->
hosts.each { host ->
if (!paths) {
appLinkSettings.deeplinks.add(new Deeplink(scheme: scheme, host: host, path: ".*", intentFilterCheck: intentFilterCheck))
} else {
paths.each { path ->
appLinkSettings.deeplinks.add(new Deeplink(scheme: scheme, host: host, path: path, intentFilterCheck: intentFilterCheck))
}
}
}
}
}
}
}
JsonGenerator generator = new JsonGenerator.Options().build()
new File(project.getProperty("outputPath")).write(generator.toJson(appLinkSettings))
}
}
}
}
/**
* Returns a Flutter build mode suitable for the specified Android buildType.
*
* The BuildType DSL type is not public, and is therefore omitted from the signature.
*
* @return "debug", "profile", or "release" (fall-back).
*/
private static String buildModeFor(buildType) {
if (buildType.name == "profile") {
return "profile"
} else if (buildType.debuggable) {
return "debug"
}
return "release"
}
/**
* Adds the dependencies required by the Flutter project.
* This includes:
* 1. The embedding
* 2. libflutter.so
*/
void addFlutterDependencies(buildType) {
String flutterBuildMode = buildModeFor(buildType)
if (!supportsBuildMode(flutterBuildMode)) {
return
}
// The embedding is set as an API dependency in a Flutter plugin.
// Therefore, don't make the app project depend on the embedding if there are Flutter
// plugins.
// This prevents duplicated classes when using custom build types. That is, a custom build
// type like profile is used, and the plugin and app projects have API dependencies on the
// embedding.
if (!isFlutterAppProject() || getPluginList(project).size() == 0) {
addApiDependencies(project, buildType.name,
"io.flutter:flutter_embedding_$flutterBuildMode:$engineVersion")
}
List<String> platforms = getTargetPlatforms().collect()
// Debug mode includes x86 and x64, which are commonly used in emulators.
if (flutterBuildMode == "debug" && !useLocalEngine()) {
platforms.add("android-x86")
platforms.add("android-x64")
}
platforms.each { platform ->
String arch = PLATFORM_ARCH_MAP[platform].replace("-", "_")
// Add the `libflutter.so` dependency.
addApiDependencies(project, buildType.name,
"io.flutter:${arch}_$flutterBuildMode:$engineVersion")
}
}
/**
* Configures the Flutter plugin dependencies.
*
* The plugins are added to pubspec.yaml. Then, upon running `flutter pub get`,
* the tool generates a `.flutter-plugins-dependencies` file, which contains a map to each plugin location.
* Finally, the project's `settings.gradle` loads each plugin's android directory as a subproject.
*/
private void configurePlugins(Project project) {
configureLegacyPluginEachProjects(project)
getPluginList(project).each(this.&configurePluginProject)
getPluginList(project).each(this.&configurePluginDependencies)
}
// TODO(54566, 48918): Can remove once the issues are resolved.
// This means all references to `.flutter-plugins` are then removed and
// apps only depend exclusively on the `plugins` property in `.flutter-plugins-dependencies`.
/**
* Workaround to load non-native plugins for developers who may still use an
* old `settings.gradle` which includes all the plugins from the
* `.flutter-plugins` file, even if not made for Android.
* The settings.gradle then:
* 1) tries to add the android plugin implementation, which does not
* exist at all, but is also not included successfully
* (which does not throw an error and therefore isn't a problem), or
* 2) includes the plugin successfully as a valid android plugin
* directory exists, even if the surrounding flutter package does not
* support the android platform (see e.g. apple_maps_flutter: 1.0.1).
* So as it's included successfully it expects to be added as API.
* This is only possible by taking all plugins into account, which
* only appear on the `dependencyGraph` and in the `.flutter-plugins` file.
* So in summary the plugins are currently selected from the `dependencyGraph`
* and filtered then with the [doesSupportAndroidPlatform] method instead of
* just using the `plugins.android` list.
*/
private void configureLegacyPluginEachProjects(Project project) {
try {
if (!settingsGradleFile(project).text.contains("'.flutter-plugins'")) {
return
}
} catch (FileNotFoundException ignored) {
throw new GradleException("settings.gradle/settings.gradle.kts does not exist: ${settingsGradleFile(project).absolutePath}")
}
List<Map<String, Object>> deps = getPluginDependencies(project)
List<String> plugins = getPluginList(project).collect { it.name as String }
deps.removeIf { plugins.contains(it.name) }
deps.each {
Project pluginProject = project.rootProject.findProject(":${it.name}")
if (pluginProject == null) {
// Plugin was not included in `settings.gradle`, but is listed in `.flutter-plugins`.
project.logger.error("Plugin project :${it.name} listed, but not found. Please fix your settings.gradle/settings.gradle.kts.")
} else if (doesSupportAndroidPlatform(pluginProject.projectDir.parentFile.path as String)) {
// Plugin has a functioning `android` folder and is included successfully, although it's not supported.
// It must be configured nonetheless, to not throw an "Unresolved reference" exception.
configurePluginProject(it)
/* groovylint-disable-next-line EmptyElseBlock */
} else {
// Plugin has no or an empty `android` folder. No action required.
}
}
}
// TODO(54566): Can remove this function and its call sites once resolved.
/**
* Returns `true` if the given path contains an `android` directory
* containing a `build.gradle` or `build.gradle.kts` file.
*/
private Boolean doesSupportAndroidPlatform(String path) {
File buildGradle = new File(path, 'android' + File.separator + 'build.gradle')
File buildGradleKts = new File(path, 'android' + File.separator + 'build.gradle.kts')
if (buildGradle.exists() && buildGradleKts.exists()) {
project.logger.error(
"Both build.gradle and build.gradle.kts exist, so " +
"build.gradle.kts is ignored. This is likely a mistake."
)
}
return buildGradle.exists() || buildGradleKts.exists()
}
/**
* Returns the Gradle settings script for the build. When both Groovy and
* Kotlin variants exist, then Groovy (settings.gradle) is preferred over
* Kotlin (settings.gradle.kts). This is the same behavior as Gradle 8.5.
*/
private File settingsGradleFile(Project project) {
File settingsGradle = new File(project.projectDir.parentFile, "settings.gradle")
File settingsGradleKts = new File(project.projectDir.parentFile, "settings.gradle.kts")
if (settingsGradle.exists() && settingsGradleKts.exists()) {
project.logger.error(
"Both settings.gradle and settings.gradle.kts exist, so " +
"settings.gradle.kts is ignored. This is likely a mistake."
)
}
return settingsGradle.exists() ? settingsGradle : settingsGradleKts
}
/** Adds the plugin project dependency to the app project. */
private void configurePluginProject(Map<String, Object> pluginObject) {
assert(pluginObject.name instanceof String)
Project pluginProject = project.rootProject.findProject(":${pluginObject.name}")
if (pluginProject == null) {
return
}
// Add plugin dependency to the app project.
project.dependencies {
api(pluginProject)
}
Closure addEmbeddingDependencyToPlugin = { buildType ->
String flutterBuildMode = buildModeFor(buildType)
// In AGP 3.5, the embedding must be added as an API implementation,
// so java8 features are desugared against the runtime classpath.
// For more, see https://github.com/flutter/flutter/issues/40126
if (!supportsBuildMode(flutterBuildMode)) {
return
}
if (!pluginProject.hasProperty("android")) {
return
}
// Copy build types from the app to the plugin.
// This allows to build apps with plugins and custom build types or flavors.
pluginProject.android.buildTypes {
"${buildType.name}" {}
}
// The embedding is API dependency of the plugin, so the AGP is able to desugar
// default method implementations when the interface is implemented by a plugin.
//
// See https://issuetracker.google.com/139821726, and
// https://github.com/flutter/flutter/issues/72185 for more details.
addApiDependencies(
pluginProject,
buildType.name,
"io.flutter:flutter_embedding_$flutterBuildMode:$engineVersion"
)
}
// Wait until the Android plugin loaded.
pluginProject.afterEvaluate {
// Checks if there is a mismatch between the plugin compileSdkVersion and the project compileSdkVersion.
if (pluginProject.android.compileSdkVersion > project.android.compileSdkVersion) {
project.logger.quiet("Warning: The plugin ${pluginObject.name} requires Android SDK version ${getCompileSdkFromProject(pluginProject)} or higher.")
project.logger.quiet("For more information about build configuration, see $kWebsiteDeploymentAndroidBuildConfig.")
}
project.android.buildTypes.all(addEmbeddingDependencyToPlugin)
}
}
/**
* Compares semantic versions ignoring labels.
*
* If the versions are equal (ignoring labels), returns one of the two strings arbitrarily.
*
* If minor or patch are omitted (non-conformant to semantic versioning), they are considered zero.
* If the provided versions in both are equal, the longest version string is returned.
* For example, "2.8.0" vs "2.8" will always consider "2.8.0" to be the most recent version.
* TODO: Remove this or compareVersionStrings. This does not handle strings like "8.6-rc-2".
*/
static String mostRecentSemanticVersion(String version1, String version2) {
List version1Tokenized = version1.tokenize(".")
List version2Tokenized = version2.tokenize(".")
int version1numTokens = version1Tokenized.size()
int version2numTokens = version2Tokenized.size()
int minNumTokens = Math.min(version1numTokens, version2numTokens)
for (int i = 0; i < minNumTokens; i++) {
int num1 = version1Tokenized[i].toInteger()
int num2 = version2Tokenized[i].toInteger()
if (num1 > num2) {
return version1
}
if (num2 > num1) {
return version2
}
}
if (version1numTokens > version2numTokens) {
return version1
}
return version2
}
/** Prints error message and fix for any plugin compileSdkVersion or ndkVersion that are higher than the project. */
private void detectLowCompileSdkVersionOrNdkVersion() {
project.afterEvaluate {
// Default to int max if using a preview version to skip the sdk check.
int projectCompileSdkVersion = Integer.MAX_VALUE
// Stable versions use ints, legacy preview uses string.
if (getCompileSdkFromProject(project).isInteger()) {
projectCompileSdkVersion = getCompileSdkFromProject(project) as int
}
int maxPluginCompileSdkVersion = projectCompileSdkVersion
String ndkVersionIfUnspecified = "21.1.6352462" /* The default for AGP 4.1.0 used in old templates. */
String projectNdkVersion = project.android.ndkVersion ?: ndkVersionIfUnspecified
String maxPluginNdkVersion = projectNdkVersion
int numProcessedPlugins = getPluginList(project).size()
getPluginList(project).each { pluginObject ->
assert(pluginObject.name instanceof String)
Project pluginProject = project.rootProject.findProject(":${pluginObject.name}")
if (pluginProject == null) {
return
}
pluginProject.afterEvaluate {
// Default to int min if using a preview version to skip the sdk check.
int pluginCompileSdkVersion = Integer.MIN_VALUE
// Stable versions use ints, legacy preview uses string.
if (getCompileSdkFromProject(pluginProject).isInteger()) {
pluginCompileSdkVersion = getCompileSdkFromProject(pluginProject) as int
}
maxPluginCompileSdkVersion = Math.max(pluginCompileSdkVersion, maxPluginCompileSdkVersion)
String pluginNdkVersion = pluginProject.android.ndkVersion ?: ndkVersionIfUnspecified
maxPluginNdkVersion = mostRecentSemanticVersion(pluginNdkVersion, maxPluginNdkVersion)
numProcessedPlugins--
if (numProcessedPlugins == 0) {
if (maxPluginCompileSdkVersion > projectCompileSdkVersion) {
project.logger.error("One or more plugins require a higher Android SDK version.\nFix this issue by adding the following to ${project.projectDir}${File.separator}build.gradle:\nandroid {\n compileSdkVersion ${maxPluginCompileSdkVersion}\n ...\n}\n")
}
if (maxPluginNdkVersion != projectNdkVersion) {
project.logger.error("One or more plugins require a higher Android NDK version.\nFix this issue by adding the following to ${project.projectDir}${File.separator}build.gradle:\nandroid {\n ndkVersion \"${maxPluginNdkVersion}\"\n ...\n}\n")
}
}
}
}
}
}
/**
* Returns the portion of the compileSdkVersion string that corresponds to either the numeric
* or string version.
*/
private String getCompileSdkFromProject(Project gradleProject) {
return gradleProject.android.compileSdkVersion.substring(8)
}
/**
* Add the dependencies on other plugin projects to the plugin project.
* A plugin A can depend on plugin B. As a result, this dependency must be surfaced by
* making the Gradle plugin project A depend on the Gradle plugin project B.
*/
private void configurePluginDependencies(Map<String, Object> pluginObject) {
assert(pluginObject.name instanceof String)
Project pluginProject = project.rootProject.findProject(":${pluginObject.name}")
if (pluginProject == null) {
return
}
def dependencies = pluginObject.dependencies
assert(dependencies instanceof List<String>)
dependencies.each { pluginDependencyName ->
if (pluginDependencyName.empty) {
return
}
Project dependencyProject = project.rootProject.findProject(":$pluginDependencyName")
if (dependencyProject == null) {
return
}
// Wait for the Android plugin to load and add the dependency to the plugin project.
pluginProject.afterEvaluate {
pluginProject.dependencies {
implementation(dependencyProject)
}
}
}
}
/**
* Gets the list of plugins (as map) that support the Android platform.
*
* The map value contains either the plugins `name` (String),
* its `path` (String), or its `dependencies` (List<String>).
* See [NativePluginLoader#getPlugins] in packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy
*/
private List<Map<String, Object>> getPluginList(Project project) {
if (pluginList == null) {
pluginList = project.ext.nativePluginLoader.getPlugins(getFlutterSourceDirectory())
}
return pluginList
}
// TODO(54566, 48918): Remove in favor of [getPluginList] only, see also
// https://github.com/flutter/flutter/blob/1c90ed8b64d9ed8ce2431afad8bc6e6d9acc4556/packages/flutter_tools/lib/src/flutter_plugins.dart#L212
/** Gets the plugins dependencies from `.flutter-plugins-dependencies`. */
private List<Map<String, Object>> getPluginDependencies(Project project) {
if (pluginDependencies == null) {
Map meta = project.ext.nativePluginLoader.getDependenciesMetadata(getFlutterSourceDirectory())
if (meta == null) {
pluginDependencies = []
} else {
assert(meta.dependencyGraph instanceof List<Map>)
pluginDependencies = meta.dependencyGraph as List<Map<String, Object>>
}
}
return pluginDependencies
}
private String resolveProperty(String name, String defaultValue) {
if (localProperties == null) {
localProperties = readPropertiesIfExist(new File(project.projectDir.parentFile, "local.properties"))
}
String result
if (project.hasProperty(name)) {
result = project.property(name)
}
if (result == null) {
result = localProperties.getProperty(name)
}
if (result == null) {
result = defaultValue
}
return result
}
private List<String> getTargetPlatforms() {
final String propTargetPlatform = "target-platform"
if (!project.hasProperty(propTargetPlatform)) {
return DEFAULT_PLATFORMS
}
return project.property(propTargetPlatform).split(",").collect {
if (!PLATFORM_ARCH_MAP[it]) {
throw new GradleException("Invalid platform: $it.")
}
return it
}
}
private Boolean shouldSplitPerAbi() {
return project.findProperty("split-per-abi")?.toBoolean() ?: false
}
private Boolean useLocalEngine() {
return project.hasProperty(propLocalEngineRepo)
}
private Boolean isVerbose() {
return project.findProperty("verbose")?.toBoolean() ?: false
}
/** Whether to build the debug app in "fast-start" mode. */
private Boolean isFastStart() {
return project.findProperty("fast-start")?.toBoolean() ?: false
}
/**
* Returns true if the build mode is supported by the current call to Gradle.
* This only relevant when using a local engine. Because the engine
* is built for a specific mode, the call to Gradle must match that mode.
*/
private Boolean supportsBuildMode(String flutterBuildMode) {
if (!useLocalEngine()) {
return true
}
final String propLocalEngineBuildMode = "local-engine-build-mode"
assert(project.hasProperty(propLocalEngineBuildMode))
// Don't configure dependencies for a build mode that the local engine
// doesn't support.
return project.property(propLocalEngineBuildMode) == flutterBuildMode
}
/**
* Gets the directory that contains the Flutter source code.
* This is the directory containing the `android/` directory.
*/
private File getFlutterSourceDirectory() {
if (project.flutter.source == null) {
throw new GradleException("Must provide Flutter source directory")
}
return project.file(project.flutter.source)
}
/**
* Gets the target file. This is typically `lib/main.dart`.
*/
private String getFlutterTarget() {
String target = project.flutter.target
if (target == null) {
target = "lib/main.dart"
}
final String propTarget = "target"
if (project.hasProperty(propTarget)) {
target = project.property(propTarget)
}
return target
}
// TODO: Remove this AGP hack. https://github.com/flutter/flutter/issues/109560
/**
* In AGP 4.0, the Android linter task depends on the JAR tasks that generate `libapp.so`.
* When building APKs, this causes an issue where building release requires the debug JAR,
* but Gradle won't build debug.
*
* To workaround this issue, only configure the JAR task that is required given the task
* from the command line.
*
* The AGP team said that this issue is fixed in Gradle 7.0, which isn't released at the
* time of adding this code. Once released, this can be removed. However, after updating to
* AGP/Gradle 7.2.0/7.5, removing this hack still causes build failures. Further
* investigation necessary to remove this.
*
* Tested cases:
* * `./gradlew assembleRelease`
* * `./gradlew app:assembleRelease.`
* * `./gradlew assemble{flavorName}Release`
* * `./gradlew app:assemble{flavorName}Release`
* * `./gradlew assemble.`
* * `./gradlew app:assemble.`
* * `./gradlew bundle.`
* * `./gradlew bundleRelease.`
* * `./gradlew app:bundleRelease.`
*
* Related issues:
* https://issuetracker.google.com/issues/158060799
* https://issuetracker.google.com/issues/158753935
*/
private boolean shouldConfigureFlutterTask(Task assembleTask) {
List<String> cliTasksNames = project.gradle.startParameter.taskNames
if (cliTasksNames.size() != 1 || !cliTasksNames.first().contains("assemble")) {
return true
}
String taskName = cliTasksNames.first().split(":").last()
if (taskName == "assemble") {
return true
}
if (taskName == assembleTask.name) {
return true
}
if (taskName.endsWith("Release") && assembleTask.name.endsWith("Release")) {
return true
}
if (taskName.endsWith("Debug") && assembleTask.name.endsWith("Debug")) {
return true
}
if (taskName.endsWith("Profile") && assembleTask.name.endsWith("Profile")) {
return true
}
return false
}
private Task getAssembleTask(variant) {
// `assemble` became `assembleProvider` in AGP 3.3.0.
return variant.hasProperty("assembleProvider") ? variant.assembleProvider.get() : variant.assemble
}
private boolean isFlutterAppProject() {
return project.android.hasProperty("applicationVariants")
}
private void addFlutterTasks(Project project) {
if (project.state.failure) {
return
}
String[] fileSystemRootsValue = null
final String propFileSystemRoots = "filesystem-roots"
if (project.hasProperty(propFileSystemRoots)) {
fileSystemRootsValue = project.property(propFileSystemRoots).split("\\|")
}
String fileSystemSchemeValue = null
final String propFileSystemScheme = "filesystem-scheme"
if (project.hasProperty(propFileSystemScheme)) {
fileSystemSchemeValue = project.property(propFileSystemScheme)
}
Boolean trackWidgetCreationValue = true
final String propTrackWidgetCreation = "track-widget-creation"
if (project.hasProperty(propTrackWidgetCreation)) {
trackWidgetCreationValue = project.property(propTrackWidgetCreation).toBoolean()
}
String frontendServerStarterPathValue = null
final String propFrontendServerStarterPath = "frontend-server-starter-path"
if (project.hasProperty(propFrontendServerStarterPath)) {
frontendServerStarterPathValue = project.property(propFrontendServerStarterPath)
}
String extraFrontEndOptionsValue = null
final String propExtraFrontEndOptions = "extra-front-end-options"
if (project.hasProperty(propExtraFrontEndOptions)) {
extraFrontEndOptionsValue = project.property(propExtraFrontEndOptions)
}
String extraGenSnapshotOptionsValue = null
final String propExtraGenSnapshotOptions = "extra-gen-snapshot-options"
if (project.hasProperty(propExtraGenSnapshotOptions)) {
extraGenSnapshotOptionsValue = project.property(propExtraGenSnapshotOptions)
}
String splitDebugInfoValue = null
final String propSplitDebugInfo = "split-debug-info"
if (project.hasProperty(propSplitDebugInfo)) {
splitDebugInfoValue = project.property(propSplitDebugInfo)
}
Boolean dartObfuscationValue = false
final String propDartObfuscation = "dart-obfuscation"
if (project.hasProperty(propDartObfuscation)) {
dartObfuscationValue = project.property(propDartObfuscation).toBoolean()
}
Boolean treeShakeIconsOptionsValue = false
final String propTreeShakeIcons = "tree-shake-icons"
if (project.hasProperty(propTreeShakeIcons)) {
treeShakeIconsOptionsValue = project.property(propTreeShakeIcons).toBoolean()
}
String dartDefinesValue = null
final String propDartDefines = "dart-defines"
if (project.hasProperty(propDartDefines)) {
dartDefinesValue = project.property(propDartDefines)
}
String bundleSkSLPathValue
final String propBundleSkslPath = "bundle-sksl-path"
if (project.hasProperty(propBundleSkslPath)) {
bundleSkSLPathValue = project.property(propBundleSkslPath)
}
String performanceMeasurementFileValue
final String propPerformanceMesaurementFile = "performance-measurement-file"
if (project.hasProperty(propPerformanceMesaurementFile)) {
performanceMeasurementFileValue = project.property(propPerformanceMesaurementFile)
}
String codeSizeDirectoryValue
final String propCodeSizeDirectory = "code-size-directory"
if (project.hasProperty(propCodeSizeDirectory)) {
codeSizeDirectoryValue = project.property(propCodeSizeDirectory)
}
Boolean deferredComponentsValue = false
final String propDeferredComponents = "deferred-components"
if (project.hasProperty(propDeferredComponents)) {
deferredComponentsValue = project.property(propDeferredComponents).toBoolean()
}
Boolean validateDeferredComponentsValue = true
final String propValidateDeferredComponents = "validate-deferred-components"
if (project.hasProperty(propValidateDeferredComponents)) {
validateDeferredComponentsValue = project.property(propValidateDeferredComponents).toBoolean()
}
addTaskForJavaVersion(project)
if (isFlutterAppProject()) {
addTaskForPrintBuildVariants(project)
addTasksForOutputsAppLinkSettings(project)
}
List<String> targetPlatforms = getTargetPlatforms()
def addFlutterDeps = { variant ->
if (shouldSplitPerAbi()) {
variant.outputs.each { output ->
// Assigns the new version code to versionCodeOverride, which changes the version code
// for only the output APK, not for the variant itself. Skipping this step simply
// causes Gradle to use the value of variant.versionCode for the APK.
// For more, see https://developer.android.com/studio/build/configure-apk-splits
int abiVersionCode = ABI_VERSION.get(output.getFilter(OutputFile.ABI))
if (abiVersionCode != null) {
output.versionCodeOverride =
abiVersionCode * 1000 + variant.versionCode
}
}
}
// Build an AAR when this property is defined.
boolean isBuildingAar = project.hasProperty("is-plugin")
// In add to app scenarios, a Gradle project contains a `:flutter` and `:app` project.
// `:flutter` is used as a subproject when these tasks exists and the build isn't building an AAR.
Task packageAssets = project.tasks.findByPath(":flutter:package${variant.name.capitalize()}Assets")
Task cleanPackageAssets = project.tasks.findByPath(":flutter:cleanPackage${variant.name.capitalize()}Assets")
boolean isUsedAsSubproject = packageAssets && cleanPackageAssets && !isBuildingAar
String variantBuildMode = buildModeFor(variant.buildType)
String flavorValue = variant.getFlavorName()
String taskName = toCamelCase(["compile", FLUTTER_BUILD_PREFIX, variant.name])
// Be careful when configuring task below, Groovy has bizarre
// scoping rules: writing `verbose isVerbose()` means calling
// `isVerbose` on the task itself - which would return `verbose`
// original value. You either need to hoist the value
// into a separate variable `verbose verboseValue` or prefix with
// `this` (`verbose this.isVerbose()`).
FlutterTask compileTask = project.tasks.create(name: taskName, type: FlutterTask) {
flutterRoot(this.flutterRoot)
flutterExecutable(this.flutterExecutable)
buildMode(variantBuildMode)
minSdkVersion(variant.mergedFlavor.minSdkVersion.apiLevel)
localEngine(this.localEngine)
localEngineHost(this.localEngineHost)
localEngineSrcPath(this.localEngineSrcPath)
targetPath(getFlutterTarget())
verbose(this.isVerbose())
fastStart(this.isFastStart())
fileSystemRoots(fileSystemRootsValue)
fileSystemScheme(fileSystemSchemeValue)
trackWidgetCreation(trackWidgetCreationValue)
targetPlatformValues = targetPlatforms
sourceDir(getFlutterSourceDirectory())
intermediateDir(project.file("${project.buildDir}/$INTERMEDIATES_DIR/flutter/${variant.name}/"))
frontendServerStarterPath(frontendServerStarterPathValue)
extraFrontEndOptions(extraFrontEndOptionsValue)
extraGenSnapshotOptions(extraGenSnapshotOptionsValue)
splitDebugInfo(splitDebugInfoValue)
treeShakeIcons(treeShakeIconsOptionsValue)
dartObfuscation(dartObfuscationValue)
dartDefines(dartDefinesValue)
bundleSkSLPath(bundleSkSLPathValue)
performanceMeasurementFile(performanceMeasurementFileValue)
codeSizeDirectory(codeSizeDirectoryValue)
deferredComponents(deferredComponentsValue)
validateDeferredComponents(validateDeferredComponentsValue)
flavor(flavorValue)
}
File libJar = project.file("${project.buildDir}/$INTERMEDIATES_DIR/flutter/${variant.name}/libs.jar")
Task packJniLibsTask = project.tasks.create(name: "packJniLibs${FLUTTER_BUILD_PREFIX}${variant.name.capitalize()}", type: Jar) {
destinationDirectory = libJar.parentFile
archiveFileName = libJar.name
dependsOn compileTask
targetPlatforms.each { targetPlatform ->
String abi = PLATFORM_ARCH_MAP[targetPlatform]
from("${compileTask.intermediateDir}/${abi}") {
include "*.so"
// Move `app.so` to `lib/<abi>/libapp.so`
rename { String filename ->
return "lib/${abi}/lib${filename}"
}
}
// Copy the native assets created by build.dart and placed in build/native_assets by flutter assemble.
// The `$project.buildDir` is '.android/Flutter/build/' instead of 'build/'.
String buildDir = "${getFlutterSourceDirectory()}/build"
String nativeAssetsDir = "${buildDir}/native_assets/android/jniLibs/lib"
from("${nativeAssetsDir}/${abi}") {
include "*.so"
rename { String filename ->
return "lib/${abi}/${filename}"
}
}
}
}
addApiDependencies(project, variant.name, project.files {
packJniLibsTask
})
Task copyFlutterAssetsTask = project.tasks.create(
name: "copyFlutterAssets${variant.name.capitalize()}",
type: Copy,
) {
dependsOn(compileTask)
with(compileTask.assets)
String currentGradleVersion = project.getGradle().getGradleVersion()
// See https://docs.gradle.org/current/javadoc/org/gradle/api/file/ConfigurableFilePermissions.html
// See https://github.com/flutter/flutter/pull/50047
if (compareVersionStrings(currentGradleVersion, "8.3") >= 0) {
filePermissions {
user {
read = true
write = true
}
}
} else {
// See https://docs.gradle.org/8.2/dsl/org.gradle.api.tasks.Copy.html#org.gradle.api.tasks.Copy:fileMode
// See https://github.com/flutter/flutter/pull/50047
fileMode(0644)
}
if (isUsedAsSubproject) {
dependsOn(packageAssets)
dependsOn(cleanPackageAssets)
into(packageAssets.outputDir)
return
}
// `variant.mergeAssets` will be removed at the end of 2019.
def mergeAssets = variant.hasProperty("mergeAssetsProvider") ?
variant.mergeAssetsProvider.get() : variant.mergeAssets
dependsOn(mergeAssets)
dependsOn("clean${mergeAssets.name.capitalize()}")
mergeAssets.mustRunAfter("clean${mergeAssets.name.capitalize()}")
into(mergeAssets.outputDir)
}
if (!isUsedAsSubproject) {
def variantOutput = variant.outputs.first()
def processResources = variantOutput.hasProperty(propProcessResourcesProvider) ?
variantOutput.processResourcesProvider.get() : variantOutput.processResources
processResources.dependsOn(copyFlutterAssetsTask)
}
// The following tasks use the output of copyFlutterAssetsTask,
// so it's necessary to declare it as an dependency since Gradle 8.
// See https://docs.gradle.org/8.1/userguide/validation_problems.html#implicit_dependency.
def compressAssetsTask = project.tasks.findByName("compress${variant.name.capitalize()}Assets")
if (compressAssetsTask) {
compressAssetsTask.dependsOn(copyFlutterAssetsTask)
}
def bundleAarTask = project.tasks.findByName("bundle${variant.name.capitalize()}Aar")
if (bundleAarTask) {
bundleAarTask.dependsOn(copyFlutterAssetsTask)
}
return copyFlutterAssetsTask
} // end def addFlutterDeps
if (isFlutterAppProject()) {
project.android.applicationVariants.all { variant ->
Task assembleTask = getAssembleTask(variant)
if (!shouldConfigureFlutterTask(assembleTask)) {
return
}
Task copyFlutterAssetsTask = addFlutterDeps(variant)
def variantOutput = variant.outputs.first()
def processResources = variantOutput.hasProperty(propProcessResourcesProvider) ?
variantOutput.processResourcesProvider.get() : variantOutput.processResources
processResources.dependsOn(copyFlutterAssetsTask)
// Copy the output APKs into a known location, so `flutter run` or `flutter build apk`
// can discover them. By default, this is `<app-dir>/build/app/outputs/flutter-apk/<filename>.apk`.
//
// The filename consists of `app<-abi>?<-flavor-name>?-<build-mode>.apk`.
// Where:
// * `abi` can be `armeabi-v7a|arm64-v8a|x86|x86_64` only if the flag `split-per-abi` is set.
// * `flavor-name` is the flavor used to build the app in lower case if the assemble task is called.
// * `build-mode` can be `release|debug|profile`.
variant.outputs.all { output ->
assembleTask.doLast {
// `packageApplication` became `packageApplicationProvider` in AGP 3.3.0.
def outputDirectory = variant.hasProperty("packageApplicationProvider")
? variant.packageApplicationProvider.get().outputDirectory
: variant.packageApplication.outputDirectory
// `outputDirectory` is a `DirectoryProperty` in AGP 4.1.
String outputDirectoryStr = outputDirectory.metaClass.respondsTo(outputDirectory, "get")
? outputDirectory.get()
: outputDirectory
String filename = "app"
String abi = output.getFilter(OutputFile.ABI)
if (abi != null && !abi.isEmpty()) {
filename += "-${abi}"
}
if (variant.flavorName != null && !variant.flavorName.isEmpty()) {
filename += "-${variant.flavorName.toLowerCase()}"
}
filename += "-${buildModeFor(variant.buildType)}"
project.copy {
from new File("$outputDirectoryStr/${output.outputFileName}")
into new File("${project.buildDir}/outputs/flutter-apk")
rename {
return "${filename}.apk"
}
}
}
}
// Copy the native assets created by build.dart and placed here by flutter assemble.
String nativeAssetsDir = "${project.buildDir}/../native_assets/android/jniLibs/lib/"
project.android.sourceSets.main.jniLibs.srcDir(nativeAssetsDir)
}
configurePlugins(project)
detectLowCompileSdkVersionOrNdkVersion()
return
}
// Flutter host module project (Add-to-app).
String hostAppProjectName = project.rootProject.hasProperty("flutter.hostAppProjectName") ? project.rootProject.property("flutter.hostAppProjectName") : "app"
Project appProject = project.rootProject.findProject(":${hostAppProjectName}")
assert(appProject != null) : "Project :${hostAppProjectName} doesn't exist. To customize the host app project name, set `flutter.hostAppProjectName=<project-name>` in gradle.properties."
// Wait for the host app project configuration.
appProject.afterEvaluate {
assert(appProject.android != null)
project.android.libraryVariants.all { libraryVariant ->
Task copyFlutterAssetsTask
appProject.android.applicationVariants.all { appProjectVariant ->
Task appAssembleTask = getAssembleTask(appProjectVariant)
if (!shouldConfigureFlutterTask(appAssembleTask)) {
return
}
// Find a compatible application variant in the host app.
//
// For example, consider a host app that defines the following variants:
// | ----------------- | ----------------------------- |
// | Build Variant | Flutter Equivalent Variant |
// | ----------------- | ----------------------------- |
// | freeRelease | release |
// | freeDebug | debug |
// | freeDevelop | debug |
// | profile | profile |
// | ----------------- | ----------------------------- |
//
// This mapping is based on the following rules:
// 1. If the host app build variant name is `profile` then the equivalent
// Flutter variant is `profile`.
// 2. If the host app build variant is debuggable
// (e.g. `buildType.debuggable = true`), then the equivalent Flutter
// variant is `debug`.
// 3. Otherwise, the equivalent Flutter variant is `release`.
String variantBuildMode = buildModeFor(libraryVariant.buildType)
if (buildModeFor(appProjectVariant.buildType) != variantBuildMode) {
return
}
if (copyFlutterAssetsTask == null) {
copyFlutterAssetsTask = addFlutterDeps(libraryVariant)
}
Task mergeAssets = project
.tasks
.findByPath(":${hostAppProjectName}:merge${appProjectVariant.name.capitalize()}Assets")
assert(mergeAssets)
mergeAssets.dependsOn(copyFlutterAssetsTask)
}
}
}
configurePlugins(project)
detectLowCompileSdkVersionOrNdkVersion()
}
// compareTo implementation of version strings in the format of ints and periods
// Requires non null objects.
// Will not crash on RC candidate strings but considers all RC candidates the same version.
static int compareVersionStrings(String firstString, String secondString) {
List firstVersion = firstString.tokenize(".")
List secondVersion = secondString.tokenize(".")
int commonIndices = Math.min(firstVersion.size(), secondVersion.size())
for (int i = 0; i < commonIndices; i++) {
String firstAtIndex = firstVersion[i]
String secondAtIndex = secondVersion[i]
int firstInt = 0
int secondInt = 0
try {
if (firstAtIndex.contains("-")) {
// Strip any chars after "-". For example "8.6-rc-2"
firstAtIndex = firstAtIndex.substring(0, firstAtIndex.indexOf('-'))
}
firstInt = firstAtIndex.toInteger()
} catch (NumberFormatException nfe) {
println(nfe)
}
try {
if (firstAtIndex.contains("-")) {
// Strip any chars after "-". For example "8.6-rc-2"
secondAtIndex = secondAtIndex.substring(0, secondAtIndex.indexOf('-'))
}
secondInt = secondAtIndex.toInteger()
} catch (NumberFormatException nfe) {
println(nfe)
}
if (firstInt != secondInt) {
// <=> in groovy delegates to compareTo
return firstInt <=> secondInt
}
}
// If we got this far then all the common indices are identical, so whichever version is longer must be more recent
return firstVersion.size() <=> secondVersion.size()
}
}
class AppLinkSettings {
String applicationId
Set<Deeplink> deeplinks
boolean deeplinkingFlagEnabled
}
class IntentFilterCheck {
boolean hasAutoVerify
boolean hasActionView
boolean hasDefaultCategory
boolean hasBrowsableCategory
}
class Deeplink {
String scheme, host, path
IntentFilterCheck intentFilterCheck
boolean equals(o) {
if (o == null) {
throw new NullPointerException()
}
if (o.getClass() != getClass()) {
return false
}
return scheme == o.scheme &&
host == o.host &&
path == o.path
}
}
abstract class BaseFlutterTask extends DefaultTask {
@Internal
File flutterRoot
@Internal
File flutterExecutable
@Input
String buildMode
@Input
int minSdkVersion
@Optional @Input
String localEngine
@Optional @Input
String localEngineHost
@Optional @Input
String localEngineSrcPath
@Optional @Input
Boolean fastStart
@Input
String targetPath
@Optional @Input
Boolean verbose
@Optional @Input
String[] fileSystemRoots
@Optional @Input
String fileSystemScheme
@Input
Boolean trackWidgetCreation
@Optional @Input
List<String> targetPlatformValues
@Internal
File sourceDir
@Internal
File intermediateDir
@Optional @Input
String frontendServerStarterPath
@Optional @Input
String extraFrontEndOptions
@Optional @Input
String extraGenSnapshotOptions
@Optional @Input
String splitDebugInfo
@Optional @Input
Boolean treeShakeIcons
@Optional @Input
Boolean dartObfuscation
@Optional @Input
String dartDefines
@Optional @Input
String bundleSkSLPath
@Optional @Input
String codeSizeDirectory
@Optional @Input
String performanceMeasurementFile
@Optional @Input
Boolean deferredComponents
@Optional @Input
Boolean validateDeferredComponents
@Optional @Input
Boolean skipDependencyChecks
@Optional @Input
String flavor
@OutputFiles
FileCollection getDependenciesFiles() {
FileCollection depfiles = project.files()
// Includes all sources used in the flutter compilation.
depfiles += project.files("${intermediateDir}/flutter_build.d")
return depfiles
}
void buildBundle() {
if (!sourceDir.isDirectory()) {
throw new GradleException("Invalid Flutter source directory: ${sourceDir}")
}
intermediateDir.mkdirs()
// Compute the rule name for flutter assemble. To speed up builds that contain
// multiple ABIs, the target name is used to communicate which ones are required
// rather than the TargetPlatform. This allows multiple builds to share the same
// cache.
String[] ruleNames
if (buildMode == "debug") {
ruleNames = ["debug_android_application"]
} else if (deferredComponents) {
ruleNames = targetPlatformValues.collect { "android_aot_deferred_components_bundle_${buildMode}_$it" }
} else {
ruleNames = targetPlatformValues.collect { "android_aot_bundle_${buildMode}_$it" }
}
project.exec {
logging.captureStandardError(LogLevel.ERROR)
executable(flutterExecutable.absolutePath)
workingDir(sourceDir)
if (localEngine != null) {
args "--local-engine", localEngine
args "--local-engine-src-path", localEngineSrcPath
}
if (localEngineHost != null) {
args "--local-engine-host", localEngineHost
}
if (verbose) {
args "--verbose"
} else {
args "--quiet"
}
args("assemble")
args("--no-version-check")
args("--depfile", "${intermediateDir}/flutter_build.d")
args("--output", "${intermediateDir}")
if (performanceMeasurementFile != null) {
args("--performance-measurement-file=${performanceMeasurementFile}")
}
if (!fastStart || buildMode != "debug") {
args("-dTargetFile=${targetPath}")
} else {
args("-dTargetFile=${Paths.get(flutterRoot.absolutePath, "examples", "splash", "lib", "main.dart")}")
}
args("-dTargetPlatform=android")
args("-dBuildMode=${buildMode}")
if (trackWidgetCreation != null) {
args("-dTrackWidgetCreation=${trackWidgetCreation}")
}
if (splitDebugInfo != null) {
args("-dSplitDebugInfo=${splitDebugInfo}")
}
if (treeShakeIcons == true) {
args("-dTreeShakeIcons=true")
}
if (dartObfuscation == true) {
args("-dDartObfuscation=true")
}
if (dartDefines != null) {
args("--DartDefines=${dartDefines}")
}
if (bundleSkSLPath != null) {
args("-dBundleSkSLPath=${bundleSkSLPath}")
}
if (codeSizeDirectory != null) {
args("-dCodeSizeDirectory=${codeSizeDirectory}")
}
if (flavor != null) {
args("-dFlavor=${flavor}")
}
if (extraGenSnapshotOptions != null) {
args("--ExtraGenSnapshotOptions=${extraGenSnapshotOptions}")
}
if (frontendServerStarterPath != null) {
args("-dFrontendServerStarterPath=${frontendServerStarterPath}")
}
if (extraFrontEndOptions != null) {
args("--ExtraFrontEndOptions=${extraFrontEndOptions}")
}
args("-dAndroidArchs=${targetPlatformValues.join(' ')}")
args("-dMinSdkVersion=${minSdkVersion}")
args(ruleNames)
}
}
}
class FlutterTask extends BaseFlutterTask {
@OutputDirectory
File getOutputDirectory() {
return intermediateDir
}
@Internal
String getAssetsDirectory() {
return "${outputDirectory}/flutter_assets"
}
@Internal
CopySpec getAssets() {
return project.copySpec {
from("${intermediateDir}")
include("flutter_assets/**") // the working dir and its files
}
}
@Internal
CopySpec getSnapshots() {
return project.copySpec {
from("${intermediateDir}")
if (buildMode == "release" || buildMode == "profile") {
targetPlatformValues.each {
include("${PLATFORM_ARCH_MAP[targetArch]}/app.so")
}
}
}
}
FileCollection readDependencies(File dependenciesFile, Boolean inputs) {
if (dependenciesFile.exists()) {
// Dependencies file has Makefile syntax:
// <target> <files>: <source> <files> <separated> <by> <non-escaped space>
String depText = dependenciesFile.text
// So we split list of files by non-escaped(by backslash) space,
def matcher = depText.split(": ")[inputs ? 1 : 0] =~ /(\\ |[^\s])+/
// then we replace all escaped spaces with regular spaces
def depList = matcher.collect{ it[0].replaceAll("\\\\ ", " ") }
return project.files(depList)
}
return project.files()
}
@InputFiles
FileCollection getSourceFiles() {
FileCollection sources = project.files()
for (File depfile in getDependenciesFiles()) {
sources += readDependencies(depfile, true)
}
return sources + project.files("pubspec.yaml")
}
@OutputFiles
FileCollection getOutputFiles() {
FileCollection sources = project.files()
for (File depfile in getDependenciesFiles()) {
sources += readDependencies(depfile, false)
}
return sources
}
@TaskAction
void build() {
buildBundle()
}
}
| flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy/0 | {
"file_path": "flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy",
"repo_id": "flutter",
"token_count": 35066
} | 727 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="flutter_view" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/examples/flutter_view/lib/main.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/flutter_view.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/flutter_view.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 92
} | 728 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="manual_tests - hover" type="FlutterRunConfigurationType" factoryName="Flutter" singleton="false">
<option name="filePath" value="$PROJECT_DIR$/dev/manual_tests/lib/hover.dart" />
<method v="2" />
</configuration>
</component>
| flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___hover.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___hover.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 103
} | 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 '../base/config.dart';
import '../base/file_system.dart';
import '../base/platform.dart';
import '../base/user_messages.dart';
import '../doctor_validator.dart';
import '../intellij/intellij.dart';
import 'android_studio.dart';
const String _androidStudioTitle = 'Android Studio';
const String _androidStudioId = 'AndroidStudio';
const String _androidStudioPreviewTitle = 'Android Studio Preview';
const String _androidStudioPreviewId = 'AndroidStudioPreview';
class AndroidStudioValidator extends DoctorValidator {
AndroidStudioValidator(this._studio, {
required FileSystem fileSystem,
required UserMessages userMessages,
})
: _userMessages = userMessages,
_fileSystem = fileSystem,
super('Android Studio');
final AndroidStudio _studio;
final FileSystem _fileSystem;
final UserMessages _userMessages;
static const Map<String, String> idToTitle = <String, String>{
_androidStudioId: _androidStudioTitle,
_androidStudioPreviewId: _androidStudioPreviewTitle,
};
static List<DoctorValidator> allValidators(Config config, Platform platform, FileSystem fileSystem, UserMessages userMessages) {
final List<AndroidStudio> studios = AndroidStudio.allInstalled();
return <DoctorValidator>[
if (studios.isEmpty)
NoAndroidStudioValidator(config: config, platform: platform, userMessages: userMessages)
else
...studios.map<DoctorValidator>(
(AndroidStudio studio) => AndroidStudioValidator(studio, fileSystem: fileSystem, userMessages: userMessages)
),
];
}
@override
Future<ValidationResult> validate() async {
final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType type = ValidationType.missing;
final String studioVersionText = _studio.version == null
? _userMessages.androidStudioVersion('unknown')
: _userMessages.androidStudioVersion(_studio.version.toString());
messages.add(ValidationMessage(
_userMessages.androidStudioLocation(_studio.directory),
));
if (_studio.pluginsPath != null) {
final IntelliJPlugins plugins = IntelliJPlugins(_studio.pluginsPath!, fileSystem: _fileSystem);
plugins.validatePackage(
messages,
<String>['flutter-intellij', 'flutter-intellij.jar'],
'Flutter',
IntelliJPlugins.kIntellijFlutterPluginUrl,
minVersion: IntelliJPlugins.kMinFlutterPluginVersion,
);
plugins.validatePackage(
messages,
<String>['Dart'],
'Dart',
IntelliJPlugins.kIntellijDartPluginUrl,
);
}
if (_studio.version == null) {
messages.add(const ValidationMessage.error('Unable to determine Android Studio version.'));
}
if (_studio.isValid) {
type = _hasIssues(messages)
? ValidationType.partial
: ValidationType.success;
messages.addAll(_studio.validationMessages.map<ValidationMessage>(
(String m) => ValidationMessage(m),
));
} else {
type = ValidationType.partial;
messages.addAll(_studio.validationMessages.map<ValidationMessage>(
(String m) => ValidationMessage.error(m),
));
messages.add(ValidationMessage(_userMessages.androidStudioNeedsUpdate));
if (_studio.configuredPath != null) {
messages.add(ValidationMessage(_userMessages.androidStudioResetDir));
}
}
return ValidationResult(type, messages, statusInfo: studioVersionText);
}
bool _hasIssues(List<ValidationMessage> messages) {
return messages.any((ValidationMessage message) => message.isError);
}
}
class NoAndroidStudioValidator extends DoctorValidator {
NoAndroidStudioValidator({
required Config config,
required Platform platform,
required UserMessages userMessages,
}) : _config = config,
_platform = platform,
_userMessages = userMessages,
super('Android Studio');
final Config _config;
final Platform _platform;
final UserMessages _userMessages;
@override
Future<ValidationResult> validate() async {
final List<ValidationMessage> messages = <ValidationMessage>[];
final String? cfgAndroidStudio = _config.getValue(
'android-studio-dir',
) as String?;
if (cfgAndroidStudio != null) {
messages.add(ValidationMessage.error(
_userMessages.androidStudioMissing(cfgAndroidStudio),
));
}
messages.add(ValidationMessage(_userMessages.androidStudioInstallation(_platform)));
return ValidationResult(
ValidationType.notAvailable,
messages,
statusInfo: 'not installed',
);
}
}
| flutter/packages/flutter_tools/lib/src/android/android_studio_validator.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/android/android_studio_validator.dart",
"repo_id": "flutter",
"token_count": 1646
} | 730 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'package:standard_message_codec/standard_message_codec.dart';
import 'base/common.dart';
import 'base/context.dart';
import 'base/deferred_component.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/platform.dart';
import 'build_info.dart';
import 'cache.dart';
import 'convert.dart';
import 'dart/package_map.dart';
import 'devfs.dart';
import 'flutter_manifest.dart';
import 'license_collector.dart';
import 'project.dart';
const String defaultManifestPath = 'pubspec.yaml';
const String kFontManifestJson = 'FontManifest.json';
// Should match '2x', '/1x', '1.5x', etc.
final RegExp _assetVariantDirectoryRegExp = RegExp(r'/?(\d+(\.\d*)?)x$');
/// The effect of adding `uses-material-design: true` to the pubspec is to insert
/// the following snippet into the asset manifest:
///
/// ```yaml
/// material:
/// - family: MaterialIcons
/// fonts:
/// - asset: fonts/MaterialIcons-Regular.otf
/// ```
const List<Map<String, Object>> kMaterialFonts = <Map<String, Object>>[
<String, Object>{
'family': 'MaterialIcons',
'fonts': <Map<String, String>>[
<String, String>{
'asset': 'fonts/MaterialIcons-Regular.otf',
},
],
},
];
const List<String> kMaterialShaders = <String>[
'shaders/ink_sparkle.frag',
];
/// Injected factory class for spawning [AssetBundle] instances.
abstract class AssetBundleFactory {
/// The singleton instance, pulled from the [AppContext].
static AssetBundleFactory get instance => context.get<AssetBundleFactory>()!;
static AssetBundleFactory defaultInstance({
required Logger logger,
required FileSystem fileSystem,
required Platform platform,
bool splitDeferredAssets = false,
}) => _ManifestAssetBundleFactory(
logger: logger,
fileSystem: fileSystem,
platform: platform,
splitDeferredAssets: splitDeferredAssets,
);
/// Creates a new [AssetBundle].
AssetBundle createBundle();
}
enum AssetKind {
regular,
font,
shader,
model,
}
/// Contains all information about an asset needed by tool the to prepare and
/// copy an asset file to the build output.
@immutable
final class AssetBundleEntry {
const AssetBundleEntry(this.content, {
required this.kind,
required this.transformers,
});
final DevFSContent content;
final AssetKind kind;
final List<AssetTransformerEntry> transformers;
Future<List<int>> contentsAsBytes() => content.contentsAsBytes();
}
abstract class AssetBundle {
/// The files that were specified under the `assets` section in the pubspec,
/// indexed by asset key.
Map<String, AssetBundleEntry> get entries;
/// The files that were specified under the deferred components assets sections
/// in a pubspec, indexed by component name and asset key.
Map<String, Map<String, AssetBundleEntry>> get deferredComponentsEntries;
/// Additional files that this bundle depends on that are not included in the
/// output result.
List<File> get additionalDependencies;
/// Input files used to build this asset bundle.
List<File> get inputFiles;
bool wasBuiltOnce();
bool needsBuild({ String manifestPath = defaultManifestPath });
/// Returns 0 for success; non-zero for failure.
Future<int> build({
String manifestPath = defaultManifestPath,
required String packagesPath,
bool deferredComponentsEnabled = false,
TargetPlatform? targetPlatform,
String? flavor,
});
}
class _ManifestAssetBundleFactory implements AssetBundleFactory {
_ManifestAssetBundleFactory({
required Logger logger,
required FileSystem fileSystem,
required Platform platform,
bool splitDeferredAssets = false,
}) : _logger = logger,
_fileSystem = fileSystem,
_platform = platform,
_splitDeferredAssets = splitDeferredAssets;
final Logger _logger;
final FileSystem _fileSystem;
final Platform _platform;
final bool _splitDeferredAssets;
@override
AssetBundle createBundle() => ManifestAssetBundle(
logger: _logger,
fileSystem: _fileSystem,
platform: _platform,
flutterRoot: Cache.flutterRoot!,
splitDeferredAssets: _splitDeferredAssets,
);
}
/// An asset bundle based on a pubspec.yaml file.
class ManifestAssetBundle implements AssetBundle {
/// Constructs an [ManifestAssetBundle] that gathers the set of assets from the
/// pubspec.yaml manifest.
ManifestAssetBundle({
required Logger logger,
required FileSystem fileSystem,
required Platform platform,
required String flutterRoot,
bool splitDeferredAssets = false,
}) : _logger = logger,
_fileSystem = fileSystem,
_platform = platform,
_flutterRoot = flutterRoot,
_splitDeferredAssets = splitDeferredAssets,
_licenseCollector = LicenseCollector(fileSystem: fileSystem);
final Logger _logger;
final FileSystem _fileSystem;
final LicenseCollector _licenseCollector;
final Platform _platform;
final String _flutterRoot;
final bool _splitDeferredAssets;
@override
final Map<String, AssetBundleEntry> entries = <String, AssetBundleEntry>{};
@override
final Map<String, Map<String, AssetBundleEntry>> deferredComponentsEntries = <String, Map<String, AssetBundleEntry>>{};
@override
final List<File> inputFiles = <File>[];
// If an asset corresponds to a wildcard directory, then it may have been
// updated without changes to the manifest. These are only tracked for
// the current project.
final Map<Uri, Directory> _wildcardDirectories = <Uri, Directory>{};
DateTime? _lastBuildTimestamp;
// We assume the main asset is designed for a device pixel ratio of 1.0.
static const String _kAssetManifestJsonFilename = 'AssetManifest.json';
static const String _kAssetManifestBinFilename = 'AssetManifest.bin';
static const String _kAssetManifestBinJsonFilename = 'AssetManifest.bin.json';
static const String _kNoticeFile = 'NOTICES';
// Comically, this can't be name with the more common .gz file extension
// because when it's part of an AAR and brought into another APK via gradle,
// gradle individually traverses all the files of the AAR and unzips .gz
// files (b/37117906). A less common .Z extension still describes how the
// file is formatted if users want to manually inspect the application
// bundle and is recognized by default file handlers on OS such as macOS.˚
static const String _kNoticeZippedFile = 'NOTICES.Z';
@override
bool wasBuiltOnce() => _lastBuildTimestamp != null;
@override
bool needsBuild({ String manifestPath = defaultManifestPath }) {
final DateTime? lastBuildTimestamp = _lastBuildTimestamp;
if (lastBuildTimestamp == null) {
return true;
}
final FileStat manifestStat = _fileSystem.file(manifestPath).statSync();
if (manifestStat.type == FileSystemEntityType.notFound) {
return true;
}
for (final Directory directory in _wildcardDirectories.values) {
if (!directory.existsSync()) {
return true; // directory was deleted.
}
for (final File file in directory.listSync().whereType<File>()) {
final DateTime dateTime = file.statSync().modified;
if (dateTime.isAfter(lastBuildTimestamp)) {
return true;
}
}
}
return manifestStat.modified.isAfter(lastBuildTimestamp);
}
@override
Future<int> build({
String manifestPath = defaultManifestPath,
FlutterProject? flutterProject,
required String packagesPath,
bool deferredComponentsEnabled = false,
TargetPlatform? targetPlatform,
String? flavor,
}) async {
if (flutterProject == null) {
try {
flutterProject = FlutterProject.fromDirectory(_fileSystem.file(manifestPath).parent);
} on Exception catch (e) {
_logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
_logger.printError('$e');
return 1;
}
}
final FlutterManifest flutterManifest = flutterProject.manifest;
// If the last build time isn't set before this early return, empty pubspecs will
// hang on hot reload, as the incremental dill files will never be copied to the
// device.
_lastBuildTimestamp = DateTime.now();
if (flutterManifest.isEmpty) {
entries[_kAssetManifestJsonFilename] = AssetBundleEntry(
DevFSStringContent('{}'),
kind: AssetKind.regular,
transformers: const <AssetTransformerEntry>[],
);
final ByteData emptyAssetManifest =
const StandardMessageCodec().encodeMessage(<dynamic, dynamic>{})!;
entries[_kAssetManifestBinFilename] = AssetBundleEntry(
DevFSByteContent(
emptyAssetManifest.buffer.asUint8List(0, emptyAssetManifest.lengthInBytes),
),
kind: AssetKind.regular,
transformers: const <AssetTransformerEntry>[],
);
// Create .bin.json on web builds.
if (targetPlatform == TargetPlatform.web_javascript) {
entries[_kAssetManifestBinJsonFilename] = AssetBundleEntry(
DevFSStringContent('""'),
kind: AssetKind.regular,
transformers: const <AssetTransformerEntry>[],
);
}
return 0;
}
final String assetBasePath = _fileSystem.path.dirname(_fileSystem.path.absolute(manifestPath));
final File packageConfigFile = _fileSystem.file(packagesPath);
inputFiles.add(packageConfigFile);
final PackageConfig packageConfig = await loadPackageConfigWithLogging(
packageConfigFile,
logger: _logger,
);
final List<Uri> wildcardDirectories = <Uri>[];
// The _assetVariants map contains an entry for each asset listed
// in the pubspec.yaml file's assets and font sections. The
// value of each image asset is a list of resolution-specific "variants",
// see _AssetDirectoryCache.
final Map<_Asset, List<_Asset>>? assetVariants = _parseAssets(
packageConfig,
flutterManifest,
wildcardDirectories,
assetBasePath,
targetPlatform,
flavor: flavor,
);
if (assetVariants == null) {
return 1;
}
// Parse assets for deferred components.
final Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants = _parseDeferredComponentsAssets(
flutterManifest,
packageConfig,
assetBasePath,
wildcardDirectories,
flutterProject.directory,
flavor: flavor,
);
if (!_splitDeferredAssets || !deferredComponentsEnabled) {
// Include the assets in the regular set of assets if not using deferred
// components.
deferredComponentsAssetVariants.values.forEach(assetVariants.addAll);
deferredComponentsAssetVariants.clear();
deferredComponentsEntries.clear();
}
final bool includesMaterialFonts = flutterManifest.usesMaterialDesign;
final List<Map<String, Object?>> fonts = _parseFonts(
flutterManifest,
packageConfig,
primary: true,
);
// Add fonts, assets, and licenses from packages.
final Map<String, List<File>> additionalLicenseFiles = <String, List<File>>{};
for (final Package package in packageConfig.packages) {
final Uri packageUri = package.packageUriRoot;
if (packageUri.scheme == 'file') {
final String packageManifestPath = _fileSystem.path.fromUri(packageUri.resolve('../pubspec.yaml'));
inputFiles.add(_fileSystem.file(packageManifestPath));
final FlutterManifest? packageFlutterManifest = FlutterManifest.createFromPath(
packageManifestPath,
logger: _logger,
fileSystem: _fileSystem,
);
if (packageFlutterManifest == null) {
continue;
}
// Collect any additional licenses from each package.
final List<File> licenseFiles = <File>[];
for (final String relativeLicensePath in packageFlutterManifest.additionalLicenses) {
final String absoluteLicensePath = _fileSystem.path.fromUri(package.root.resolve(relativeLicensePath));
licenseFiles.add(_fileSystem.file(absoluteLicensePath).absolute);
}
additionalLicenseFiles[packageFlutterManifest.appName] = licenseFiles;
// Skip the app itself
if (packageFlutterManifest.appName == flutterManifest.appName) {
continue;
}
final String packageBasePath = _fileSystem.path.dirname(packageManifestPath);
final Map<_Asset, List<_Asset>>? packageAssets = _parseAssets(
packageConfig,
packageFlutterManifest,
// Do not track wildcard directories for dependencies.
<Uri>[],
packageBasePath,
targetPlatform,
packageName: package.name,
attributedPackage: package,
);
if (packageAssets == null) {
return 1;
}
assetVariants.addAll(packageAssets);
if (!includesMaterialFonts && packageFlutterManifest.usesMaterialDesign) {
_logger.printError(
'package:${package.name} has `uses-material-design: true` set but '
'the primary pubspec contains `uses-material-design: false`. '
'If the application needs material icons, then `uses-material-design` '
' must be set to true.'
);
}
fonts.addAll(_parseFonts(
packageFlutterManifest,
packageConfig,
packageName: package.name,
primary: false,
));
}
}
// Save the contents of each image, image variant, and font
// asset in entries.
for (final _Asset asset in assetVariants.keys) {
final File assetFile = asset.lookupAssetFile(_fileSystem);
final List<_Asset> variants = assetVariants[asset]!;
if (!assetFile.existsSync() && variants.isEmpty) {
_logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
_logger.printError('No file or variants found for $asset.\n');
if (asset.package != null) {
_logger.printError('This asset was included from package ${asset.package?.name}.');
}
return 1;
}
// The file name for an asset's "main" entry is whatever appears in
// the pubspec.yaml file. The main entry's file must always exist for
// font assets. It need not exist for an image if resolution-specific
// variant files exist. An image's main entry is treated the same as a
// "1x" resolution variant and if both exist then the explicit 1x
// variant is preferred.
if (assetFile.existsSync() && !variants.contains(asset)) {
variants.insert(0, asset);
}
for (final _Asset variant in variants) {
final File variantFile = variant.lookupAssetFile(_fileSystem);
inputFiles.add(variantFile);
assert(variantFile.existsSync());
entries[variant.entryUri.path] ??= AssetBundleEntry(
DevFSFileContent(variantFile),
kind: variant.kind,
transformers: variant.transformers,
);
}
}
// Save the contents of each deferred component image, image variant, and font
// asset in deferredComponentsEntries.
for (final String componentName in deferredComponentsAssetVariants.keys) {
deferredComponentsEntries[componentName] = <String, AssetBundleEntry>{};
final Map<_Asset, List<_Asset>> assetsMap = deferredComponentsAssetVariants[componentName]!;
for (final _Asset asset in assetsMap.keys) {
final File assetFile = asset.lookupAssetFile(_fileSystem);
if (!assetFile.existsSync() && assetsMap[asset]!.isEmpty) {
_logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
_logger.printError('No file or variants found for $asset.\n');
if (asset.package != null) {
_logger.printError('This asset was included from package ${asset.package?.name}.');
}
return 1;
}
// The file name for an asset's "main" entry is whatever appears in
// the pubspec.yaml file. The main entry's file must always exist for
// font assets. It need not exist for an image if resolution-specific
// variant files exist. An image's main entry is treated the same as a
// "1x" resolution variant and if both exist then the explicit 1x
// variant is preferred.
if (assetFile.existsSync() && !assetsMap[asset]!.contains(asset)) {
assetsMap[asset]!.insert(0, asset);
}
for (final _Asset variant in assetsMap[asset]!) {
final File variantFile = variant.lookupAssetFile(_fileSystem);
assert(variantFile.existsSync());
deferredComponentsEntries[componentName]![variant.entryUri.path] ??= AssetBundleEntry(
DevFSFileContent(variantFile),
kind: AssetKind.regular,
transformers: variant.transformers,
);
}
}
}
final List<_Asset> materialAssets = <_Asset>[
if (flutterManifest.usesMaterialDesign)
..._getMaterialFonts(),
// For all platforms, include the shaders unconditionally. They are
// small, and whether they're used is determined only by the app source
// code and not by the Flutter manifest.
..._getMaterialShaders(),
];
for (final _Asset asset in materialAssets) {
final File assetFile = asset.lookupAssetFile(_fileSystem);
assert(assetFile.existsSync(), 'Missing ${assetFile.path}');
entries[asset.entryUri.path] ??= AssetBundleEntry(
DevFSFileContent(assetFile),
kind: asset.kind,
transformers: const <AssetTransformerEntry>[],
);
}
// Update wildcard directories we can detect changes in them.
for (final Uri uri in wildcardDirectories) {
_wildcardDirectories[uri] ??= _fileSystem.directory(uri);
}
final Map<String, List<String>> assetManifest =
_createAssetManifest(assetVariants, deferredComponentsAssetVariants);
final DevFSByteContent assetManifestBinary = _createAssetManifestBinary(assetManifest);
final DevFSStringContent assetManifestJson = DevFSStringContent(json.encode(assetManifest));
final DevFSStringContent fontManifest = DevFSStringContent(json.encode(fonts));
final LicenseResult licenseResult = _licenseCollector.obtainLicenses(packageConfig, additionalLicenseFiles);
if (licenseResult.errorMessages.isNotEmpty) {
licenseResult.errorMessages.forEach(_logger.printError);
return 1;
}
additionalDependencies = licenseResult.dependencies;
inputFiles.addAll(additionalDependencies);
if (wildcardDirectories.isNotEmpty) {
// Force the depfile to contain missing files so that Gradle does not skip
// the task. Wildcard directories are not compatible with full incremental
// builds. For more context see https://github.com/flutter/flutter/issues/56466 .
_logger.printTrace(
'Manifest contained wildcard assets. Inserting missing file into '
'build graph to force rerun. for more information see #56466.'
);
final int suffix = Object().hashCode;
additionalDependencies.add(
_fileSystem.file('DOES_NOT_EXIST_RERUN_FOR_WILDCARD$suffix').absolute);
}
_setIfChanged(_kAssetManifestJsonFilename, assetManifestJson, AssetKind.regular);
_setIfChanged(_kAssetManifestBinFilename, assetManifestBinary, AssetKind.regular);
// Create .bin.json on web builds.
if (targetPlatform == TargetPlatform.web_javascript) {
final DevFSStringContent assetManifestBinaryJson = DevFSStringContent(json.encode(
base64.encode(assetManifestBinary.bytes)
));
_setIfChanged(_kAssetManifestBinJsonFilename, assetManifestBinaryJson, AssetKind.regular);
}
_setIfChanged(kFontManifestJson, fontManifest, AssetKind.regular);
_setLicenseIfChanged(licenseResult.combinedLicenses, targetPlatform);
return 0;
}
@override
List<File> additionalDependencies = <File>[];
void _setIfChanged(String key, DevFSContent content, AssetKind assetKind) {
final DevFSContent? oldContent = entries[key]?.content;
// In the case that the content is unchanged, we want to avoid an overwrite
// as the isModified property may be reset to true,
if (oldContent is DevFSByteContent && content is DevFSByteContent &&
_compareIntLists(oldContent.bytes, content.bytes)) {
return;
}
entries[key] = AssetBundleEntry(
content,
kind: assetKind,
transformers: const <AssetTransformerEntry>[],
);
}
static bool _compareIntLists(List<int> o1, List<int> o2) {
if (o1.length != o2.length) {
return false;
}
for (int index = 0; index < o1.length; index++) {
if (o1[index] != o2[index]) {
return false;
}
}
return true;
}
void _setLicenseIfChanged(
String combinedLicenses,
TargetPlatform? targetPlatform,
) {
// On the web, don't compress the NOTICES file since the client doesn't have
// dart:io to decompress it. So use the standard _setIfChanged to check if
// the strings still match.
if (targetPlatform == TargetPlatform.web_javascript) {
_setIfChanged(_kNoticeFile, DevFSStringContent(combinedLicenses), AssetKind.regular);
return;
}
// On other platforms, let the NOTICES file be compressed. But use a
// specialized DevFSStringCompressingBytesContent class to compare
// the uncompressed strings to not incur decompression/decoding while making
// the comparison.
if (!entries.containsKey(_kNoticeZippedFile) ||
(entries[_kNoticeZippedFile]?.content as DevFSStringCompressingBytesContent?)
?.equals(combinedLicenses) != true) {
entries[_kNoticeZippedFile] = AssetBundleEntry(
DevFSStringCompressingBytesContent(
combinedLicenses,
// A zlib dictionary is a hinting string sequence with the most
// likely string occurrences at the end. This ends up just being
// common English words with domain specific words like copyright.
hintString: 'copyrightsoftwaretothisinandorofthe',
),
kind: AssetKind.regular,
transformers: const<AssetTransformerEntry>[],
);
}
}
List<_Asset> _getMaterialFonts() {
final List<_Asset> result = <_Asset>[];
for (final Map<String, Object> family in kMaterialFonts) {
final Object? fonts = family['fonts'];
if (fonts == null) {
continue;
}
for (final Map<String, Object> font in fonts as List<Map<String, String>>) {
final String? asset = font['asset'] as String?;
if (asset == null) {
continue;
}
final Uri entryUri = _fileSystem.path.toUri(asset);
result.add(_Asset(
baseDir: _fileSystem.path.join(
_flutterRoot,
'bin', 'cache', 'artifacts', 'material_fonts',
),
relativeUri: Uri(path: entryUri.pathSegments.last),
entryUri: entryUri,
package: null,
kind: AssetKind.font,
));
}
}
return result;
}
List<_Asset> _getMaterialShaders() {
final String shaderPath = _fileSystem.path.join(
_flutterRoot, 'packages', 'flutter', 'lib', 'src', 'material', 'shaders',
);
// This file will exist in a real invocation unless the git checkout is
// corrupted somehow, but unit tests generally don't create this file
// in their mock file systems. Leaving it out in those cases is harmless.
if (!_fileSystem.directory(shaderPath).existsSync()) {
return <_Asset>[];
}
final List<_Asset> result = <_Asset>[];
for (final String shader in kMaterialShaders) {
final Uri entryUri = _fileSystem.path.toUri(shader);
result.add(_Asset(
baseDir: shaderPath,
relativeUri: Uri(path: entryUri.pathSegments.last),
entryUri: entryUri,
package: null,
kind: AssetKind.shader,
));
}
return result;
}
List<Map<String, Object?>> _parseFonts(
FlutterManifest manifest,
PackageConfig packageConfig, {
String? packageName,
required bool primary,
}) {
return <Map<String, Object?>>[
if (primary && manifest.usesMaterialDesign)
...kMaterialFonts,
if (packageName == null)
...manifest.fontsDescriptor
else
for (final Font font in _parsePackageFonts(
manifest,
packageName,
packageConfig,
)) font.descriptor,
];
}
Map<String, Map<_Asset, List<_Asset>>> _parseDeferredComponentsAssets(
FlutterManifest flutterManifest,
PackageConfig packageConfig,
String assetBasePath,
List<Uri> wildcardDirectories,
Directory projectDirectory, {
String? flavor,
}) {
final List<DeferredComponent>? components = flutterManifest.deferredComponents;
final Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants = <String, Map<_Asset, List<_Asset>>>{};
if (components == null) {
return deferredComponentsAssetVariants;
}
for (final DeferredComponent component in components) {
final _AssetDirectoryCache cache = _AssetDirectoryCache(_fileSystem);
final Map<_Asset, List<_Asset>> componentAssets = <_Asset, List<_Asset>>{};
for (final AssetsEntry assetsEntry in component.assets) {
if (assetsEntry.uri.path.endsWith('/')) {
wildcardDirectories.add(assetsEntry.uri);
_parseAssetsFromFolder(
packageConfig,
flutterManifest,
assetBasePath,
cache,
componentAssets,
assetsEntry.uri,
flavors: assetsEntry.flavors,
transformers: assetsEntry.transformers,
);
} else {
_parseAssetFromFile(
packageConfig,
flutterManifest,
assetBasePath,
cache,
componentAssets,
assetsEntry.uri,
flavors: assetsEntry.flavors,
transformers: assetsEntry.transformers,
);
}
}
componentAssets.removeWhere((_Asset asset, List<_Asset> variants) => !asset.matchesFlavor(flavor));
deferredComponentsAssetVariants[component.name] = componentAssets;
}
return deferredComponentsAssetVariants;
}
Map<String, List<String>> _createAssetManifest(
Map<_Asset, List<_Asset>> assetVariants,
Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants
) {
final Map<String, List<String>> manifest = <String, List<String>>{};
final Map<_Asset, List<String>> entries = <_Asset, List<String>>{};
assetVariants.forEach((_Asset main, List<_Asset> variants) {
entries[main] = <String>[
for (final _Asset variant in variants)
variant.entryUri.path,
];
});
for (final Map<_Asset, List<_Asset>> componentAssets in deferredComponentsAssetVariants.values) {
componentAssets.forEach((_Asset main, List<_Asset> variants) {
entries[main] = <String>[
for (final _Asset variant in variants)
variant.entryUri.path,
];
});
}
final List<_Asset> sortedKeys = entries.keys.toList()
..sort((_Asset left, _Asset right) => left.entryUri.path.compareTo(right.entryUri.path));
for (final _Asset main in sortedKeys) {
final String decodedEntryPath = Uri.decodeFull(main.entryUri.path);
final List<String> rawEntryVariantsPaths = entries[main]!;
final List<String> decodedEntryVariantPaths = rawEntryVariantsPaths
.map((String value) => Uri.decodeFull(value))
.toList();
manifest[decodedEntryPath] = decodedEntryVariantPaths;
}
return manifest;
}
// Matches path-like strings ending in a number followed by an 'x'.
// Example matches include "assets/animals/2.0x", "plants/3x", and "2.7x".
static final RegExp _extractPixelRatioFromKeyRegExp = RegExp(r'/?(\d+(\.\d*)?)x$');
DevFSByteContent _createAssetManifestBinary(
Map<String, List<String>> assetManifest
) {
double? parseScale(String key) {
final Uri assetUri = Uri.parse(key);
String directoryPath = '';
if (assetUri.pathSegments.length > 1) {
directoryPath = assetUri.pathSegments[assetUri.pathSegments.length - 2];
}
final Match? match = _extractPixelRatioFromKeyRegExp.firstMatch(directoryPath);
if (match != null && match.groupCount > 0) {
return double.parse(match.group(1)!);
}
return null;
}
final Map<String, dynamic> result = <String, dynamic>{};
for (final MapEntry<String, dynamic> manifestEntry in assetManifest.entries) {
final List<dynamic> resultVariants = <dynamic>[];
final List<String> entries = (manifestEntry.value as List<dynamic>).cast<String>();
for (final String variant in entries) {
final Map<String, dynamic> resultVariant = <String, dynamic>{};
final double? variantDevicePixelRatio = parseScale(variant);
resultVariant['asset'] = variant;
if (variantDevicePixelRatio != null) {
resultVariant['dpr'] = variantDevicePixelRatio;
}
resultVariants.add(resultVariant);
}
result[manifestEntry.key] = resultVariants;
}
final ByteData message = const StandardMessageCodec().encodeMessage(result)!;
return DevFSByteContent(message.buffer.asUint8List(0, message.lengthInBytes));
}
/// Prefixes family names and asset paths of fonts included from packages with
/// 'packages/<package_name>'
List<Font> _parsePackageFonts(
FlutterManifest manifest,
String packageName,
PackageConfig packageConfig,
) {
final List<Font> packageFonts = <Font>[];
for (final Font font in manifest.fonts) {
final List<FontAsset> packageFontAssets = <FontAsset>[];
for (final FontAsset fontAsset in font.fontAssets) {
final Uri assetUri = fontAsset.assetUri;
if (assetUri.pathSegments.first == 'packages' &&
!_fileSystem.isFileSync(_fileSystem.path.fromUri(
packageConfig[packageName]?.packageUriRoot.resolve('../${assetUri.path}')))) {
packageFontAssets.add(FontAsset(
fontAsset.assetUri,
weight: fontAsset.weight,
style: fontAsset.style,
));
} else {
packageFontAssets.add(FontAsset(
Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]),
weight: fontAsset.weight,
style: fontAsset.style,
));
}
}
packageFonts.add(Font('packages/$packageName/${font.familyName}', packageFontAssets));
}
return packageFonts;
}
/// Given an assetBase location and a pubspec.yaml Flutter manifest, return a
/// map of assets to asset variants.
///
/// Returns null on missing assets.
///
/// Given package: 'test_package' and an assets directory like this:
///
/// - assets/foo
/// - assets/var1/foo
/// - assets/var2/foo
/// - assets/bar
///
/// This will return:
/// ```
/// {
/// asset: packages/test_package/assets/foo: [
/// asset: packages/test_package/assets/foo,
/// asset: packages/test_package/assets/var1/foo,
/// asset: packages/test_package/assets/var2/foo,
/// ],
/// asset: packages/test_package/assets/bar: [
/// asset: packages/test_package/assets/bar,
/// ],
/// }
/// ```
Map<_Asset, List<_Asset>>? _parseAssets(
PackageConfig packageConfig,
FlutterManifest flutterManifest,
List<Uri> wildcardDirectories,
String assetBase,
TargetPlatform? targetPlatform, {
String? packageName,
Package? attributedPackage,
String? flavor,
}) {
final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
final _AssetDirectoryCache cache = _AssetDirectoryCache(_fileSystem);
for (final AssetsEntry assetsEntry in flutterManifest.assets) {
if (assetsEntry.uri.path.endsWith('/')) {
wildcardDirectories.add(assetsEntry.uri);
_parseAssetsFromFolder(
packageConfig,
flutterManifest,
assetBase,
cache,
result,
assetsEntry.uri,
packageName: packageName,
attributedPackage: attributedPackage,
flavors: assetsEntry.flavors,
transformers: assetsEntry.transformers,
);
} else {
_parseAssetFromFile(
packageConfig,
flutterManifest,
assetBase,
cache,
result,
assetsEntry.uri,
packageName: packageName,
attributedPackage: attributedPackage,
flavors: assetsEntry.flavors,
transformers: assetsEntry.transformers,
);
}
}
result.removeWhere((_Asset asset, List<_Asset> variants) {
if (!asset.matchesFlavor(flavor)) {
_logger.printTrace('Skipping assets entry "${asset.entryUri.path}" since '
'its configured flavor(s) did not match the provided flavor (if any).\n'
'Configured flavors: ${asset.flavors.join(', ')}\n');
return true;
}
return false;
});
for (final Uri shaderUri in flutterManifest.shaders) {
_parseAssetFromFile(
packageConfig,
flutterManifest,
assetBase,
cache,
result,
shaderUri,
packageName: packageName,
attributedPackage: attributedPackage,
assetKind: AssetKind.shader,
flavors: <String>{},
transformers: <AssetTransformerEntry>[],
);
}
for (final Uri modelUri in flutterManifest.models) {
_parseAssetFromFile(
packageConfig,
flutterManifest,
assetBase,
cache,
result,
modelUri,
packageName: packageName,
attributedPackage: attributedPackage,
assetKind: AssetKind.model,
flavors: <String>{},
transformers: <AssetTransformerEntry>[],
);
}
// Add assets referenced in the fonts section of the manifest.
for (final Font font in flutterManifest.fonts) {
for (final FontAsset fontAsset in font.fontAssets) {
final _Asset baseAsset = _resolveAsset(
packageConfig,
assetBase,
fontAsset.assetUri,
packageName,
attributedPackage,
assetKind: AssetKind.font,
flavors: <String>{},
transformers: <AssetTransformerEntry>[],
);
final File baseAssetFile = baseAsset.lookupAssetFile(_fileSystem);
if (!baseAssetFile.existsSync()) {
_logger.printError('Error: unable to locate asset entry in pubspec.yaml: "${fontAsset.assetUri}".');
return null;
}
result[baseAsset] = <_Asset>[];
}
}
return result;
}
void _parseAssetsFromFolder(
PackageConfig packageConfig,
FlutterManifest flutterManifest,
String assetBase,
_AssetDirectoryCache cache,
Map<_Asset, List<_Asset>> result,
Uri assetUri, {
String? packageName,
Package? attributedPackage,
required Set<String> flavors,
required List<AssetTransformerEntry> transformers,
}) {
final String directoryPath;
try {
directoryPath = _fileSystem.path
.join(assetBase, assetUri.toFilePath(windows: _platform.isWindows));
} on UnsupportedError catch (e) {
throwToolExit(
'Unable to search for asset files in directory path "${assetUri.path}". '
'Please ensure that this entry in pubspec.yaml is a valid file path.\n'
'Error details:\n$e');
}
if (!_fileSystem.directory(directoryPath).existsSync()) {
_logger.printError('Error: unable to find directory entry in pubspec.yaml: $directoryPath');
return;
}
final Iterable<FileSystemEntity> entities = _fileSystem.directory(directoryPath).listSync();
final Iterable<File> files = entities.whereType<File>();
for (final File file in files) {
final String relativePath = _fileSystem.path.relative(file.path, from: assetBase);
final Uri uri = Uri.file(relativePath, windows: _platform.isWindows);
_parseAssetFromFile(
packageConfig,
flutterManifest,
assetBase,
cache,
result,
uri,
packageName: packageName,
attributedPackage: attributedPackage,
originUri: assetUri,
flavors: flavors,
transformers: transformers,
);
}
}
void _parseAssetFromFile(
PackageConfig packageConfig,
FlutterManifest flutterManifest,
String assetBase,
_AssetDirectoryCache cache,
Map<_Asset, List<_Asset>> result,
Uri assetUri, {
Uri? originUri,
String? packageName,
Package? attributedPackage,
AssetKind assetKind = AssetKind.regular,
required Set<String> flavors,
required List<AssetTransformerEntry> transformers,
}) {
final _Asset asset = _resolveAsset(
packageConfig,
assetBase,
assetUri,
packageName,
attributedPackage,
assetKind: assetKind,
originUri: originUri,
flavors: flavors,
transformers: transformers,
);
_checkForFlavorConflicts(asset, result.keys.toList());
final List<_Asset> variants = <_Asset>[];
final File assetFile = asset.lookupAssetFile(_fileSystem);
for (final String path in cache.variantsFor(assetFile.path)) {
final String relativePath = _fileSystem.path.relative(path, from: asset.baseDir);
final Uri relativeUri = _fileSystem.path.toUri(relativePath);
final Uri? entryUri = asset.symbolicPrefixUri == null
? relativeUri
: asset.symbolicPrefixUri?.resolveUri(relativeUri);
if (entryUri != null) {
variants.add(
_Asset(
baseDir: asset.baseDir,
entryUri: entryUri,
relativeUri: relativeUri,
package: attributedPackage,
kind: assetKind,
flavors: flavors,
transformers: transformers,
),
);
}
}
result[asset] = variants;
}
// Since it is not clear how overlapping asset declarations should work in the
// presence of conditions such as `flavor`, we throw an Error.
//
// To be more specific, it is not clear if conditions should be combined with
// or-logic or and-logic, or if it should depend on the specificity of the
// declarations (file versus directory). If you would like examples, consider these:
//
// ```yaml
// # Should assets/free.mp3 always be included since "assets/" has no flavor?
// assets:
// - assets/
// - path: assets/free.mp3
// flavor: free
//
// # Should "assets/paid/pip.mp3" be included for both the "paid" and "free" flavors?
// # Or, since "assets/paid/pip.mp3" is more specific than "assets/paid/"", should
// # it take precedence over the latter (included only in "free" flavor)?
// assets:
// - path: assets/paid/
// flavor: paid
// - path: assets/paid/pip.mp3
// flavor: free
// - asset
// ```
//
// Since it is not obvious what logic (if any) would be intuitive and preferable
// to the vast majority of users (if any), we play it safe by throwing a `ToolExit`
// in any of these situations. We can always loosen up this restriction later
// without breaking anyone.
void _checkForFlavorConflicts(_Asset newAsset, List<_Asset> previouslyParsedAssets) {
bool cameFromDirectoryEntry(_Asset asset) {
return asset.originUri.path.endsWith('/');
}
String flavorErrorInfo(_Asset asset) {
if (asset.flavors.isEmpty) {
return 'An entry with the path "${asset.originUri}" does not specify any flavors.';
}
final Iterable<String> flavorsWrappedWithQuotes = asset.flavors.map((String e) => '"$e"');
return 'An entry with the path "${asset.originUri}" specifies the flavor(s): '
'${flavorsWrappedWithQuotes.join(', ')}.';
}
final _Asset? preExistingAsset = previouslyParsedAssets
.where((_Asset other) => other.entryUri == newAsset.entryUri)
.firstOrNull;
if (preExistingAsset == null || preExistingAsset.hasEquivalentFlavorsWith(newAsset)) {
return;
}
final StringBuffer errorMessage = StringBuffer(
'Multiple assets entries include the file '
'"${newAsset.entryUri.path}", but they specify different lists of flavors.\n');
errorMessage.writeln(flavorErrorInfo(preExistingAsset));
errorMessage.writeln(flavorErrorInfo(newAsset));
if (cameFromDirectoryEntry(newAsset)|| cameFromDirectoryEntry(preExistingAsset)) {
errorMessage.writeln();
errorMessage.write('Consider organizing assets with different flavors '
'into different directories.');
}
throwToolExit(errorMessage.toString());
}
_Asset _resolveAsset(
PackageConfig packageConfig,
String assetsBaseDir,
Uri assetUri,
String? packageName,
Package? attributedPackage, {
Uri? originUri,
AssetKind assetKind = AssetKind.regular,
required Set<String> flavors,
required List<AssetTransformerEntry> transformers,
}) {
final String assetPath = _fileSystem.path.fromUri(assetUri);
if (assetUri.pathSegments.first == 'packages'
&& !_fileSystem.isFileSync(_fileSystem.path.join(assetsBaseDir, assetPath))) {
// The asset is referenced in the pubspec.yaml as
// 'packages/PACKAGE_NAME/PATH/TO/ASSET .
final _Asset? packageAsset = _resolvePackageAsset(
assetUri,
packageConfig,
attributedPackage,
assetKind: assetKind,
originUri: originUri,
flavors: flavors,
transformers: transformers,
);
if (packageAsset != null) {
return packageAsset;
}
}
return _Asset(
baseDir: assetsBaseDir,
entryUri: packageName == null
? assetUri // Asset from the current application.
: Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]), // Asset from, and declared in $packageName.
relativeUri: assetUri,
package: attributedPackage,
originUri: originUri,
kind: assetKind,
flavors: flavors,
transformers: transformers,
);
}
_Asset? _resolvePackageAsset(
Uri assetUri,
PackageConfig packageConfig,
Package? attributedPackage, {
AssetKind assetKind = AssetKind.regular,
Uri? originUri,
Set<String>? flavors,
List<AssetTransformerEntry>? transformers,
}) {
assert(assetUri.pathSegments.first == 'packages');
if (assetUri.pathSegments.length > 1) {
final String packageName = assetUri.pathSegments[1];
final Package? package = packageConfig[packageName];
final Uri? packageUri = package?.packageUriRoot;
if (packageUri != null && packageUri.scheme == 'file') {
return _Asset(
baseDir: _fileSystem.path.fromUri(packageUri),
entryUri: assetUri,
relativeUri: Uri(pathSegments: assetUri.pathSegments.sublist(2)),
package: attributedPackage,
kind: assetKind,
originUri: originUri,
flavors: flavors,
transformers: transformers,
);
}
}
_logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
_logger.printError('Could not resolve package for asset $assetUri.\n');
if (attributedPackage != null) {
_logger.printError('This asset was included from package ${attributedPackage.name}');
}
return null;
}
}
@immutable
class _Asset {
const _Asset({
required this.baseDir,
Uri? originUri,
required this.relativeUri,
required this.entryUri,
required this.package,
this.kind = AssetKind.regular,
Set<String>? flavors,
List<AssetTransformerEntry>? transformers,
}) : originUri = originUri ?? entryUri,
flavors = flavors ?? const <String>{},
transformers = transformers ?? const <AssetTransformerEntry>[];
final String baseDir;
final Package? package;
/// The platform-independent URL provided by the user in the pubspec that this
/// asset was found from.
final Uri originUri;
/// A platform-independent URL where this asset can be found on disk on the
/// host system relative to [baseDir].
final Uri relativeUri;
/// A platform-independent URL representing the entry for the asset manifest.
final Uri entryUri;
final AssetKind kind;
final Set<String> flavors;
final List<AssetTransformerEntry> transformers;
File lookupAssetFile(FileSystem fileSystem) {
return fileSystem.file(fileSystem.path.join(baseDir, fileSystem.path.fromUri(relativeUri)));
}
/// The delta between what the entryUri is and the relativeUri (e.g.,
/// packages/flutter_gallery).
Uri? get symbolicPrefixUri {
if (entryUri == relativeUri) {
return null;
}
final int index = entryUri.path.indexOf(relativeUri.path);
return index == -1 ? null : Uri(path: entryUri.path.substring(0, index));
}
bool matchesFlavor(String? flavor) {
if (flavors.isEmpty) {
return true;
}
if (flavor == null) {
return false;
}
return flavors.contains(flavor);
}
bool hasEquivalentFlavorsWith(_Asset other) {
final Set<String> assetFlavors = flavors.toSet();
final Set<String> otherFlavors = other.flavors.toSet();
return assetFlavors.length == otherFlavors.length && assetFlavors.every(
(String e) => otherFlavors.contains(e),
);
}
@override
String toString() => 'asset: $entryUri';
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is _Asset
&& other.baseDir == baseDir
&& other.relativeUri == relativeUri
&& other.entryUri == entryUri
&& other.kind == kind
&& hasEquivalentFlavorsWith(other);
}
@override
int get hashCode => Object.hashAll(<Object>[
baseDir,
relativeUri,
entryUri,
kind,
...flavors,
]);
}
// Given an assets directory like this:
//
// assets/foo.png
// assets/2x/foo.png
// assets/3.0x/foo.png
// assets/bar/foo.png
// assets/bar.png
//
// variantsFor('assets/foo.png') => ['/assets/foo.png', '/assets/2x/foo.png', 'assets/3.0x/foo.png']
// variantsFor('assets/bar.png') => ['/assets/bar.png']
// variantsFor('assets/bar/foo.png') => ['/assets/bar/foo.png']
class _AssetDirectoryCache {
_AssetDirectoryCache(this._fileSystem);
final FileSystem _fileSystem;
final Map<String, List<String>> _cache = <String, List<String>>{};
final Map<String, List<File>> _variantsPerFolder = <String, List<File>>{};
List<String> variantsFor(String assetPath) {
final String directoryName = _fileSystem.path.dirname(assetPath);
try {
if (!_fileSystem.directory(directoryName).existsSync()) {
return const <String>[];
}
} on FileSystemException catch (e) {
throwToolExit(
'Unable to check the existence of asset file "$assetPath". '
'Ensure that the asset file is declared as a valid local file system path.\n'
'Details: $e',
);
}
if (_cache.containsKey(assetPath)) {
return _cache[assetPath]!;
}
if (!_variantsPerFolder.containsKey(directoryName)) {
_variantsPerFolder[directoryName] = _fileSystem.directory(directoryName)
.listSync()
.whereType<Directory>()
.where((Directory dir) => _assetVariantDirectoryRegExp.hasMatch(dir.basename))
.expand((Directory dir) => dir.listSync())
.whereType<File>()
.toList();
}
final File assetFile = _fileSystem.file(assetPath);
final List<File> potentialVariants = _variantsPerFolder[directoryName]!;
final String basename = assetFile.basename;
return _cache[assetPath] = <String>[
// It's possible that the user specifies only explicit variants (e.g. .../1x/asset.png),
// so there does not necessarily need to be a file at the given path.
if (assetFile.existsSync())
assetPath,
...potentialVariants
.where((File file) => file.basename == basename)
.map((File file) => file.path),
];
}
}
| flutter/packages/flutter_tools/lib/src/asset.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/asset.dart",
"repo_id": "flutter",
"token_count": 18187
} | 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:io' as io
show
Directory,
File,
FileStat,
FileSystemEntity,
FileSystemEntityType,
Link;
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p; // flutter_ignore: package_path_import
/// A [FileSystem] that wraps the [delegate] file system to create an overlay of
/// files from multiple [roots].
///
/// Regular paths or `file:` URIs are resolved directly in the underlying file
/// system, but URIs that use a special [scheme] are resolved by searching
/// under a set of given roots in order.
///
/// For example, consider the following inputs:
///
/// - scheme is `multi-root`
/// - the set of roots are `/a` and `/b`
/// - the underlying file system contains files:
/// /root_a/dir/only_a.dart
/// /root_a/dir/both.dart
/// /root_b/dir/only_b.dart
/// /root_b/dir/both.dart
/// /other/other.dart
///
/// Then:
///
/// - file:///other/other.dart is resolved as /other/other.dart
/// - multi-root:///dir/only_a.dart is resolved as /root_a/dir/only_a.dart
/// - multi-root:///dir/only_b.dart is resolved as /root_b/dir/only_b.dart
/// - multi-root:///dir/both.dart is resolved as /root_a/dir/only_a.dart
class MultiRootFileSystem extends ForwardingFileSystem {
MultiRootFileSystem({
required FileSystem delegate,
required String scheme,
required List<String> roots,
}) : assert(roots.isNotEmpty),
_scheme = scheme,
_roots = roots.map((String root) => delegate.path.normalize(root)).toList(),
super(delegate);
@visibleForTesting
FileSystem get fileSystem => delegate;
final String _scheme;
final List<String> _roots;
@override
File file(dynamic path) => MultiRootFile(
fileSystem: this,
delegate: delegate.file(_resolve(path)),
);
@override
Directory directory(dynamic path) => MultiRootDirectory(
fileSystem: this,
delegate: delegate.directory(_resolve(path)),
);
@override
Link link(dynamic path) => MultiRootLink(
fileSystem: this,
delegate: delegate.link(_resolve(path)),
);
@override
Future<io.FileStat> stat(String path) =>
delegate.stat(_resolve(path).toString());
@override
io.FileStat statSync(String path) =>
delegate.statSync(_resolve(path).toString());
@override
Future<bool> identical(String path1, String path2) =>
delegate.identical(_resolve(path1).toString(), _resolve(path2).toString());
@override
bool identicalSync(String path1, String path2) =>
delegate.identicalSync(_resolve(path1).toString(), _resolve(path2).toString());
@override
Future<io.FileSystemEntityType> type(String path, {bool followLinks = true}) =>
delegate.type(_resolve(path).toString(), followLinks: followLinks);
@override
io.FileSystemEntityType typeSync(String path, {bool followLinks = true}) =>
delegate.typeSync(_resolve(path).toString(), followLinks: followLinks);
// Caching the path context here and clearing when the currentDirectory setter
// is updated works since the flutter tool restricts usage of dart:io directly
// via the forbidden import tests. Otherwise, the path context's current
// working directory might get out of sync, leading to unexpected results from
// methods like `path.relative`.
@override
p.Context get path => _cachedPath ??= delegate.path;
p.Context? _cachedPath;
@override
set currentDirectory(dynamic path) {
_cachedPath = null;
delegate.currentDirectory = path;
}
/// If the path is a multiroot uri, resolve to the actual path of the
/// underlying file system. Otherwise, return as is.
dynamic _resolve(dynamic path) {
Uri uri;
if (path == null) {
return null;
} else if (path is String) {
uri = Uri.parse(path);
} else if (path is Uri) {
uri = path;
} else if (path is FileSystemEntity) {
uri = path.uri;
} else {
throw ArgumentError('Invalid type for "path": ${(path as Object?)?.runtimeType}');
}
if (!uri.hasScheme || uri.scheme != _scheme) {
return path;
}
String? firstRootPath;
final String relativePath = delegate.path.joinAll(uri.pathSegments);
for (final String root in _roots) {
final String pathWithRoot = delegate.path.join(root, relativePath);
if (delegate.typeSync(pathWithRoot, followLinks: false) !=
FileSystemEntityType.notFound) {
return pathWithRoot;
}
firstRootPath ??= pathWithRoot;
}
// If not found, construct the path with the first root.
return firstRootPath!;
}
Uri _toMultiRootUri(Uri uri) {
if (uri.scheme != 'file') {
return uri;
}
final p.Context pathContext = delegate.path;
final bool isWindows = pathContext.style == p.Style.windows;
final String path = uri.toFilePath(windows: isWindows);
for (final String root in _roots) {
if (path.startsWith('$root${pathContext.separator}')) {
String pathWithoutRoot = path.substring(root.length + 1);
if (isWindows) {
// Convert the path from Windows style
pathWithoutRoot = p.url.joinAll(pathContext.split(pathWithoutRoot));
}
return Uri.parse('$_scheme:///$pathWithoutRoot');
}
}
return uri;
}
@override
String toString() =>
'MultiRootFileSystem(scheme = $_scheme, roots = $_roots, delegate = $delegate)';
}
abstract class MultiRootFileSystemEntity<T extends FileSystemEntity,
D extends io.FileSystemEntity> extends ForwardingFileSystemEntity<T, D> {
MultiRootFileSystemEntity({
required this.fileSystem,
required this.delegate,
});
@override
final D delegate;
@override
final MultiRootFileSystem fileSystem;
@override
File wrapFile(io.File delegate) => MultiRootFile(
fileSystem: fileSystem,
delegate: delegate,
);
@override
Directory wrapDirectory(io.Directory delegate) => MultiRootDirectory(
fileSystem: fileSystem,
delegate: delegate,
);
@override
Link wrapLink(io.Link delegate) => MultiRootLink(
fileSystem: fileSystem,
delegate: delegate,
);
@override
Uri get uri => fileSystem._toMultiRootUri(delegate.uri);
}
class MultiRootFile extends MultiRootFileSystemEntity<File, io.File>
with ForwardingFile {
MultiRootFile({
required super.fileSystem,
required super.delegate,
});
@override
String toString() =>
'MultiRootFile(fileSystem = $fileSystem, delegate = $delegate)';
}
class MultiRootDirectory
extends MultiRootFileSystemEntity<Directory, io.Directory>
with ForwardingDirectory<Directory> {
MultiRootDirectory({
required super.fileSystem,
required super.delegate,
});
// For the childEntity methods, we first obtain an instance of the entity
// from the underlying file system, then invoke childEntity() on it, then
// wrap in the ErrorHandling version.
@override
Directory childDirectory(String basename) =>
fileSystem.directory(fileSystem.path.join(delegate.path, basename));
@override
File childFile(String basename) =>
fileSystem.file(fileSystem.path.join(delegate.path, basename));
@override
Link childLink(String basename) =>
fileSystem.link(fileSystem.path.join(delegate.path, basename));
@override
String toString() =>
'MultiRootDirectory(fileSystem = $fileSystem, delegate = $delegate)';
}
class MultiRootLink
extends MultiRootFileSystemEntity<Link, io.Link>
with ForwardingLink {
MultiRootLink({
required super.fileSystem,
required super.delegate,
});
@override
String toString() =>
'MultiRootLink(fileSystem = $fileSystem, delegate = $delegate)';
}
| flutter/packages/flutter_tools/lib/src/base/multi_root_file_system.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/multi_root_file_system.dart",
"repo_id": "flutter",
"token_count": 2709
} | 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 'package:async/async.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:meta/meta.dart';
import 'package:pool/pool.dart';
import 'package:process/process.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../artifacts.dart';
import '../base/error_handling_io.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/utils.dart';
import '../cache.dart';
import '../convert.dart';
import '../reporting/reporting.dart';
import 'depfile.dart';
import 'exceptions.dart';
import 'file_store.dart';
import 'source.dart';
export 'source.dart';
/// A reasonable amount of files to open at the same time.
///
/// This number is somewhat arbitrary - it is difficult to detect whether
/// or not we'll run out of file descriptors when using async dart:io
/// APIs.
const int kMaxOpenFiles = 64;
/// Configuration for the build system itself.
class BuildSystemConfig {
/// Create a new [BuildSystemConfig].
const BuildSystemConfig({this.resourcePoolSize});
/// The maximum number of concurrent tasks the build system will run.
///
/// If not provided, defaults to [platform.numberOfProcessors].
final int? resourcePoolSize;
}
/// A Target describes a single step during a flutter build.
///
/// The target inputs are required to be files discoverable via a combination
/// of at least one of the environment values and zero or more local values.
///
/// To determine if the action for a target needs to be executed, the
/// [BuildSystem] computes a key of the file contents for both inputs and
/// outputs. This is tracked separately in the [FileStore]. The key may
/// be either an md5 hash of the file contents or a timestamp.
///
/// A Target has both implicit and explicit inputs and outputs. Only the
/// later are safe to evaluate before invoking the [buildAction]. For example,
/// a wildcard output pattern requires the outputs to exist before it can
/// glob files correctly.
///
/// - All listed inputs are considered explicit inputs.
/// - Outputs which are provided as [Source.pattern].
/// without wildcards are considered explicit.
/// - The remaining outputs are considered implicit.
///
/// For each target, executing its action creates a corresponding stamp file
/// which records both the input and output files. This file is read by
/// subsequent builds to determine which file hashes need to be checked. If the
/// stamp file is missing, the target's action is always rerun.
///
/// file: `example_target.stamp`
///
/// {
/// "inputs": [
/// "absolute/path/foo",
/// "absolute/path/bar",
/// ...
/// ],
/// "outputs": [
/// "absolute/path/fizz"
/// ]
/// }
///
/// ## Code review
///
/// ### Targets should only depend on files that are provided as inputs
///
/// Example: gen_snapshot must be provided as an input to the aot_elf
/// build steps, even though it isn't a source file. This ensures that changes
/// to the gen_snapshot binary (during a local engine build) correctly
/// trigger a corresponding build update.
///
/// Example: aot_elf has a dependency on the dill and packages file
/// produced by the kernel_snapshot step.
///
/// ### Targets should declare all outputs produced
///
/// If a target produces an output it should be listed, even if it is not
/// intended to be consumed by another target.
///
/// ## Unit testing
///
/// Most targets will invoke an external binary which makes unit testing
/// trickier. It is recommend that for unit testing that a Fake is used and
/// provided via the dependency injection system. a [Testbed] may be used to
/// set up the environment before the test is run. Unit tests should fully
/// exercise the rule, ensuring that the existing input and output verification
/// logic can run, as well as verifying it correctly handles provided defines
/// and meets any additional contracts present in the target.
abstract class Target {
const Target();
/// The user-readable name of the target.
///
/// This information is surfaced in the assemble commands and used as an
/// argument to build a particular target.
String get name;
/// A name that measurements can be categorized under for this [Target].
///
/// Unlike [name], this is not expected to be unique, so multiple targets
/// that are conceptually the same can share an analytics name.
///
/// If not provided, defaults to [name]
String get analyticsName => name;
/// The dependencies of this target.
List<Target> get dependencies;
/// The input [Source]s which are diffed to determine if a target should run.
List<Source> get inputs;
/// The output [Source]s which we attempt to verify are correctly produced.
List<Source> get outputs;
/// A list of zero or more depfiles, located directly under {BUILD_DIR}.
List<String> get depfiles => const <String>[];
/// A string that differentiates different build variants from each other
/// with regards to build flags or settings on the target. This string should
/// represent each build variant as a different unique value. If this value
/// changes between builds, the target will be invalidated and rebuilt.
///
/// By default, this returns null, which indicates there is only one build
/// variant, and the target won't invalidate or rebuild due to this property.
String? get buildKey => null;
/// Whether this target can be executed with the given [environment].
///
/// Returning `true` will cause [build] to be skipped. This is equivalent
/// to a build that produces no outputs.
bool canSkip(Environment environment) => false;
/// The action which performs this build step.
Future<void> build(Environment environment);
/// Create a [Node] with resolved inputs and outputs.
Node _toNode(Environment environment) {
final ResolvedFiles inputsFiles = resolveInputs(environment);
final ResolvedFiles outputFiles = resolveOutputs(environment);
return Node(
this,
inputsFiles.sources,
outputFiles.sources,
<Node>[
for (final Target target in dependencies) target._toNode(environment),
],
buildKey,
environment,
inputsFiles.containsNewDepfile,
);
}
/// Invoke to remove the stamp file if the [buildAction] threw an exception.
void clearStamp(Environment environment) {
final File stamp = _findStampFile(environment);
ErrorHandlingFileSystem.deleteIfExists(stamp);
}
void _writeStamp(
List<File> inputs,
List<File> outputs,
Environment environment,
) {
final File stamp = _findStampFile(environment);
final List<String> inputPaths = <String>[];
for (final File input in inputs) {
inputPaths.add(input.path);
}
final List<String> outputPaths = <String>[];
for (final File output in outputs) {
outputPaths.add(output.path);
}
final String? key = buildKey;
final Map<String, Object> result = <String, Object>{
'inputs': inputPaths,
'outputs': outputPaths,
if (key != null) 'buildKey': key,
};
if (!stamp.existsSync()) {
stamp.createSync();
}
stamp.writeAsStringSync(json.encode(result));
}
/// Resolve the set of input patterns and functions into a concrete list of
/// files.
ResolvedFiles resolveInputs(Environment environment) {
return _resolveConfiguration(inputs, depfiles, environment);
}
/// Find the current set of declared outputs, including wildcard directories.
///
/// The [implicit] flag controls whether it is safe to evaluate [Source]s
/// which uses functions, behaviors, or patterns.
ResolvedFiles resolveOutputs(Environment environment) {
return _resolveConfiguration(outputs, depfiles, environment, inputs: false);
}
/// Performs a fold across this target and its dependencies.
T fold<T>(T initialValue, T Function(T previousValue, Target target) combine) {
final T dependencyResult = dependencies.fold(
initialValue, (T prev, Target t) => t.fold(prev, combine));
return combine(dependencyResult, this);
}
/// Convert the target to a JSON structure appropriate for consumption by
/// external systems.
///
/// This requires constants from the [Environment] to resolve the paths of
/// inputs and the output stamp.
Map<String, Object> toJson(Environment environment) {
final String? key = buildKey;
return <String, Object>{
'name': name,
'dependencies': <String>[
for (final Target target in dependencies) target.name,
],
'inputs': <String>[
for (final File file in resolveInputs(environment).sources) file.path,
],
'outputs': <String>[
for (final File file in resolveOutputs(environment).sources) file.path,
],
if (key != null) 'buildKey': key,
'stamp': _findStampFile(environment).absolute.path,
};
}
/// Locate the stamp file for a particular target name and environment.
File _findStampFile(Environment environment) {
final String fileName = '$name.stamp';
return environment.buildDir.childFile(fileName);
}
static ResolvedFiles _resolveConfiguration(
List<Source> config,
List<String> depfiles,
Environment environment, {
bool inputs = true,
}) {
final SourceVisitor collector = SourceVisitor(environment, inputs);
for (final Source source in config) {
source.accept(collector);
}
depfiles.forEach(collector.visitDepfile);
return collector;
}
}
/// Target that contains multiple other targets.
///
/// This target does not do anything in its own [build]
/// and acts as a wrapper around multiple other targets.
class CompositeTarget extends Target {
CompositeTarget(this.dependencies);
@override
final List<Target> dependencies;
@override
String get name => '_composite';
@override
Future<void> build(Environment environment) async { }
@override
List<Source> get inputs => <Source>[];
@override
List<Source> get outputs => <Source>[];
}
/// The [Environment] defines several constants for use during the build.
///
/// The environment contains configuration and file paths that are safe to
/// depend on and reference during the build.
///
/// Example (Good):
///
/// Use the environment to determine where to write an output file.
///
/// ```dart
/// environment.buildDir.childFile('output')
/// ..createSync()
/// ..writeAsStringSync('output data');
/// ```
///
/// Example (Bad):
///
/// Use a hard-coded path or directory relative to the current working
/// directory to write an output file.
///
/// ```dart
/// globals.fs.file('build/linux/out')
/// ..createSync()
/// ..writeAsStringSync('output data');
/// ```
///
/// Example (Good):
///
/// Using the build mode to produce different output. The action
/// is still responsible for outputting a different file, as defined by the
/// corresponding output [Source].
///
/// ```dart
/// final BuildMode buildMode = getBuildModeFromDefines(environment.defines);
/// if (buildMode == BuildMode.debug) {
/// environment.buildDir.childFile('debug.output')
/// ..createSync()
/// ..writeAsStringSync('debug');
/// } else {
/// environment.buildDir.childFile('non_debug.output')
/// ..createSync()
/// ..writeAsStringSync('non_debug');
/// }
/// ```
class Environment {
/// Create a new [Environment] object.
///
/// [engineVersion] should be set to null for local engine builds.
factory Environment({
required Directory projectDir,
required Directory outputDir,
required Directory cacheDir,
required Directory flutterRootDir,
required FileSystem fileSystem,
required Logger logger,
required Artifacts artifacts,
required ProcessManager processManager,
required Platform platform,
required Usage usage,
required Analytics analytics,
String? engineVersion,
required bool generateDartPluginRegistry,
Directory? buildDir,
Map<String, String> defines = const <String, String>{},
Map<String, String> inputs = const <String, String>{},
}) {
// Compute a unique hash of this build's particular environment.
// Sort the keys by key so that the result is stable. We always
// include the engine and dart versions.
String buildPrefix;
final List<String> keys = defines.keys.toList()..sort();
final StringBuffer buffer = StringBuffer();
// The engine revision is `null` for local or custom engines.
if (engineVersion != null) {
buffer.write(engineVersion);
}
for (final String key in keys) {
buffer.write(key);
buffer.write(defines[key]);
}
buffer.write(outputDir.path);
final String output = buffer.toString();
final Digest digest = md5.convert(utf8.encode(output));
buildPrefix = hex.encode(digest.bytes);
final Directory rootBuildDir = buildDir ?? projectDir.childDirectory('build');
final Directory buildDirectory = rootBuildDir.childDirectory(buildPrefix);
return Environment._(
outputDir: outputDir,
projectDir: projectDir,
buildDir: buildDirectory,
rootBuildDir: rootBuildDir,
cacheDir: cacheDir,
defines: defines,
flutterRootDir: flutterRootDir,
fileSystem: fileSystem,
logger: logger,
artifacts: artifacts,
processManager: processManager,
platform: platform,
usage: usage,
analytics: analytics,
engineVersion: engineVersion,
inputs: inputs,
generateDartPluginRegistry: generateDartPluginRegistry,
);
}
/// Create a new [Environment] object for unit testing.
///
/// Any directories not provided will fallback to a [testDirectory]
@visibleForTesting
factory Environment.test(Directory testDirectory, {
Directory? projectDir,
Directory? outputDir,
Directory? cacheDir,
Directory? flutterRootDir,
Directory? buildDir,
Map<String, String> defines = const <String, String>{},
Map<String, String> inputs = const <String, String>{},
String? engineVersion,
Platform? platform,
Usage? usage,
Analytics? analytics,
bool generateDartPluginRegistry = false,
required FileSystem fileSystem,
required Logger logger,
required Artifacts artifacts,
required ProcessManager processManager,
}) {
return Environment(
projectDir: projectDir ?? testDirectory,
outputDir: outputDir ?? testDirectory,
cacheDir: cacheDir ?? testDirectory,
flutterRootDir: flutterRootDir ?? testDirectory,
buildDir: buildDir,
defines: defines,
inputs: inputs,
fileSystem: fileSystem,
logger: logger,
artifacts: artifacts,
processManager: processManager,
platform: platform ?? FakePlatform(),
usage: usage ?? TestUsage(),
analytics: analytics ?? const NoOpAnalytics(),
engineVersion: engineVersion,
generateDartPluginRegistry: generateDartPluginRegistry,
);
}
Environment._({
required this.outputDir,
required this.projectDir,
required this.buildDir,
required this.rootBuildDir,
required this.cacheDir,
required this.defines,
required this.flutterRootDir,
required this.processManager,
required this.platform,
required this.logger,
required this.fileSystem,
required this.artifacts,
required this.usage,
required this.analytics,
this.engineVersion,
required this.inputs,
required this.generateDartPluginRegistry,
});
/// The [Source] value which is substituted with the path to [projectDir].
static const String kProjectDirectory = '{PROJECT_DIR}';
/// The [Source] value which is substituted with the path to [buildDir].
static const String kBuildDirectory = '{BUILD_DIR}';
/// The [Source] value which is substituted with the path to [cacheDir].
static const String kCacheDirectory = '{CACHE_DIR}';
/// The [Source] value which is substituted with a path to the flutter root.
static const String kFlutterRootDirectory = '{FLUTTER_ROOT}';
/// The [Source] value which is substituted with a path to [outputDir].
static const String kOutputDirectory = '{OUTPUT_DIR}';
/// The `PROJECT_DIR` environment variable.
///
/// This should be root of the flutter project where a pubspec and dart files
/// can be located.
final Directory projectDir;
/// The `BUILD_DIR` environment variable.
///
/// The root of the output directory where build step intermediates and
/// outputs are written. Current usages of assemble configure ths to be
/// a unique directory under `.dart_tool/flutter_build`, though it can
/// be placed anywhere. The uniqueness is only enforced by callers, and
/// is currently done by hashing the build configuration.
final Directory buildDir;
/// The `CACHE_DIR` environment variable.
///
/// Defaults to `{FLUTTER_ROOT}/bin/cache`. The root of the artifact cache for
/// the flutter tool.
final Directory cacheDir;
/// The `FLUTTER_ROOT` environment variable.
///
/// Defaults to the value of [Cache.flutterRoot].
final Directory flutterRootDir;
/// The `OUTPUT_DIR` environment variable.
///
/// Must be provided to configure the output location for the final artifacts.
final Directory outputDir;
/// Additional configuration passed to the build targets.
///
/// Setting values here forces a unique build directory to be chosen
/// which prevents the config from leaking into different builds.
final Map<String, String> defines;
/// Additional input files passed to the build targets.
///
/// Unlike [defines], values set here do not force a new build configuration.
/// This is useful for passing file inputs that may have changing paths
/// without running builds from scratch.
///
/// It is the responsibility of the [Target] to declare that an input was
/// used in an output depfile.
final Map<String, String> inputs;
/// The root build directory shared by all builds.
final Directory rootBuildDir;
final ProcessManager processManager;
final Platform platform;
final Logger logger;
final Artifacts artifacts;
final FileSystem fileSystem;
final Usage usage;
final Analytics analytics;
/// The version of the current engine, or `null` if built with a local engine.
final String? engineVersion;
/// Whether to generate the Dart plugin registry.
/// When [true], the main entrypoint is wrapped and the wrapper becomes
/// the new entrypoint.
final bool generateDartPluginRegistry;
late final DepfileService depFileService = DepfileService(
logger: logger,
fileSystem: fileSystem,
);
}
/// The result information from the build system.
class BuildResult {
BuildResult({
required this.success,
this.exceptions = const <String, ExceptionMeasurement>{},
this.performance = const <String, PerformanceMeasurement>{},
this.inputFiles = const <File>[],
this.outputFiles = const <File>[],
});
final bool success;
final Map<String, ExceptionMeasurement> exceptions;
final Map<String, PerformanceMeasurement> performance;
final List<File> inputFiles;
final List<File> outputFiles;
bool get hasException => exceptions.isNotEmpty;
}
/// The build system is responsible for invoking and ordering [Target]s.
abstract class BuildSystem {
/// Const constructor to allow subclasses to be const.
const BuildSystem();
/// Build [target] and all of its dependencies.
Future<BuildResult> build(
Target target,
Environment environment, {
BuildSystemConfig buildSystemConfig = const BuildSystemConfig(),
});
/// Perform an incremental build of [target] and all of its dependencies.
///
/// If [previousBuild] is not provided, a new incremental build is
/// initialized.
Future<BuildResult> buildIncremental(
Target target,
Environment environment,
BuildResult? previousBuild,
);
}
class FlutterBuildSystem extends BuildSystem {
const FlutterBuildSystem({
required FileSystem fileSystem,
required Platform platform,
required Logger logger,
}) : _fileSystem = fileSystem,
_platform = platform,
_logger = logger;
final FileSystem _fileSystem;
final Platform _platform;
final Logger _logger;
@override
Future<BuildResult> build(
Target target,
Environment environment, {
BuildSystemConfig buildSystemConfig = const BuildSystemConfig(),
}) async {
environment.buildDir.createSync(recursive: true);
environment.outputDir.createSync(recursive: true);
// Load file store from previous builds.
final File cacheFile = environment.buildDir.childFile(FileStore.kFileCache);
final FileStore fileCache = FileStore(
cacheFile: cacheFile,
logger: _logger,
)..initialize();
// Perform sanity checks on build.
checkCycles(target);
final Node node = target._toNode(environment);
final _BuildInstance buildInstance = _BuildInstance(
environment: environment,
fileCache: fileCache,
buildSystemConfig: buildSystemConfig,
logger: _logger,
fileSystem: _fileSystem,
platform: _platform,
);
bool passed = true;
try {
passed = await buildInstance.invokeTarget(node);
} finally {
// Always persist the file cache to disk.
fileCache.persist();
}
// This is a bit of a hack, due to various parts of
// the flutter tool writing these files unconditionally. Since Xcode uses
// timestamps to track files, this leads to unnecessary rebuilds if they
// are included. Once all the places that write these files have been
// tracked down and moved into assemble, these checks should be removable.
// We also remove files under .dart_tool, since these are intermediaries
// and don't need to be tracked by external systems.
{
buildInstance.inputFiles.removeWhere((String path, File file) {
return path.contains('.flutter-plugins') ||
path.contains('xcconfig') ||
path.contains('.dart_tool');
});
buildInstance.outputFiles.removeWhere((String path, File file) {
return path.contains('.flutter-plugins') ||
path.contains('xcconfig') ||
path.contains('.dart_tool');
});
}
trackSharedBuildDirectory(
environment, _fileSystem, buildInstance.outputFiles,
);
environment.buildDir.childFile('outputs.json')
.writeAsStringSync(json.encode(buildInstance.outputFiles.keys.toList()));
return BuildResult(
success: passed,
exceptions: buildInstance.exceptionMeasurements,
performance: buildInstance.stepTimings,
inputFiles: buildInstance.inputFiles.values.toList()
..sort((File a, File b) => a.path.compareTo(b.path)),
outputFiles: buildInstance.outputFiles.values.toList()
..sort((File a, File b) => a.path.compareTo(b.path)),
);
}
static final Expando<FileStore> _incrementalFileStore = Expando<FileStore>();
@override
Future<BuildResult> buildIncremental(
Target target,
Environment environment,
BuildResult? previousBuild,
) async {
environment.buildDir.createSync(recursive: true);
environment.outputDir.createSync(recursive: true);
FileStore? fileCache;
if (previousBuild == null || _incrementalFileStore[previousBuild] == null) {
final File cacheFile = environment.buildDir.childFile(FileStore.kFileCache);
fileCache = FileStore(
cacheFile: cacheFile,
logger: _logger,
strategy: FileStoreStrategy.timestamp,
)..initialize();
} else {
fileCache = _incrementalFileStore[previousBuild];
}
final Node node = target._toNode(environment);
final _BuildInstance buildInstance = _BuildInstance(
environment: environment,
fileCache: fileCache!,
buildSystemConfig: const BuildSystemConfig(),
logger: _logger,
fileSystem: _fileSystem,
platform: _platform,
);
bool passed = true;
try {
passed = await buildInstance.invokeTarget(node);
} finally {
fileCache.persistIncremental();
}
final BuildResult result = BuildResult(
success: passed,
exceptions: buildInstance.exceptionMeasurements,
performance: buildInstance.stepTimings,
);
_incrementalFileStore[result] = fileCache;
return result;
}
/// Write the identifier of the last build into the output directory and
/// remove the previous build's output.
///
/// The build identifier is the basename of the build directory where
/// outputs and intermediaries are written, under `.dart_tool/flutter_build`.
/// This is computed from a hash of the build's configuration.
///
/// This identifier is used to perform a targeted cleanup of the last output
/// files, if these were not already covered by the built-in cleanup. This
/// cleanup is only necessary when multiple different build configurations
/// output to the same directory.
@visibleForTesting
void trackSharedBuildDirectory(
Environment environment,
FileSystem fileSystem,
Map<String, File> currentOutputs,
) {
final String currentBuildId = fileSystem.path.basename(environment.buildDir.path);
final File lastBuildIdFile = environment.outputDir.childFile('.last_build_id');
if (!lastBuildIdFile.existsSync()) {
lastBuildIdFile.parent.createSync(recursive: true);
lastBuildIdFile.writeAsStringSync(currentBuildId);
// No config file, either output was cleaned or this is the first build.
return;
}
final String lastBuildId = lastBuildIdFile.readAsStringSync().trim();
if (lastBuildId == currentBuildId) {
// The last build was the same configuration as the current build
return;
}
// Update the output dir with the latest config.
lastBuildIdFile
..createSync()
..writeAsStringSync(currentBuildId);
final File outputsFile = environment.buildDir
.parent
.childDirectory(lastBuildId)
.childFile('outputs.json');
if (!outputsFile.existsSync()) {
// There is no output list. This could happen if the user manually
// edited .last_config or deleted .dart_tool.
return;
}
final List<String> lastOutputs = (json.decode(outputsFile.readAsStringSync()) as List<Object?>)
.cast<String>();
for (final String lastOutput in lastOutputs) {
if (!currentOutputs.containsKey(lastOutput)) {
final File lastOutputFile = fileSystem.file(lastOutput);
ErrorHandlingFileSystem.deleteIfExists(lastOutputFile);
}
}
}
}
/// An active instance of a build.
class _BuildInstance {
_BuildInstance({
required this.environment,
required this.fileCache,
required this.buildSystemConfig,
required this.logger,
required this.fileSystem,
Platform? platform,
})
: resourcePool = Pool(buildSystemConfig.resourcePoolSize ?? platform?.numberOfProcessors ?? 1);
final Logger logger;
final FileSystem fileSystem;
final BuildSystemConfig buildSystemConfig;
final Pool resourcePool;
final Map<String, AsyncMemoizer<bool>> pending = <String, AsyncMemoizer<bool>>{};
final Environment environment;
final FileStore fileCache;
final Map<String, File> inputFiles = <String, File>{};
final Map<String, File> outputFiles = <String, File>{};
// Timings collected during target invocation.
final Map<String, PerformanceMeasurement> stepTimings = <String, PerformanceMeasurement>{};
// Exceptions caught during the build process.
final Map<String, ExceptionMeasurement> exceptionMeasurements = <String, ExceptionMeasurement>{};
Future<bool> invokeTarget(Node node) async {
final List<bool> results = await Future.wait(node.dependencies.map(invokeTarget));
if (results.any((bool result) => !result)) {
return false;
}
final AsyncMemoizer<bool> memoizer = pending[node.target.name] ??= AsyncMemoizer<bool>();
return memoizer.runOnce(() => _invokeInternal(node));
}
Future<bool> _invokeInternal(Node node) async {
final PoolResource resource = await resourcePool.request();
final Stopwatch stopwatch = Stopwatch()..start();
bool succeeded = true;
bool skipped = false;
// The build system produces a list of aggregate input and output
// files for the overall build. This list is provided to a hosting build
// system, such as Xcode, to configure logic for when to skip the
// rule/phase which contains the flutter build.
//
// When looking at the inputs and outputs for the individual rules, we need
// to be careful to remove inputs that were actually output from previous
// build steps. This indicates that the file is an intermediary. If
// these files are included as both inputs and outputs then it isn't
// possible to construct a DAG describing the build.
void updateGraph() {
for (final File output in node.outputs) {
outputFiles[output.path] = output;
}
for (final File input in node.inputs) {
final String resolvedPath = input.absolute.path;
if (outputFiles.containsKey(resolvedPath)) {
continue;
}
inputFiles[resolvedPath] = input;
}
}
try {
// If we're missing a depfile, wait until after evaluating the target to
// compute changes.
final bool canSkip = !node.missingDepfile &&
node.computeChanges(environment, fileCache, fileSystem, logger);
if (canSkip) {
skipped = true;
logger.printTrace('Skipping target: ${node.target.name}');
updateGraph();
return succeeded;
}
// Clear old inputs. These will be replaced with new inputs/outputs
// after the target is run. In the case of a runtime skip, each list
// must be empty to ensure the previous outputs are purged.
node.inputs.clear();
node.outputs.clear();
// Check if we can skip via runtime dependencies.
final bool runtimeSkip = node.target.canSkip(environment);
if (runtimeSkip) {
logger.printTrace('Skipping target: ${node.target.name}');
skipped = true;
} else {
logger.printTrace('${node.target.name}: Starting due to ${node.invalidatedReasons}');
await node.target.build(environment);
logger.printTrace('${node.target.name}: Complete');
node.inputs.addAll(node.target.resolveInputs(environment).sources);
node.outputs.addAll(node.target.resolveOutputs(environment).sources);
}
// If we were missing the depfile, resolve input files after executing the
// target so that all file hashes are up to date on the next run.
if (node.missingDepfile) {
fileCache.diffFileList(node.inputs);
}
// Always update hashes for output files.
fileCache.diffFileList(node.outputs);
node.target._writeStamp(node.inputs, node.outputs, environment);
updateGraph();
// Delete outputs from previous stages that are no longer a part of the
// build.
for (final String previousOutput in node.previousOutputs) {
if (outputFiles.containsKey(previousOutput)) {
continue;
}
final File previousFile = fileSystem.file(previousOutput);
ErrorHandlingFileSystem.deleteIfExists(previousFile);
}
} on Exception catch (exception, stackTrace) {
node.target.clearStamp(environment);
succeeded = false;
skipped = false;
exceptionMeasurements[node.target.name] = ExceptionMeasurement(
node.target.name, exception, stackTrace, fatal: true);
} finally {
resource.release();
stopwatch.stop();
stepTimings[node.target.name] = PerformanceMeasurement(
target: node.target.name,
elapsedMilliseconds: stopwatch.elapsedMilliseconds,
skipped: skipped,
succeeded: succeeded,
analyticsName: node.target.analyticsName,
);
}
return succeeded;
}
}
/// Helper class to collect exceptions.
class ExceptionMeasurement {
ExceptionMeasurement(this.target, this.exception, this.stackTrace, {this.fatal = false});
final String target;
final Object? exception;
final StackTrace stackTrace;
/// Whether this exception was a fatal build system error.
final bool fatal;
@override
String toString() => 'target: $target\nexception:$exception\n$stackTrace';
}
/// Helper class to collect measurement data.
class PerformanceMeasurement {
PerformanceMeasurement({
required this.target,
required this.elapsedMilliseconds,
required this.skipped,
required this.succeeded,
required this.analyticsName,
});
final int elapsedMilliseconds;
final String target;
final bool skipped;
final bool succeeded;
final String analyticsName;
}
/// Check if there are any dependency cycles in the target.
///
/// Throws a [CycleException] if one is encountered.
void checkCycles(Target initial) {
void checkInternal(Target target, Set<Target> visited, Set<Target> stack) {
if (stack.contains(target)) {
throw CycleException(stack..add(target));
}
if (visited.contains(target)) {
return;
}
visited.add(target);
stack.add(target);
for (final Target dependency in target.dependencies) {
checkInternal(dependency, visited, stack);
}
stack.remove(target);
}
checkInternal(initial, <Target>{}, <Target>{});
}
/// Verifies that all files exist and are in a subdirectory of [Environment.buildDir].
void verifyOutputDirectories(List<File> outputs, Environment environment, Target target) {
final String buildDirectory = environment.buildDir.resolveSymbolicLinksSync();
final String projectDirectory = environment.projectDir.resolveSymbolicLinksSync();
final List<File> missingOutputs = <File>[];
for (final File sourceFile in outputs) {
if (!sourceFile.existsSync()) {
missingOutputs.add(sourceFile);
continue;
}
final String path = sourceFile.path;
if (!path.startsWith(buildDirectory) && !path.startsWith(projectDirectory)) {
throw MisplacedOutputException(path, target.name);
}
}
if (missingOutputs.isNotEmpty) {
throw MissingOutputException(missingOutputs, target.name);
}
}
/// A node in the build graph.
class Node {
factory Node(
Target target,
List<File> inputs,
List<File> outputs,
List<Node> dependencies,
String? buildKey,
Environment environment,
bool missingDepfile,
) {
final File stamp = target._findStampFile(environment);
Map<String, Object?>? stampValues;
// If the stamp file doesn't exist, we haven't run this step before and
// all inputs were added.
if (stamp.existsSync()) {
final String content = stamp.readAsStringSync();
if (content.isEmpty) {
stamp.deleteSync();
} else {
try {
stampValues = castStringKeyedMap(json.decode(content));
} on FormatException {
// The json is malformed in some way.
}
}
}
if (stampValues != null) {
final String? previousBuildKey = stampValues['buildKey'] as String?;
final Object? stampInputs = stampValues['inputs'];
final Object? stampOutputs = stampValues['outputs'];
if (stampInputs is List<Object?> && stampOutputs is List<Object?>) {
final Set<String> previousInputs = stampInputs.whereType<String>().toSet();
final Set<String> previousOutputs = stampOutputs.whereType<String>().toSet();
return Node.withStamp(
target,
inputs,
previousInputs,
outputs,
previousOutputs,
dependencies,
buildKey,
previousBuildKey,
missingDepfile,
);
}
}
return Node.withNoStamp(
target,
inputs,
outputs,
dependencies,
buildKey,
missingDepfile,
);
}
Node.withNoStamp(
this.target,
this.inputs,
this.outputs,
this.dependencies,
this.buildKey,
this.missingDepfile,
) : previousInputs = <String>{},
previousOutputs = <String>{},
previousBuildKey = null,
_dirty = true;
Node.withStamp(
this.target,
this.inputs,
this.previousInputs,
this.outputs,
this.previousOutputs,
this.dependencies,
this.buildKey,
this.previousBuildKey,
this.missingDepfile,
) : _dirty = false;
/// The resolved input files.
///
/// These files may not yet exist if they are produced by previous steps.
final List<File> inputs;
/// The resolved output files.
///
/// These files may not yet exist if the target hasn't run yet.
final List<File> outputs;
/// The current build key of the target
///
/// See `buildKey` in the `Target` class for more information.
final String? buildKey;
/// Whether this node is missing a depfile.
///
/// This requires an additional pass of source resolution after the target
/// has been executed.
final bool missingDepfile;
/// The target definition which contains the build action to invoke.
final Target target;
/// All of the nodes that this one depends on.
final List<Node> dependencies;
/// Output file paths from the previous invocation of this build node.
final Set<String> previousOutputs;
/// Input file paths from the previous invocation of this build node.
final Set<String> previousInputs;
/// The buildKey from the previous invocation of this build node.
///
/// See `buildKey` in the `Target` class for more information.
final String? previousBuildKey;
/// One or more reasons why a task was invalidated.
///
/// May be empty if the task was skipped.
final Map<InvalidatedReasonKind, InvalidatedReason> invalidatedReasons = <InvalidatedReasonKind, InvalidatedReason>{};
/// Whether this node needs an action performed.
bool get dirty => _dirty;
bool _dirty = false;
InvalidatedReason _invalidate(InvalidatedReasonKind kind) {
return invalidatedReasons[kind] ??= InvalidatedReason(kind);
}
/// Collect hashes for all inputs to determine if any have changed.
///
/// Returns whether this target can be skipped.
bool computeChanges(
Environment environment,
FileStore fileStore,
FileSystem fileSystem,
Logger logger,
) {
if (buildKey != previousBuildKey) {
_invalidate(InvalidatedReasonKind.buildKeyChanged);
_dirty = true;
}
final Set<String> currentOutputPaths = <String>{
for (final File file in outputs) file.path,
};
// For each input, first determine if we've already computed the key
// for it. Then collect it to be sent off for diffing as a group.
final List<File> sourcesToDiff = <File>[];
final List<File> missingInputs = <File>[];
for (final File file in inputs) {
if (!file.existsSync()) {
missingInputs.add(file);
continue;
}
final String absolutePath = file.path;
final String? previousAssetKey = fileStore.previousAssetKeys[absolutePath];
if (fileStore.currentAssetKeys.containsKey(absolutePath)) {
final String? currentHash = fileStore.currentAssetKeys[absolutePath];
if (currentHash != previousAssetKey) {
final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.inputChanged);
reason.data.add(absolutePath);
_dirty = true;
}
} else {
sourcesToDiff.add(file);
}
}
// For each output, first determine if we've already computed the key
// for it. Then collect it to be sent off for hashing as a group.
for (final String previousOutput in previousOutputs) {
// output paths changed.
if (!currentOutputPaths.contains(previousOutput)) {
_dirty = true;
final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.outputSetChanged);
reason.data.add(previousOutput);
// if this isn't a current output file there is no reason to compute the key.
continue;
}
final File file = fileSystem.file(previousOutput);
if (!file.existsSync()) {
final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.outputMissing);
reason.data.add(file.path);
_dirty = true;
continue;
}
final String absolutePath = file.path;
final String? previousHash = fileStore.previousAssetKeys[absolutePath];
if (fileStore.currentAssetKeys.containsKey(absolutePath)) {
final String? currentHash = fileStore.currentAssetKeys[absolutePath];
if (currentHash != previousHash) {
final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.outputChanged);
reason.data.add(absolutePath);
_dirty = true;
}
} else {
sourcesToDiff.add(file);
}
}
// If we depend on a file that doesn't exist on disk, mark the build as
// dirty. if the rule is not correctly specified, this will result in it
// always being rerun.
if (missingInputs.isNotEmpty) {
_dirty = true;
final String missingMessage = missingInputs.map((File file) => file.path).join(', ');
logger.printTrace('invalidated build due to missing files: $missingMessage');
final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.inputMissing);
reason.data.addAll(missingInputs.map((File file) => file.path));
}
// If we have files to diff, compute them asynchronously and then
// update the result.
if (sourcesToDiff.isNotEmpty) {
final List<File> dirty = fileStore.diffFileList(sourcesToDiff);
if (dirty.isNotEmpty) {
final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.inputChanged);
reason.data.addAll(dirty.map((File file) => file.path));
_dirty = true;
}
}
return !_dirty;
}
}
/// Data about why a target was re-run.
class InvalidatedReason {
InvalidatedReason(this.kind);
final InvalidatedReasonKind kind;
/// Absolute file paths of inputs or outputs, depending on [kind].
final List<String> data = <String>[];
@override
String toString() {
return switch (kind) {
InvalidatedReasonKind.inputMissing => 'The following inputs were missing: ${data.join(',')}',
InvalidatedReasonKind.inputChanged => 'The following inputs have updated contents: ${data.join(',')}',
InvalidatedReasonKind.outputChanged => 'The following outputs have updated contents: ${data.join(',')}',
InvalidatedReasonKind.outputMissing => 'The following outputs were missing: ${data.join(',')}',
InvalidatedReasonKind.outputSetChanged => 'The following outputs were removed from the output set: ${data.join(',')}',
InvalidatedReasonKind.buildKeyChanged => 'The target build key changed.',
};
}
}
/// A description of why a target was rerun.
enum InvalidatedReasonKind {
/// An input file that was expected is missing. This can occur when using
/// depfile dependencies, or if a target is incorrectly specified.
inputMissing,
/// An input file has an updated key.
inputChanged,
/// An output file has an updated key.
outputChanged,
/// An output file that is expected is missing.
outputMissing,
/// The set of expected output files changed.
outputSetChanged,
/// The build key changed
buildKeyChanged,
}
| flutter/packages/flutter_tools/lib/src/build_system/build_system.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/build_system/build_system.dart",
"repo_id": "flutter",
"token_count": 13884
} | 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 '../../base/file_system.dart';
import '../../convert.dart';
import '../../localizations/gen_l10n.dart';
import '../../localizations/localizations_utils.dart';
import '../build_system.dart';
import '../depfile.dart';
const String _kDependenciesFileName = 'gen_l10n_inputs_and_outputs.json';
/// A build step that runs the generate localizations script from
/// dev/tool/localizations.
class GenerateLocalizationsTarget extends Target {
const GenerateLocalizationsTarget();
@override
List<Target> get dependencies => <Target>[];
@override
List<Source> get inputs => <Source>[
// This is added as a convenience for developing the tool.
const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/localizations.dart'),
];
@override
String get name => 'gen_localizations';
@override
List<Source> get outputs => <Source>[];
@override
List<String> get depfiles => <String>['gen_localizations.d'];
@override
bool canSkip(Environment environment) {
final File configFile = environment.projectDir.childFile('l10n.yaml');
return !configFile.existsSync();
}
@override
Future<void> build(Environment environment) async {
final File configFile = environment.projectDir.childFile('l10n.yaml');
assert(configFile.existsSync());
// Keep in mind that this is also defined in the following locations:
// 1. flutter_tools/lib/src/commands/generate_localizations.dart
// 2. flutter_tools/test/general.shard/build_system/targets/localizations_test.dart
// Keep the value consistent in all three locations to ensure behavior is the
// same across "flutter gen-l10n" and "flutter run".
final String defaultArbDir = environment.fileSystem.path.join('lib', 'l10n');
final LocalizationOptions options = parseLocalizationsOptionsFromYAML(
file: configFile,
logger: environment.logger,
defaultArbDir: defaultArbDir,
);
await generateLocalizations(
logger: environment.logger,
options: options,
projectDir: environment.projectDir,
dependenciesDir: environment.buildDir,
fileSystem: environment.fileSystem,
artifacts: environment.artifacts,
processManager: environment.processManager,
);
final Map<String, Object?> dependencies = json.decode(
environment.buildDir.childFile(_kDependenciesFileName).readAsStringSync()
) as Map<String, Object?>;
final List<Object?>? inputs = dependencies['inputs'] as List<Object?>?;
final List<Object?>? outputs = dependencies['outputs'] as List<Object?>?;
final Depfile depfile = Depfile(
<File>[
configFile,
if (inputs != null)
for (final Object inputFile in inputs.whereType<Object>())
environment.fileSystem.file(inputFile),
],
<File>[
if (outputs != null)
for (final Object outputFile in outputs.whereType<Object>())
environment.fileSystem.file(outputFile),
],
);
environment.depFileService.writeToFile(
depfile,
environment.buildDir.childFile('gen_localizations.d'),
);
}
}
| flutter/packages/flutter_tools/lib/src/build_system/targets/localizations.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/localizations.dart",
"repo_id": "flutter",
"token_count": 1126
} | 734 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../dart/analysis.dart';
import 'analyze_base.dart';
class AnalyzeOnce extends AnalyzeBase {
AnalyzeOnce(
super.argResults,
List<Directory> repoPackages, {
required super.fileSystem,
required super.logger,
required super.platform,
required super.processManager,
required super.terminal,
required super.artifacts,
required super.suppressAnalytics,
this.workingDirectory,
}) : super(
repoPackages: repoPackages,
);
/// The working directory for testing analysis using dartanalyzer.
final Directory? workingDirectory;
@override
Future<void> analyze() async {
final String currentDirectory =
(workingDirectory ?? fileSystem.currentDirectory).path;
final Set<String> items = findDirectories(argResults, fileSystem);
if (isFlutterRepo) {
// check for conflicting dependencies
final PackageDependencyTracker dependencies = PackageDependencyTracker();
dependencies.checkForConflictingDependencies(repoPackages, dependencies);
items.add(flutterRoot);
if (argResults.wasParsed('current-package') && (argResults['current-package'] as bool)) {
items.add(currentDirectory);
}
} else {
if ((argResults['current-package'] as bool) && items.isEmpty) {
items.add(currentDirectory);
}
}
if (items.isEmpty) {
throwToolExit('Nothing to analyze.', exitCode: 0);
}
final Completer<void> analysisCompleter = Completer<void>();
final List<AnalysisError> errors = <AnalysisError>[];
final AnalysisServer server = AnalysisServer(
sdkPath,
items.toList(),
fileSystem: fileSystem,
platform: platform,
logger: logger,
processManager: processManager,
terminal: terminal,
protocolTrafficLog: protocolTrafficLog,
suppressAnalytics: suppressAnalytics,
);
Stopwatch? timer;
Status? progress;
try {
StreamSubscription<bool>? subscription;
void handleAnalysisStatus(bool isAnalyzing) {
if (!isAnalyzing) {
analysisCompleter.complete();
subscription?.cancel();
subscription = null;
}
}
subscription = server.onAnalyzing.listen((bool isAnalyzing) => handleAnalysisStatus(isAnalyzing));
void handleAnalysisErrors(FileAnalysisErrors fileErrors) {
fileErrors.errors.removeWhere((AnalysisError error) => error.type == 'TODO');
errors.addAll(fileErrors.errors);
}
server.onErrors.listen(handleAnalysisErrors);
await server.start();
// Completing the future in the callback can't fail.
unawaited(server.onExit.then<void>((int? exitCode) {
if (!analysisCompleter.isCompleted) {
analysisCompleter.completeError(
// Include the last 20 lines of server output in exception message
Exception(
'analysis server exited with code $exitCode and output:\n${server.getLogs(20)}',
),
);
}
}));
// collect results
timer = Stopwatch()..start();
final String message = items.length > 1
? '${items.length} ${items.length == 1 ? 'item' : 'items'}'
: fileSystem.path.basename(items.first);
progress = argResults['preamble'] == true
? logger.startProgress(
'Analyzing $message...',
)
: null;
await analysisCompleter.future;
} finally {
await server.dispose();
progress?.cancel();
timer?.stop();
}
// emit benchmarks
if (isBenchmarking) {
writeBenchmark(timer, errors.length);
}
// --write
dumpErrors(errors.map<String>((AnalysisError error) => error.toLegacyString()));
// report errors
if (errors.isNotEmpty && (argResults['preamble'] as bool)) {
logger.printStatus('');
}
errors.sort();
for (final AnalysisError error in errors) {
logger.printStatus(error.toString(), hangingIndent: 7);
}
final int errorCount = errors.length;
final String seconds = (timer.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
final String errorsMessage = AnalyzeBase.generateErrorsMessage(
issueCount: errorCount,
seconds: seconds,
);
if (errorCount > 0) {
logger.printStatus('');
throwToolExit(errorsMessage, exitCode: _isFatal(errors) ? 1 : 0);
}
if (argResults['congratulate'] as bool) {
logger.printStatus(errorsMessage);
}
if (server.didServerErrorOccur) {
throwToolExit('Server error(s) occurred. (ran in ${seconds}s)');
}
}
bool _isFatal(List<AnalysisError> errors) {
for (final AnalysisError error in errors) {
final AnalysisSeverity severityLevel = error.writtenError.severityLevel;
if (severityLevel == AnalysisSeverity.error) {
return true;
}
if (severityLevel == AnalysisSeverity.warning && argResults['fatal-warnings'] as bool) {
return true;
}
if (severityLevel == AnalysisSeverity.info && argResults['fatal-infos'] as bool) {
return true;
}
}
return false;
}
}
| flutter/packages/flutter_tools/lib/src/commands/analyze_once.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/analyze_once.dart",
"repo_id": "flutter",
"token_count": 2051
} | 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:meta/meta.dart';
import '../base/analyze_size.dart';
import '../base/common.dart';
import '../base/os.dart';
import '../build_info.dart';
import '../cache.dart';
import '../features.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../runner/flutter_command.dart' show FlutterCommandResult;
import '../windows/build_windows.dart';
import '../windows/visual_studio.dart';
import 'build.dart';
/// A command to build a windows desktop target through a build shell script.
class BuildWindowsCommand extends BuildSubCommand {
BuildWindowsCommand({
required super.logger,
required OperatingSystemUtils operatingSystemUtils,
bool verboseHelp = false,
}) : _operatingSystemUtils = operatingSystemUtils,
super(verboseHelp: verboseHelp) {
addCommonDesktopBuildOptions(verboseHelp: verboseHelp);
}
final OperatingSystemUtils _operatingSystemUtils;
@override
final String name = 'windows';
@override
bool get hidden => !featureFlags.isWindowsEnabled || !globals.platform.isWindows;
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{
DevelopmentArtifact.windows,
};
@override
String get description => 'Build a Windows desktop application.';
@visibleForTesting
VisualStudio? visualStudioOverride;
@override
Future<FlutterCommandResult> runCommand() async {
final FlutterProject flutterProject = FlutterProject.current();
final BuildInfo buildInfo = await getBuildInfo();
if (!featureFlags.isWindowsEnabled) {
throwToolExit('"build windows" is not currently supported. To enable, run "flutter config --enable-windows-desktop".');
}
if (!globals.platform.isWindows) {
throwToolExit('"build windows" only supported on Windows hosts.');
}
final String defaultTargetPlatform = (_operatingSystemUtils.hostPlatform == HostPlatform.windows_arm64) ?
'windows-arm64' : 'windows-x64';
final TargetPlatform targetPlatform = getTargetPlatformForName(defaultTargetPlatform);
displayNullSafetyMode(buildInfo);
await buildWindows(
flutterProject.windows,
buildInfo,
targetPlatform,
target: targetFile,
visualStudioOverride: visualStudioOverride,
sizeAnalyzer: SizeAnalyzer(
fileSystem: globals.fs,
logger: globals.logger,
appFilenamePattern: 'app.so',
flutterUsage: globals.flutterUsage,
analytics: analytics,
),
);
return FlutterCommandResult.success();
}
}
| flutter/packages/flutter_tools/lib/src/commands/build_windows.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/build_windows.dart",
"repo_id": "flutter",
"token_count": 873
} | 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 '../base/common.dart';
import '../base/file_system.dart';
import '../cache.dart';
import '../globals.dart' as globals;
import '../runner/flutter_command.dart';
import '../template.dart';
class IdeConfigCommand extends FlutterCommand {
IdeConfigCommand() {
argParser.addFlag(
'overwrite',
help: 'When performing operations, overwrite existing files.',
);
argParser.addFlag(
'update-templates',
negatable: false,
help: 'Update the templates in the template directory from the current '
'configuration files. This is the opposite of what $name usually does. '
'Will search the flutter tree for *.iml files and copy any missing ones '
'into the template directory. If "--overwrite" is also specified, it will '
'update any out-of-date files, and remove any deleted files from the '
'template directory.',
);
argParser.addFlag(
'with-root-module',
defaultsTo: true,
help: 'Also create module that corresponds to the root of Flutter tree. '
'This makes the entire Flutter tree browsable and searchable in IDE. '
'Without this flag, only the child modules will be visible in IDE.',
);
}
@override
final String name = 'ide-config';
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{};
@override
final String description = 'Configure the IDE for use in the Flutter tree.\n\n'
'If run on a Flutter tree that is already configured for the IDE, this '
'command will add any new configurations, recreate any files that are '
'missing. If --overwrite is specified, will revert existing files to '
'the template versions, reset the module list, and return configuration '
'settings to the template versions.\n\n'
'This command is intended for Flutter developers to help them set up the '
"Flutter tree for development in an IDE. It doesn't affect other projects.\n\n"
'Currently, IntelliJ is the default (and only) IDE that may be configured.';
@override
final bool hidden = true;
@override
String get invocation => '${runner?.executableName} $name';
static const String _ideName = 'intellij';
Directory get _templateDirectory {
return globals.fs.directory(globals.fs.path.join(
Cache.flutterRoot!,
'packages',
'flutter_tools',
'ide_templates',
_ideName,
));
}
Directory get _createTemplatesDirectory {
return globals.fs.directory(globals.fs.path.join(
Cache.flutterRoot!,
'packages',
'flutter_tools',
'templates',
));
}
Directory get _flutterRoot => globals.fs.directory(globals.fs.path.absolute(Cache.flutterRoot!));
// Returns true if any entire path element is equal to dir.
bool _hasDirectoryInPath(FileSystemEntity entity, String dir) {
String path = entity.absolute.path;
while (path.isNotEmpty && globals.fs.path.dirname(path) != path) {
if (globals.fs.path.basename(path) == dir) {
return true;
}
path = globals.fs.path.dirname(path);
}
return false;
}
// Returns true if child is anywhere underneath parent.
bool _isChildDirectoryOf(FileSystemEntity parent, FileSystemEntity child) {
return child.absolute.path.startsWith(parent.absolute.path);
}
// Checks the contents of the two files to see if they have changes.
bool _fileIsIdentical(File src, File dest) {
if (src.lengthSync() != dest.lengthSync()) {
return false;
}
// Test byte by byte. We're assuming that these are small files.
final List<int> srcBytes = src.readAsBytesSync();
final List<int> destBytes = dest.readAsBytesSync();
for (int i = 0; i < srcBytes.length; ++i) {
if (srcBytes[i] != destBytes[i]) {
return false;
}
}
return true;
}
// Discovers and syncs with existing configuration files in the Flutter tree.
void _handleTemplateUpdate() {
if (!_flutterRoot.existsSync()) {
return;
}
final Set<String> manifest = <String>{};
final Iterable<File> flutterFiles = _flutterRoot.listSync(recursive: true).whereType<File>();
for (final File srcFile in flutterFiles) {
final String relativePath = globals.fs.path.relative(srcFile.path, from: _flutterRoot.absolute.path);
// Skip template files in both the ide_templates and templates
// directories to avoid copying onto themselves.
if (_isChildDirectoryOf(_templateDirectory, srcFile) ||
_isChildDirectoryOf(_createTemplatesDirectory, srcFile)) {
continue;
}
// Skip files we aren't interested in.
final RegExp trackedIdeaFileRegExp = RegExp(
r'(\.name|modules.xml|vcs.xml)$',
);
final bool isATrackedIdeaFile = _hasDirectoryInPath(srcFile, '.idea') &&
(trackedIdeaFileRegExp.hasMatch(relativePath) ||
_hasDirectoryInPath(srcFile, 'runConfigurations'));
final bool isAnImlOutsideIdea = !isATrackedIdeaFile && srcFile.path.endsWith('.iml');
if (!isATrackedIdeaFile && !isAnImlOutsideIdea) {
continue;
}
final File finalDestinationFile = globals.fs.file(globals.fs.path.absolute(
_templateDirectory.absolute.path, '$relativePath${Template.copyTemplateExtension}'));
final String relativeDestination =
globals.fs.path.relative(finalDestinationFile.path, from: _flutterRoot.absolute.path);
if (finalDestinationFile.existsSync()) {
if (_fileIsIdentical(srcFile, finalDestinationFile)) {
globals.printTrace(' $relativeDestination (identical)');
manifest.add('$relativePath${Template.copyTemplateExtension}');
continue;
}
if (boolArg('overwrite')) {
finalDestinationFile.deleteSync();
globals.printStatus(' $relativeDestination (overwritten)');
} else {
globals.printTrace(' $relativeDestination (existing - skipped)');
manifest.add('$relativePath${Template.copyTemplateExtension}');
continue;
}
} else {
globals.printStatus(' $relativeDestination (added)');
}
final Directory finalDestinationDir = globals.fs.directory(finalDestinationFile.dirname);
if (!finalDestinationDir.existsSync()) {
globals.printTrace(" ${finalDestinationDir.path} doesn't exist, creating.");
finalDestinationDir.createSync(recursive: true);
}
srcFile.copySync(finalDestinationFile.path);
manifest.add('$relativePath${Template.copyTemplateExtension}');
}
// If we're not overwriting, then we're not going to remove missing items either.
if (!boolArg('overwrite')) {
return;
}
// Look for any files under the template dir that don't exist in the manifest and remove
// them.
final Iterable<File> templateFiles = _templateDirectory.listSync(recursive: true).whereType<File>();
for (final File templateFile in templateFiles) {
final String relativePath = globals.fs.path.relative(
templateFile.absolute.path,
from: _templateDirectory.absolute.path,
);
if (!manifest.contains(relativePath)) {
templateFile.deleteSync();
final String relativeDestination =
globals.fs.path.relative(templateFile.path, from: _flutterRoot.absolute.path);
globals.printStatus(' $relativeDestination (removed)');
}
// If the directory is now empty, then remove it, and do the same for its parent,
// until we escape to the template directory.
Directory parentDir = globals.fs.directory(templateFile.dirname);
while (parentDir.listSync().isEmpty) {
parentDir.deleteSync();
globals.printTrace(' ${globals.fs.path.relative(parentDir.absolute.path)} (empty directory - removed)');
parentDir = globals.fs.directory(parentDir.dirname);
if (globals.fs.path.isWithin(_templateDirectory.absolute.path, parentDir.absolute.path)) {
break;
}
}
}
}
@override
Future<FlutterCommandResult> runCommand() async {
final List<String> rest = argResults?.rest ?? <String>[];
if (rest.isNotEmpty) {
throwToolExit('Currently, the only supported IDE is IntelliJ\n$usage', exitCode: 2);
}
if (boolArg('update-templates')) {
_handleTemplateUpdate();
return FlutterCommandResult.success();
}
final String flutterRoot = globals.fs.path.absolute(Cache.flutterRoot!);
final String dirPath = globals.fs.path.normalize(
globals.fs.directory(globals.fs.path.absolute(Cache.flutterRoot!)).absolute.path,
);
final String? error = _validateFlutterDir(dirPath, flutterRoot: flutterRoot);
if (error != null) {
throwToolExit(error);
}
globals.printStatus('Updating IDE configuration for Flutter tree at $dirPath...');
int generatedCount = 0;
generatedCount += _renderTemplate(_ideName, dirPath, <String, Object>{
'withRootModule': boolArg('with-root-module'),
'android': true,
});
globals.printStatus('Wrote $generatedCount files.');
globals.printStatus('');
globals.printStatus('Your IntelliJ configuration is now up to date. It is prudent to '
'restart IntelliJ, if running.');
return FlutterCommandResult.success();
}
int _renderTemplate(String templateName, String dirPath, Map<String, Object> context) {
final Template template = Template(
_templateDirectory,
null,
fileSystem: globals.fs,
logger: globals.logger,
templateRenderer: globals.templateRenderer,
);
return template.render(
globals.fs.directory(dirPath),
context,
overwriteExisting: boolArg('overwrite'),
);
}
}
/// Return null if the flutter root directory is a valid destination. Return a
/// validation message if we should disallow the directory.
String? _validateFlutterDir(String dirPath, { String? flutterRoot }) {
final FileSystemEntityType type = globals.fs.typeSync(dirPath);
switch (type) { // ignore: exhaustive_cases, https://github.com/dart-lang/linter/issues/3017
case FileSystemEntityType.link:
// Do not overwrite links.
return "Invalid project root dir: '$dirPath' - refers to a link.";
case FileSystemEntityType.file:
case FileSystemEntityType.directory:
case FileSystemEntityType.notFound:
return null;
}
// In the case of any other [FileSystemEntityType]s, like the deprecated ones, return null.
return null;
}
| flutter/packages/flutter_tools/lib/src/commands/ide_config.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/ide_config.dart",
"repo_id": "flutter",
"token_count": 3844
} | 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:async';
import 'package:process/process.dart';
import 'package:unified_analytics/unified_analytics.dart';
import 'android/android_builder.dart';
import 'android/android_sdk.dart';
import 'android/android_studio.dart';
import 'android/android_workflow.dart';
import 'android/gradle.dart';
import 'android/gradle_utils.dart';
import 'android/java.dart';
import 'application_package.dart';
import 'artifacts.dart';
import 'asset.dart';
import 'base/config.dart';
import 'base/context.dart';
import 'base/error_handling_io.dart';
import 'base/io.dart';
import 'base/logger.dart';
import 'base/os.dart';
import 'base/process.dart';
import 'base/terminal.dart';
import 'base/time.dart';
import 'base/user_messages.dart';
import 'build_system/build_system.dart';
import 'cache.dart';
import 'custom_devices/custom_devices_config.dart';
import 'dart/pub.dart';
import 'devfs.dart';
import 'device.dart';
import 'devtools_launcher.dart';
import 'doctor.dart';
import 'emulator.dart';
import 'features.dart';
import 'flutter_application_package.dart';
import 'flutter_cache.dart';
import 'flutter_device_manager.dart';
import 'flutter_features.dart';
import 'fuchsia/fuchsia_device.dart' show FuchsiaDeviceTools;
import 'fuchsia/fuchsia_sdk.dart' show FuchsiaArtifacts, FuchsiaSdk;
import 'fuchsia/fuchsia_workflow.dart' show FuchsiaWorkflow, fuchsiaWorkflow;
import 'globals.dart' as globals;
import 'ios/ios_workflow.dart';
import 'ios/iproxy.dart';
import 'ios/simulators.dart';
import 'ios/xcodeproj.dart';
import 'macos/cocoapods.dart';
import 'macos/cocoapods_validator.dart';
import 'macos/macos_workflow.dart';
import 'macos/xcdevice.dart';
import 'macos/xcode.dart';
import 'mdns_discovery.dart';
import 'persistent_tool_state.dart';
import 'reporting/crash_reporting.dart';
import 'reporting/first_run.dart';
import 'reporting/reporting.dart';
import 'reporting/unified_analytics.dart';
import 'resident_runner.dart';
import 'run_hot.dart';
import 'runner/local_engine.dart';
import 'version.dart';
import 'web/workflow.dart';
import 'windows/visual_studio.dart';
import 'windows/visual_studio_validator.dart';
import 'windows/windows_workflow.dart';
Future<T> runInContext<T>(
FutureOr<T> Function() runner, {
Map<Type, Generator>? overrides,
}) async {
// Wrap runner with any asynchronous initialization that should run with the
// overrides and callbacks.
late bool runningOnBot;
FutureOr<T> runnerWrapper() async {
runningOnBot = await globals.isRunningOnBot;
return runner();
}
// TODO(ianh): We should split this into two, one for tests (which should be
// in test/), and one for production (which should be in executable.dart).
return context.run<T>(
name: 'global fallbacks',
body: runnerWrapper,
overrides: overrides,
fallbacks: <Type, Generator>{
Analytics: () => getAnalytics(
runningOnBot: runningOnBot,
flutterVersion: globals.flutterVersion,
environment: globals.platform.environment,
clientIde: globals.platform.environment['FLUTTER_HOST'],
config: globals.config,
),
AndroidBuilder: () => AndroidGradleBuilder(
java: globals.java,
logger: globals.logger,
processManager: globals.processManager,
fileSystem: globals.fs,
artifacts: globals.artifacts!,
usage: globals.flutterUsage,
analytics: globals.analytics,
gradleUtils: globals.gradleUtils!,
platform: globals.platform,
androidStudio: globals.androidStudio,
),
AndroidLicenseValidator: () => AndroidLicenseValidator(
platform: globals.platform,
userMessages: globals.userMessages,
processManager: globals.processManager,
java: globals.java,
androidSdk: globals.androidSdk,
logger: globals.logger,
stdio: globals.stdio,
),
AndroidSdk: AndroidSdk.locateAndroidSdk,
AndroidStudio: AndroidStudio.latestValid,
AndroidValidator: () => AndroidValidator(
java: globals.java,
androidSdk: globals.androidSdk,
logger: globals.logger,
platform: globals.platform,
userMessages: globals.userMessages,
),
AndroidWorkflow: () => AndroidWorkflow(
androidSdk: globals.androidSdk,
featureFlags: featureFlags,
),
ApplicationPackageFactory: () => FlutterApplicationPackageFactory(
userMessages: globals.userMessages,
processManager: globals.processManager,
logger: globals.logger,
fileSystem: globals.fs,
androidSdk: globals.androidSdk,
),
Artifacts: () => CachedArtifacts(
fileSystem: globals.fs,
cache: globals.cache,
platform: globals.platform,
operatingSystemUtils: globals.os,
),
AssetBundleFactory: () {
return AssetBundleFactory.defaultInstance(
logger: globals.logger,
fileSystem: globals.fs,
platform: globals.platform,
);
},
BuildSystem: () => FlutterBuildSystem(
fileSystem: globals.fs,
logger: globals.logger,
platform: globals.platform,
),
Cache: () => FlutterCache(
fileSystem: globals.fs,
logger: globals.logger,
platform: globals.platform,
osUtils: globals.os,
projectFactory: globals.projectFactory,
),
CocoaPods: () => CocoaPods(
fileSystem: globals.fs,
processManager: globals.processManager,
logger: globals.logger,
platform: globals.platform,
xcodeProjectInterpreter: globals.xcodeProjectInterpreter!,
usage: globals.flutterUsage,
analytics: globals.analytics,
),
CocoaPodsValidator: () => CocoaPodsValidator(
globals.cocoaPods!,
globals.userMessages,
),
Config: () => Config(
Config.kFlutterSettings,
fileSystem: globals.fs,
logger: globals.logger,
platform: globals.platform,
),
CustomDevicesConfig: () => CustomDevicesConfig(
fileSystem: globals.fs,
logger: globals.logger,
platform: globals.platform
),
CrashReporter: () => CrashReporter(
fileSystem: globals.fs,
logger: globals.logger,
flutterProjectFactory: globals.projectFactory,
),
DevFSConfig: () => DevFSConfig(),
DeviceManager: () => FlutterDeviceManager(
logger: globals.logger,
processManager: globals.processManager,
platform: globals.platform,
androidSdk: globals.androidSdk,
iosSimulatorUtils: globals.iosSimulatorUtils!,
featureFlags: featureFlags,
fileSystem: globals.fs,
iosWorkflow: globals.iosWorkflow!,
artifacts: globals.artifacts!,
flutterVersion: globals.flutterVersion,
androidWorkflow: androidWorkflow!,
fuchsiaWorkflow: fuchsiaWorkflow!,
xcDevice: globals.xcdevice!,
userMessages: globals.userMessages,
windowsWorkflow: windowsWorkflow!,
macOSWorkflow: MacOSWorkflow(
platform: globals.platform,
featureFlags: featureFlags,
),
fuchsiaSdk: globals.fuchsiaSdk!,
operatingSystemUtils: globals.os,
customDevicesConfig: globals.customDevicesConfig,
),
DevtoolsLauncher: () => DevtoolsServerLauncher(
processManager: globals.processManager,
dartExecutable: globals.artifacts!.getArtifactPath(Artifact.engineDartBinary),
logger: globals.logger,
botDetector: globals.botDetector,
),
Doctor: () => Doctor(
logger: globals.logger,
clock: globals.systemClock,
),
DoctorValidatorsProvider: () => DoctorValidatorsProvider.defaultInstance,
EmulatorManager: () => EmulatorManager(
java: globals.java,
androidSdk: globals.androidSdk,
processManager: globals.processManager,
logger: globals.logger,
fileSystem: globals.fs,
androidWorkflow: androidWorkflow!,
),
FeatureFlags: () => FlutterFeatureFlags(
flutterVersion: globals.flutterVersion,
config: globals.config,
platform: globals.platform,
),
FlutterVersion: () => FlutterVersion(
fs: globals.fs,
flutterRoot: Cache.flutterRoot!,
),
FuchsiaArtifacts: () => FuchsiaArtifacts.find(),
FuchsiaDeviceTools: () => FuchsiaDeviceTools(),
FuchsiaSdk: () => FuchsiaSdk(),
FuchsiaWorkflow: () => FuchsiaWorkflow(
featureFlags: featureFlags,
platform: globals.platform,
fuchsiaArtifacts: globals.fuchsiaArtifacts!,
),
GradleUtils: () => GradleUtils(
operatingSystemUtils: globals.os,
logger: globals.logger,
platform: globals.platform,
cache: globals.cache,
),
HotRunnerConfig: () => HotRunnerConfig(),
IOSSimulatorUtils: () => IOSSimulatorUtils(
logger: globals.logger,
processManager: globals.processManager,
xcode: globals.xcode!,
),
IOSWorkflow: () => IOSWorkflow(
featureFlags: featureFlags,
xcode: globals.xcode!,
platform: globals.platform,
),
Java: () => Java.find(
config: globals.config,
androidStudio: globals.androidStudio,
logger: globals.logger,
fileSystem: globals.fs,
platform: globals.platform,
processManager: globals.processManager
),
LocalEngineLocator: () => LocalEngineLocator(
userMessages: globals.userMessages,
logger: globals.logger,
platform: globals.platform,
fileSystem: globals.fs,
flutterRoot: Cache.flutterRoot!,
),
Logger: () => globals.platform.isWindows
? WindowsStdoutLogger(
terminal: globals.terminal,
stdio: globals.stdio,
outputPreferences: globals.outputPreferences,
)
: StdoutLogger(
terminal: globals.terminal,
stdio: globals.stdio,
outputPreferences: globals.outputPreferences,
),
MacOSWorkflow: () => MacOSWorkflow(
featureFlags: featureFlags,
platform: globals.platform,
),
MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
logger: globals.logger,
flutterUsage: globals.flutterUsage,
analytics: globals.analytics,
),
OperatingSystemUtils: () => OperatingSystemUtils(
fileSystem: globals.fs,
logger: globals.logger,
platform: globals.platform,
processManager: globals.processManager,
),
OutputPreferences: () => OutputPreferences(
wrapText: globals.stdio.hasTerminal,
showColor: globals.platform.stdoutSupportsAnsi,
stdio: globals.stdio,
),
PersistentToolState: () => PersistentToolState(
fileSystem: globals.fs,
logger: globals.logger,
platform: globals.platform,
),
ProcessInfo: () => ProcessInfo(globals.fs),
ProcessManager: () => ErrorHandlingProcessManager(
delegate: const LocalProcessManager(),
platform: globals.platform,
),
ProcessUtils: () => ProcessUtils(
processManager: globals.processManager,
logger: globals.logger,
),
Pub: () => Pub(
fileSystem: globals.fs,
logger: globals.logger,
processManager: globals.processManager,
botDetector: globals.botDetector,
platform: globals.platform,
usage: globals.flutterUsage,
),
Stdio: () => Stdio(),
SystemClock: () => const SystemClock(),
Usage: () => Usage(
runningOnBot: runningOnBot,
firstRunMessenger: FirstRunMessenger(persistentToolState: globals.persistentToolState!),
),
UserMessages: () => UserMessages(),
VisualStudioValidator: () => VisualStudioValidator(
userMessages: globals.userMessages,
visualStudio: VisualStudio(
fileSystem: globals.fs,
platform: globals.platform,
logger: globals.logger,
processManager: globals.processManager,
osUtils: globals.os,
)
),
WebWorkflow: () => WebWorkflow(
featureFlags: featureFlags,
platform: globals.platform,
),
WindowsWorkflow: () => WindowsWorkflow(
featureFlags: featureFlags,
platform: globals.platform,
),
Xcode: () => Xcode(
logger: globals.logger,
processManager: globals.processManager,
platform: globals.platform,
fileSystem: globals.fs,
xcodeProjectInterpreter: globals.xcodeProjectInterpreter!,
userMessages: globals.userMessages,
),
XCDevice: () => XCDevice(
processManager: globals.processManager,
logger: globals.logger,
artifacts: globals.artifacts!,
cache: globals.cache,
platform: globals.platform,
xcode: globals.xcode!,
iproxy: IProxy(
iproxyPath: globals.artifacts!.getHostArtifact(
HostArtifact.iproxy,
).path,
logger: globals.logger,
processManager: globals.processManager,
dyLdLibEntry: globals.cache.dyLdLibEntry,
),
fileSystem: globals.fs,
analytics: globals.analytics,
),
XcodeProjectInterpreter: () => XcodeProjectInterpreter(
logger: globals.logger,
processManager: globals.processManager,
platform: globals.platform,
fileSystem: globals.fs,
usage: globals.flutterUsage,
analytics: globals.analytics,
),
},
);
}
| flutter/packages/flutter_tools/lib/src/context_runner.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/context_runner.dart",
"repo_id": "flutter",
"token_count": 5837
} | 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 'package:dds/dap.dart';
/// An implementation of [AttachRequestArguments] that includes all fields used by the Flutter debug adapter.
///
/// This class represents the data passed from the client editor to the debug
/// adapter in attachRequest, which is a request to attach to/debug a running
/// application.
class FlutterAttachRequestArguments
extends DartCommonLaunchAttachRequestArguments
implements AttachRequestArguments {
FlutterAttachRequestArguments({
this.toolArgs,
this.customTool,
this.customToolReplacesArgs,
this.vmServiceUri,
this.vmServiceInfoFile,
this.program,
super.restart,
super.name,
super.cwd,
super.env,
super.additionalProjectPaths,
super.allowAnsiColorOutput,
super.debugSdkLibraries,
super.debugExternalPackageLibraries,
super.evaluateGettersInDebugViews,
super.evaluateToStringInDebugViews,
super.sendLogsToClient,
super.sendCustomProgressEvents,
});
FlutterAttachRequestArguments.fromMap(super.obj)
: toolArgs = (obj['toolArgs'] as List<Object?>?)?.cast<String>(),
customTool = obj['customTool'] as String?,
customToolReplacesArgs = obj['customToolReplacesArgs'] as int?,
vmServiceUri = obj['vmServiceUri'] as String?,
vmServiceInfoFile = obj['vmServiceInfoFile'] as String?,
program = obj['program'] as String?,
super.fromMap();
factory FlutterAttachRequestArguments.fromJson(Map<String, Object?> obj) = FlutterAttachRequestArguments.fromMap;
/// Arguments to be passed to the tool that will run [program] (for example, the VM or Flutter tool).
final List<String>? toolArgs;
/// An optional tool to run instead of "flutter".
///
/// In combination with [customToolReplacesArgs] allows invoking a custom
/// tool instead of "flutter" to launch scripts/tests. The custom tool must be
/// completely compatible with the tool/command it is replacing.
///
/// This field should be a full absolute path if the tool may not be available
/// in `PATH`.
final String? customTool;
/// The number of arguments to delete from the beginning of the argument list
/// when invoking [customTool].
///
/// For example, setting [customTool] to `flutter_test_wrapper` and
/// `customToolReplacesArgs` to `1` for a test run would invoke
/// `flutter_test_wrapper foo_test.dart` instead of `flutter test foo_test.dart`.
final int? customToolReplacesArgs;
/// The VM Service URI of the running Flutter app to connect to.
///
/// Only one of this or [vmServiceInfoFile] (or neither) can be supplied.
final String? vmServiceUri;
/// The VM Service info file to extract the VM Service URI from to attach to.
///
/// Only one of this or [vmServiceUri] (or neither) can be supplied.
final String? vmServiceInfoFile;
/// The program/Flutter app to be run.
final String? program;
@override
Map<String, Object?> toJson() => <String, Object?>{
...super.toJson(),
if (toolArgs != null) 'toolArgs': toolArgs,
if (customTool != null) 'customTool': customTool,
if (customToolReplacesArgs != null)
'customToolReplacesArgs': customToolReplacesArgs,
if (vmServiceUri != null) 'vmServiceUri': vmServiceUri,
};
}
/// An implementation of [LaunchRequestArguments] that includes all fields used by the Flutter debug adapter.
///
/// This class represents the data passed from the client editor to the debug
/// adapter in launchRequest, which is a request to start debugging an
/// application.
class FlutterLaunchRequestArguments
extends DartCommonLaunchAttachRequestArguments
implements LaunchRequestArguments {
FlutterLaunchRequestArguments({
this.noDebug,
required this.program,
this.args,
this.toolArgs,
this.customTool,
this.customToolReplacesArgs,
super.restart,
super.name,
super.cwd,
super.env,
super.additionalProjectPaths,
super.allowAnsiColorOutput,
super.debugSdkLibraries,
super.debugExternalPackageLibraries,
super.evaluateGettersInDebugViews,
super.evaluateToStringInDebugViews,
super.sendLogsToClient,
super.sendCustomProgressEvents,
});
FlutterLaunchRequestArguments.fromMap(super.obj)
: noDebug = obj['noDebug'] as bool?,
program = obj['program'] as String?,
args = (obj['args'] as List<Object?>?)?.cast<String>(),
toolArgs = (obj['toolArgs'] as List<Object?>?)?.cast<String>(),
customTool = obj['customTool'] as String?,
customToolReplacesArgs = obj['customToolReplacesArgs'] as int?,
super.fromMap();
factory FlutterLaunchRequestArguments.fromJson(Map<String, Object?> obj) = FlutterLaunchRequestArguments.fromMap;
/// If noDebug is true the launch request should launch the program without enabling debugging.
@override
final bool? noDebug;
/// The program/Flutter app to be run.
final String? program;
/// Arguments to be passed to [program].
final List<String>? args;
/// Arguments to be passed to the tool that will run [program] (for example, the VM or Flutter tool).
final List<String>? toolArgs;
/// An optional tool to run instead of "flutter".
///
/// In combination with [customToolReplacesArgs] allows invoking a custom
/// tool instead of "flutter" to launch scripts/tests. The custom tool must be
/// completely compatible with the tool/command it is replacing.
///
/// This field should be a full absolute path if the tool may not be available
/// in `PATH`.
final String? customTool;
/// The number of arguments to delete from the beginning of the argument list
/// when invoking [customTool].
///
/// For example, setting [customTool] to `flutter_test_wrapper` and
/// `customToolReplacesArgs` to `1` for a test run would invoke
/// `flutter_test_wrapper foo_test.dart` instead of `flutter test foo_test.dart`.
final int? customToolReplacesArgs;
@override
Map<String, Object?> toJson() => <String, Object?>{
...super.toJson(),
if (noDebug != null) 'noDebug': noDebug,
if (program != null) 'program': program,
if (args != null) 'args': args,
if (toolArgs != null) 'toolArgs': toolArgs,
if (customTool != null) 'customTool': customTool,
if (customToolReplacesArgs != null)
'customToolReplacesArgs': customToolReplacesArgs,
};
}
| flutter/packages/flutter_tools/lib/src/debug_adapters/flutter_adapter_args.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/debug_adapters/flutter_adapter_args.dart",
"repo_id": "flutter",
"token_count": 2113
} | 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 'package:process/process.dart';
import 'android/android_sdk.dart';
import 'android/application_package.dart';
import 'application_package.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/process.dart';
import 'base/user_messages.dart';
import 'build_info.dart';
import 'fuchsia/application_package.dart';
import 'globals.dart' as globals;
import 'ios/application_package.dart';
import 'linux/application_package.dart';
import 'macos/application_package.dart';
import 'project.dart';
import 'tester/flutter_tester.dart';
import 'web/web_device.dart';
import 'windows/application_package.dart';
/// A package factory that supports all Flutter target platforms.
class FlutterApplicationPackageFactory extends ApplicationPackageFactory {
FlutterApplicationPackageFactory({
required AndroidSdk? androidSdk,
required ProcessManager processManager,
required Logger logger,
required UserMessages userMessages,
required FileSystem fileSystem,
}) : _androidSdk = androidSdk,
_processManager = processManager,
_logger = logger,
_userMessages = userMessages,
_fileSystem = fileSystem,
_processUtils = ProcessUtils(logger: logger, processManager: processManager);
final AndroidSdk? _androidSdk;
final ProcessManager _processManager;
final Logger _logger;
final ProcessUtils _processUtils;
final UserMessages _userMessages;
final FileSystem _fileSystem;
@override
Future<ApplicationPackage?> getPackageForPlatform(
TargetPlatform platform, {
BuildInfo? buildInfo,
File? applicationBinary,
}) async {
switch (platform) {
case TargetPlatform.android:
case TargetPlatform.android_arm:
case TargetPlatform.android_arm64:
case TargetPlatform.android_x64:
case TargetPlatform.android_x86:
if (applicationBinary == null) {
return AndroidApk.fromAndroidProject(
FlutterProject.current().android,
processManager: _processManager,
processUtils: _processUtils,
logger: _logger,
androidSdk: _androidSdk,
userMessages: _userMessages,
fileSystem: _fileSystem,
buildInfo: buildInfo,
);
}
return AndroidApk.fromApk(
applicationBinary,
processManager: _processManager,
logger: _logger,
androidSdk: _androidSdk!,
userMessages: _userMessages,
processUtils: _processUtils,
);
case TargetPlatform.ios:
return applicationBinary == null
? await IOSApp.fromIosProject(FlutterProject.current().ios, buildInfo)
: IOSApp.fromPrebuiltApp(applicationBinary);
case TargetPlatform.tester:
return FlutterTesterApp.fromCurrentDirectory(globals.fs);
case TargetPlatform.darwin:
return applicationBinary == null
? MacOSApp.fromMacOSProject(FlutterProject.current().macos)
: MacOSApp.fromPrebuiltApp(applicationBinary);
case TargetPlatform.web_javascript:
if (!FlutterProject.current().web.existsSync()) {
return null;
}
return WebApplicationPackage(FlutterProject.current());
case TargetPlatform.linux_x64:
case TargetPlatform.linux_arm64:
return applicationBinary == null
? LinuxApp.fromLinuxProject(FlutterProject.current().linux)
: LinuxApp.fromPrebuiltApp(applicationBinary);
case TargetPlatform.windows_x64:
case TargetPlatform.windows_arm64:
return applicationBinary == null
? WindowsApp.fromWindowsProject(FlutterProject.current().windows)
: WindowsApp.fromPrebuiltApp(applicationBinary);
case TargetPlatform.fuchsia_arm64:
case TargetPlatform.fuchsia_x64:
return applicationBinary == null
? FuchsiaApp.fromFuchsiaProject(FlutterProject.current().fuchsia)
: FuchsiaApp.fromPrebuiltApp(applicationBinary);
}
}
}
| flutter/packages/flutter_tools/lib/src/flutter_application_package.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/flutter_application_package.dart",
"repo_id": "flutter",
"token_count": 1579
} | 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 'dart:async';
import 'base/io.dart';
import 'base/net.dart';
import 'base/platform.dart';
import 'doctor_validator.dart';
import 'features.dart';
/// Common Flutter HTTP hosts.
const String kCloudHost = 'https://storage.googleapis.com/';
const String kCocoaPods = 'https://cocoapods.org/';
const String kGitHub = 'https://github.com/';
const String kMaven = 'https://maven.google.com/';
const String kPubDev = 'https://pub.dev/';
// Overridable environment variables.
const String kPubDevOverride = 'PUB_HOSTED_URL'; // https://dart.dev/tools/pub/environment-variables
// Validator that checks all provided hosts are reachable and responsive
class HttpHostValidator extends DoctorValidator {
HttpHostValidator({
required Platform platform,
required FeatureFlags featureFlags,
required HttpClient httpClient,
}) : _platform = platform,
_featureFlags = featureFlags,
_httpClient = httpClient,
super('Network resources');
final Platform _platform;
final FeatureFlags _featureFlags;
final HttpClient _httpClient;
final Set<Uri> _activeHosts = <Uri>{};
@override
String get slowWarning {
if (_activeHosts.isEmpty) {
return 'Network resources check is taking a long time...';
}
return 'Attempting to reach ${_activeHosts.map((Uri url) => url.host).join(", ")}...';
}
/// Make a head request to the HTTP host for checking availability
Future<String?> _checkHostAvailability(Uri host) async {
try {
assert(!_activeHosts.contains(host));
_activeHosts.add(host);
final HttpClientRequest req = await _httpClient.headUrl(host);
await req.close();
// HTTP host is available if no exception happened.
return null;
} on SocketException catch (error) {
return 'A network error occurred while checking "$host": ${error.message}';
} on HttpException catch (error) {
return 'An HTTP error occurred while checking "$host": ${error.message}';
} on HandshakeException catch (error) {
return 'A cryptographic error occurred while checking "$host": ${error.message}\n'
'You may be experiencing a man-in-the-middle attack, your network may be '
'compromised, or you may have malware installed on your computer.';
} on OSError catch (error) {
return 'An error occurred while checking "$host": ${error.message}';
} finally {
_activeHosts.remove(host);
}
}
static Uri? _parseUrl(String value) {
final Uri? url = Uri.tryParse(value);
if (url == null || !url.hasScheme || !url.hasAuthority || (!url.hasEmptyPath && !url.hasAbsolutePath) || url.hasFragment) {
return null;
}
return url;
}
@override
Future<ValidationResult> validate() async {
final List<String?> availabilityResults = <String?>[];
final List<Uri> requiredHosts = <Uri>[];
if (_platform.environment.containsKey(kPubDevOverride)) {
final Uri? url = _parseUrl(_platform.environment[kPubDevOverride]!);
if (url == null) {
availabilityResults.add(
'Environment variable $kPubDevOverride does not specify a valid URL: "${_platform.environment[kPubDevOverride]}"\n'
'Please see https://flutter.dev/community/china for an example of how to use it.'
);
} else {
requiredHosts.add(url);
}
} else {
requiredHosts.add(Uri.parse(kPubDev));
}
if (_platform.environment.containsKey(kFlutterStorageBaseUrl)) {
final Uri? url = _parseUrl(_platform.environment[kFlutterStorageBaseUrl]!);
if (url == null) {
availabilityResults.add(
'Environment variable $kFlutterStorageBaseUrl does not specify a valid URL: "${_platform.environment[kFlutterStorageBaseUrl]}"\n'
'Please see https://flutter.dev/community/china for an example of how to use it.'
);
} else {
requiredHosts.add(url);
}
} else {
requiredHosts.add(Uri.parse(kCloudHost));
if (_featureFlags.isAndroidEnabled) {
// if kFlutterStorageBaseUrl is set it is used instead of Maven
requiredHosts.add(Uri.parse(kMaven));
}
}
if (_featureFlags.isMacOSEnabled) {
requiredHosts.add(Uri.parse(kCocoaPods));
}
requiredHosts.add(Uri.parse(kGitHub));
// Check all the hosts simultaneously.
availabilityResults.addAll(await Future.wait<String?>(requiredHosts.map(_checkHostAvailability)));
int failures = 0;
int successes = 0;
final List<ValidationMessage> messages = <ValidationMessage>[];
for (final String? message in availabilityResults) {
if (message == null) {
successes += 1;
} else {
failures += 1;
messages.add(ValidationMessage.error(message));
}
}
if (failures == 0) {
assert(successes > 0);
assert(messages.isEmpty);
return const ValidationResult(
ValidationType.success,
<ValidationMessage>[ValidationMessage('All expected network resources are available.')],
);
}
assert(messages.isNotEmpty);
return ValidationResult(
successes == 0 ? ValidationType.notAvailable : ValidationType.partial,
messages,
);
}
}
| flutter/packages/flutter_tools/lib/src/http_host_validator.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/http_host_validator.dart",
"repo_id": "flutter",
"token_count": 1929
} | 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 '../../base/file_system.dart';
import '../../base/project_migrator.dart';
import '../../xcode_project.dart';
/// Remove deprecated bitcode build setting.
class RemoveBitcodeMigration extends ProjectMigrator {
RemoveBitcodeMigration(
IosProject project,
super.logger,
) : _xcodeProjectInfoFile = project.xcodeProjectInfoFile;
final File _xcodeProjectInfoFile;
@override
bool migrate() {
if (_xcodeProjectInfoFile.existsSync()) {
processFileLines(_xcodeProjectInfoFile);
} else {
logger.printTrace('Xcode project not found, skipping removing bitcode migration.');
}
return true;
}
@override
String? migrateLine(String line) {
if (line.contains('ENABLE_BITCODE = YES;')) {
if (!migrationRequired) {
// Only print for the first discovered change found.
logger.printWarning('Disabling deprecated bitcode Xcode build setting. See https://github.com/flutter/flutter/issues/107887 for additional details.');
}
return line.replaceAll('ENABLE_BITCODE = YES', 'ENABLE_BITCODE = NO');
}
return line;
}
}
| flutter/packages/flutter_tools/lib/src/ios/migrations/remove_bitcode_migration.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/ios/migrations/remove_bitcode_migration.dart",
"repo_id": "flutter",
"token_count": 428
} | 742 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:native_assets_builder/native_assets_builder.dart'
hide NativeAssetsBuildRunner;
import 'package:native_assets_cli/native_assets_cli_internal.dart'
hide BuildMode;
import 'package:native_assets_cli/native_assets_cli_internal.dart'
as native_assets_cli;
import '../../../base/file_system.dart';
import '../../../build_info.dart';
import '../../../globals.dart' as globals;
import '../native_assets.dart';
import 'native_assets_host.dart';
/// Dry run the native builds.
///
/// This does not build native assets, it only simulates what the final paths
/// of all assets will be so that this can be embedded in the kernel file and
/// the Xcode project.
Future<Uri?> dryRunNativeAssetsMacOS({
required NativeAssetsBuildRunner buildRunner,
required Uri projectUri,
bool flutterTester = false,
required FileSystem fileSystem,
}) async {
if (!await nativeBuildRequired(buildRunner)) {
return null;
}
final Uri buildUri = nativeAssetsBuildUri(projectUri, OS.macOS);
final Iterable<KernelAsset> nativeAssetPaths = await dryRunNativeAssetsMacOSInternal(
fileSystem,
projectUri,
flutterTester,
buildRunner,
);
final Uri nativeAssetsUri = await writeNativeAssetsYaml(
KernelAssets(nativeAssetPaths),
buildUri,
fileSystem,
);
return nativeAssetsUri;
}
Future<Iterable<KernelAsset>> dryRunNativeAssetsMacOSInternal(
FileSystem fileSystem,
Uri projectUri,
bool flutterTester,
NativeAssetsBuildRunner buildRunner,
) async {
const OS targetOS = OS.macOS;
final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS);
globals.logger.printTrace('Dry running native assets for $targetOS.');
final DryRunResult dryRunResult = await buildRunner.dryRun(
linkModePreference: LinkModePreference.dynamic,
targetOS: targetOS,
workingDirectory: projectUri,
includeParentEnvironment: true,
);
ensureNativeAssetsBuildSucceed(dryRunResult);
final List<Asset> nativeAssets = dryRunResult.assets;
ensureNoLinkModeStatic(nativeAssets);
globals.logger.printTrace('Dry running native assets for $targetOS done.');
final Uri? absolutePath = flutterTester ? buildUri : null;
final Map<Asset, KernelAsset> assetTargetLocations = _assetTargetLocations(
nativeAssets,
absolutePath,
);
return assetTargetLocations.values;
}
/// Builds native assets.
///
/// If [darwinArchs] is omitted, the current target architecture is used.
///
/// If [flutterTester] is true, absolute paths are emitted in the native
/// assets mapping. This can be used for JIT mode without sandbox on the host.
/// This is used in `flutter test` and `flutter run -d flutter-tester`.
Future<(Uri? nativeAssetsYaml, List<Uri> dependencies)> buildNativeAssetsMacOS({
required NativeAssetsBuildRunner buildRunner,
List<DarwinArch>? darwinArchs,
required Uri projectUri,
required BuildMode buildMode,
bool flutterTester = false,
String? codesignIdentity,
Uri? yamlParentDirectory,
required FileSystem fileSystem,
}) async {
const OS targetOS = OS.macOS;
final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS);
if (!await nativeBuildRequired(buildRunner)) {
final Uri nativeAssetsYaml = await writeNativeAssetsYaml(
KernelAssets(),
yamlParentDirectory ?? buildUri,
fileSystem,
);
return (nativeAssetsYaml, <Uri>[]);
}
final List<Target> targets = darwinArchs != null
? darwinArchs.map(_getNativeTarget).toList()
: <Target>[Target.current];
final native_assets_cli.BuildMode buildModeCli =
nativeAssetsBuildMode(buildMode);
globals.logger
.printTrace('Building native assets for $targets $buildModeCli.');
final List<Asset> nativeAssets = <Asset>[];
final Set<Uri> dependencies = <Uri>{};
for (final Target target in targets) {
final BuildResult result = await buildRunner.build(
linkModePreference: LinkModePreference.dynamic,
target: target,
buildMode: buildModeCli,
workingDirectory: projectUri,
includeParentEnvironment: true,
cCompilerConfig: await buildRunner.cCompilerConfig,
);
ensureNativeAssetsBuildSucceed(result);
nativeAssets.addAll(result.assets);
dependencies.addAll(result.dependencies);
}
ensureNoLinkModeStatic(nativeAssets);
globals.logger.printTrace('Building native assets for $targets done.');
final Uri? absolutePath = flutterTester ? buildUri : null;
final Map<Asset, KernelAsset> assetTargetLocations =
_assetTargetLocations(nativeAssets, absolutePath);
final Map<KernelAssetPath, List<Asset>> fatAssetTargetLocations =
_fatAssetTargetLocations(nativeAssets, absolutePath);
if (flutterTester) {
await _copyNativeAssetsMacOSFlutterTester(
buildUri,
fatAssetTargetLocations,
codesignIdentity,
buildMode,
fileSystem,
);
} else {
await _copyNativeAssetsMacOS(
buildUri,
fatAssetTargetLocations,
codesignIdentity,
buildMode,
fileSystem,
);
}
final Uri nativeAssetsUri = await writeNativeAssetsYaml(
KernelAssets(assetTargetLocations.values),
yamlParentDirectory ?? buildUri,
fileSystem,
);
return (nativeAssetsUri, dependencies.toList());
}
/// Extract the [Target] from a [DarwinArch].
Target _getNativeTarget(DarwinArch darwinArch) {
switch (darwinArch) {
case DarwinArch.arm64:
return Target.macOSArm64;
case DarwinArch.x86_64:
return Target.macOSX64;
case DarwinArch.armv7:
throw Exception('Unknown DarwinArch: $darwinArch.');
}
}
Map<KernelAssetPath, List<Asset>> _fatAssetTargetLocations(
List<Asset> nativeAssets,
Uri? absolutePath,
) {
final Set<String> alreadyTakenNames = <String>{};
final Map<KernelAssetPath, List<Asset>> result =
<KernelAssetPath, List<Asset>>{};
final Map<String, KernelAssetPath> idToPath = <String, KernelAssetPath>{};
for (final Asset asset in nativeAssets) {
// Use same target path for all assets with the same id.
final KernelAssetPath path = idToPath[asset.id] ??
_targetLocationMacOS(
asset,
absolutePath,
alreadyTakenNames,
).path;
idToPath[asset.id] = path;
result[path] ??= <Asset>[];
result[path]!.add(asset);
}
return result;
}
Map<Asset, KernelAsset> _assetTargetLocations(
List<Asset> nativeAssets,
Uri? absolutePath,
) {
final Set<String> alreadyTakenNames = <String>{};
return <Asset, KernelAsset>{
for (final Asset asset in nativeAssets)
asset: _targetLocationMacOS(asset, absolutePath, alreadyTakenNames),
};
}
KernelAsset _targetLocationMacOS(
Asset asset,
Uri? absolutePath,
Set<String> alreadyTakenNames,
) {
final AssetPath path = asset.path;
final KernelAssetPath kernelAssetPath;
switch (path) {
case AssetSystemPath _:
kernelAssetPath = KernelAssetSystemPath(path.uri);
case AssetInExecutable _:
kernelAssetPath = KernelAssetInExecutable();
case AssetInProcess _:
kernelAssetPath = KernelAssetInProcess();
case AssetAbsolutePath _:
final String fileName = path.uri.pathSegments.last;
Uri uri;
if (absolutePath != null) {
// Flutter tester needs full host paths.
uri = absolutePath.resolve(fileName);
} else {
// Flutter Desktop needs "absolute" paths inside the app.
// "relative" in the context of native assets would be relative to the
// kernel or aot snapshot.
uri = frameworkUri(fileName, alreadyTakenNames);
}
kernelAssetPath = KernelAssetAbsolutePath(uri);
default:
throw Exception(
'Unsupported asset path type ${path.runtimeType} in asset $asset',
);
}
return KernelAsset(
id: asset.id,
target: asset.target,
path: kernelAssetPath,
);
}
/// Copies native assets into a framework per dynamic library.
///
/// The framework contains symlinks according to
/// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/FrameworkAnatomy.html
///
/// For `flutter run -release` a multi-architecture solution is needed. So,
/// `lipo` is used to combine all target architectures into a single file.
///
/// The install name is set so that it matches what the place it will
/// be bundled in the final app.
///
/// Code signing is also done here, so that it doesn't have to be done in
/// in macos_assemble.sh.
Future<void> _copyNativeAssetsMacOS(
Uri buildUri,
Map<KernelAssetPath, List<Asset>> assetTargetLocations,
String? codesignIdentity,
BuildMode buildMode,
FileSystem fileSystem,
) async {
if (assetTargetLocations.isNotEmpty) {
globals.logger.printTrace(
'Copying native assets to ${buildUri.toFilePath()}.',
);
for (final MapEntry<KernelAssetPath, List<Asset>> assetMapping
in assetTargetLocations.entries) {
final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri;
final List<Uri> sources = <Uri>[
for (final Asset source in assetMapping.value)
(source.path as AssetAbsolutePath).uri,
];
final Uri targetUri = buildUri.resolveUri(target);
final String name = targetUri.pathSegments.last;
final Directory frameworkDir = fileSystem.file(targetUri).parent;
if (await frameworkDir.exists()) {
await frameworkDir.delete(recursive: true);
}
// MyFramework.framework/ frameworkDir
// MyFramework -> Versions/Current/MyFramework dylibLink
// Resources -> Versions/Current/Resources resourcesLink
// Versions/ versionsDir
// A/ versionADir
// MyFramework dylibFile
// Resources/ resourcesDir
// Info.plist
// Current -> A currentLink
final Directory versionsDir = frameworkDir.childDirectory('Versions');
final Directory versionADir = versionsDir.childDirectory('A');
final Directory resourcesDir = versionADir.childDirectory('Resources');
await resourcesDir.create(recursive: true);
final File dylibFile = versionADir.childFile(name);
final Link currentLink = versionsDir.childLink('Current');
await currentLink.create(fileSystem.path.relative(
versionADir.path,
from: currentLink.parent.path,
));
final Link resourcesLink = frameworkDir.childLink('Resources');
await resourcesLink.create(fileSystem.path.relative(
resourcesDir.path,
from: resourcesLink.parent.path,
));
await lipoDylibs(dylibFile, sources);
final Link dylibLink = frameworkDir.childLink(name);
await dylibLink.create(fileSystem.path.relative(
versionsDir.childDirectory('Current').childFile(name).path,
from: dylibLink.parent.path,
));
await setInstallNameDylib(dylibFile);
await createInfoPlist(name, resourcesDir);
await codesignDylib(codesignIdentity, buildMode, frameworkDir);
}
globals.logger.printTrace('Copying native assets done.');
}
}
/// Copies native assets for flutter tester.
///
/// For `flutter run -release` a multi-architecture solution is needed. So,
/// `lipo` is used to combine all target architectures into a single file.
///
/// In contrast to [_copyNativeAssetsMacOS], it does not set the install name.
///
/// Code signing is also done here.
Future<void> _copyNativeAssetsMacOSFlutterTester(
Uri buildUri,
Map<KernelAssetPath, List<Asset>> assetTargetLocations,
String? codesignIdentity,
BuildMode buildMode,
FileSystem fileSystem,
) async {
if (assetTargetLocations.isNotEmpty) {
globals.logger.printTrace(
'Copying native assets to ${buildUri.toFilePath()}.',
);
for (final MapEntry<KernelAssetPath, List<Asset>> assetMapping
in assetTargetLocations.entries) {
final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri;
final List<Uri> sources = <Uri>[
for (final Asset source in assetMapping.value)
(source.path as AssetAbsolutePath).uri,
];
final Uri targetUri = buildUri.resolveUri(target);
final File dylibFile = fileSystem.file(targetUri);
final Directory targetParent = dylibFile.parent;
if (!await targetParent.exists()) {
await targetParent.create(recursive: true);
}
await lipoDylibs(dylibFile, sources);
await codesignDylib(codesignIdentity, buildMode, dylibFile);
}
globals.logger.printTrace('Copying native assets done.');
}
}
| flutter/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets.dart",
"repo_id": "flutter",
"token_count": 4656
} | 743 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:meta/meta.dart';
import 'package:yaml/yaml.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../runner/flutter_command.dart';
import 'gen_l10n_types.dart';
import 'language_subtag_registry.dart';
typedef HeaderGenerator = String Function(String regenerateInstructions);
typedef ConstructorGenerator = String Function(LocaleInfo locale);
int sortFilesByPath (File a, File b) {
return a.path.compareTo(b.path);
}
/// Simple data class to hold parsed locale. Does not promise validity of any data.
@immutable
class LocaleInfo implements Comparable<LocaleInfo> {
const LocaleInfo({
required this.languageCode,
required this.scriptCode,
required this.countryCode,
required this.length,
required this.originalString,
});
/// Simple parser. Expects the locale string to be in the form of 'language_script_COUNTRY'
/// where the language is 2 characters, script is 4 characters with the first uppercase,
/// and country is 2-3 characters and all uppercase.
///
/// 'language_COUNTRY' or 'language_script' are also valid. Missing fields will be null.
///
/// When `deriveScriptCode` is true, if [scriptCode] was unspecified, it will
/// be derived from the [languageCode] and [countryCode] if possible.
factory LocaleInfo.fromString(String locale, { bool deriveScriptCode = false }) {
final List<String> codes = locale.split('_'); // [language, script, country]
assert(codes.isNotEmpty && codes.length < 4);
final String languageCode = codes[0];
String? scriptCode;
String? countryCode;
int length = codes.length;
String originalString = locale;
if (codes.length == 2) {
scriptCode = codes[1].length >= 4 ? codes[1] : null;
countryCode = codes[1].length < 4 ? codes[1] : null;
} else if (codes.length == 3) {
scriptCode = codes[1].length > codes[2].length ? codes[1] : codes[2];
countryCode = codes[1].length < codes[2].length ? codes[1] : codes[2];
}
assert(codes[0].isNotEmpty);
assert(countryCode == null || countryCode.isNotEmpty);
assert(scriptCode == null || scriptCode.isNotEmpty);
/// Adds scriptCodes to locales where we are able to assume it to provide
/// finer granularity when resolving locales.
///
/// The basis of the assumptions here are based off of known usage of scripts
/// across various countries. For example, we know Taiwan uses traditional (Hant)
/// script, so it is safe to apply (Hant) to Taiwanese languages.
if (deriveScriptCode && scriptCode == null) {
switch (languageCode) {
case 'zh': {
if (countryCode == null) {
scriptCode = 'Hans';
}
switch (countryCode) {
case 'CN':
case 'SG':
scriptCode = 'Hans';
case 'TW':
case 'HK':
case 'MO':
scriptCode = 'Hant';
}
break;
}
case 'sr': {
if (countryCode == null) {
scriptCode = 'Cyrl';
}
break;
}
}
// Increment length if we were able to assume a scriptCode.
if (scriptCode != null) {
length += 1;
}
// Update the base string to reflect assumed scriptCodes.
originalString = languageCode;
if (scriptCode != null) {
originalString += '_$scriptCode';
}
if (countryCode != null) {
originalString += '_$countryCode';
}
}
return LocaleInfo(
languageCode: languageCode,
scriptCode: scriptCode,
countryCode: countryCode,
length: length,
originalString: originalString,
);
}
final String languageCode;
final String? scriptCode;
final String? countryCode;
final int length; // The number of fields. Ranges from 1-3.
final String originalString; // Original un-parsed locale string.
String camelCase() {
return originalString
.split('_')
.map<String>((String part) => part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
.join();
}
@override
bool operator ==(Object other) {
return other is LocaleInfo
&& other.originalString == originalString;
}
@override
int get hashCode => originalString.hashCode;
@override
String toString() {
return originalString;
}
@override
int compareTo(LocaleInfo other) {
return originalString.compareTo(other.originalString);
}
}
// See also //master/tools/gen_locale.dart in the engine repo.
Map<String, List<String>> _parseSection(String section) {
final Map<String, List<String>> result = <String, List<String>>{};
late List<String> lastHeading;
for (final String line in section.split('\n')) {
if (line == '') {
continue;
}
if (line.startsWith(' ')) {
lastHeading[lastHeading.length - 1] = '${lastHeading.last}${line.substring(1)}';
continue;
}
final int colon = line.indexOf(':');
if (colon <= 0) {
throw Exception('not sure how to deal with "$line"');
}
final String name = line.substring(0, colon);
final String value = line.substring(colon + 2);
lastHeading = result.putIfAbsent(name, () => <String>[]);
result[name]!.add(value);
}
return result;
}
final Map<String, String> _languages = <String, String>{};
final Map<String, String> _regions = <String, String>{};
final Map<String, String> _scripts = <String, String>{};
const String kProvincePrefix = ', Province of ';
const String kParentheticalPrefix = ' (';
/// Prepares the data for the [describeLocale] method below.
///
/// The data is obtained from the official IANA registry.
void precacheLanguageAndRegionTags() {
final List<Map<String, List<String>>> sections =
languageSubtagRegistry.split('%%').skip(1).map<Map<String, List<String>>>(_parseSection).toList();
for (final Map<String, List<String>> section in sections) {
assert(section.containsKey('Type'), section.toString());
final String type = section['Type']!.single;
if (type == 'language' || type == 'region' || type == 'script') {
assert(section.containsKey('Subtag') && section.containsKey('Description'), section.toString());
final String subtag = section['Subtag']!.single;
String description = section['Description']!.join(' ');
if (description.startsWith('United ')) {
description = 'the $description';
}
if (description.contains(kParentheticalPrefix)) {
description = description.substring(0, description.indexOf(kParentheticalPrefix));
}
if (description.contains(kProvincePrefix)) {
description = description.substring(0, description.indexOf(kProvincePrefix));
}
if (description.endsWith(' Republic')) {
description = 'the $description';
}
switch (type) {
case 'language':
_languages[subtag] = description;
case 'region':
_regions[subtag] = description;
case 'script':
_scripts[subtag] = description;
}
}
}
}
String describeLocale(String tag) {
final List<String> subtags = tag.split('_');
assert(subtags.isNotEmpty);
final String languageCode = subtags[0];
if (!_languages.containsKey(languageCode)) {
throw L10nException(
'"$languageCode" is not a supported language code.\n'
'See https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry '
'for the supported list.',
);
}
final String language = _languages[languageCode]!;
String output = language;
String? region;
String? script;
if (subtags.length == 2) {
region = _regions[subtags[1]];
script = _scripts[subtags[1]];
assert(region != null || script != null);
} else if (subtags.length >= 3) {
region = _regions[subtags[2]];
script = _scripts[subtags[1]];
assert(region != null && script != null);
}
if (region != null) {
output += ', as used in $region';
}
if (script != null) {
output += ', using the $script script';
}
return output;
}
/// Return the input string as a Dart-parsable string.
///
/// ```
/// foo => 'foo'
/// foo "bar" => 'foo "bar"'
/// foo 'bar' => "foo 'bar'"
/// foo 'bar' "baz" => '''foo 'bar' "baz"'''
/// ```
///
/// This function is used by tools that take in a JSON-formatted file to
/// generate Dart code. For this reason, characters with special meaning
/// in JSON files are escaped. For example, the backspace character (\b)
/// has to be properly escaped by this function so that the generated
/// Dart code correctly represents this character:
/// ```
/// foo\bar => 'foo\\bar'
/// foo\nbar => 'foo\\nbar'
/// foo\\nbar => 'foo\\\\nbar'
/// foo\\bar => 'foo\\\\bar'
/// foo\ bar => 'foo\\ bar'
/// foo$bar = 'foo\$bar'
/// ```
String generateString(String value) {
const String backslash = '__BACKSLASH__';
assert(
!value.contains(backslash),
'Input string cannot contain the sequence: '
'"__BACKSLASH__", as it is used as part of '
'backslash character processing.'
);
value = value
// Replace backslashes with a placeholder for now to properly parse
// other special characters.
.replaceAll(r'\', backslash)
.replaceAll(r'$', r'\$')
.replaceAll("'", r"\'")
.replaceAll('"', r'\"')
.replaceAll('\n', r'\n')
.replaceAll('\f', r'\f')
.replaceAll('\t', r'\t')
.replaceAll('\r', r'\r')
.replaceAll('\b', r'\b')
// Reintroduce escaped backslashes into generated Dart string.
.replaceAll(backslash, r'\\');
return value;
}
/// Given a list of normal strings or interpolated variables, concatenate them
/// into a single dart string to be returned. An example of a normal string
/// would be "'Hello world!'" and an example of a interpolated variable would be
/// "'$placeholder'".
///
/// Each of the strings in [expressions] should be a raw string, which, if it
/// were to be added to a dart file, would be a properly formatted dart string
/// with escapes and/or interpolation. The purpose of this function is to
/// concatenate these dart strings into a single dart string which can be
/// returned in the generated localization files.
///
/// The following rules describe the kinds of string expressions that can be
/// handled:
/// 1. If [expressions] is empty, return the empty string "''".
/// 2. If [expressions] has only one [String] which is an interpolated variable,
/// it is converted to the variable itself e.g. ["'$expr'"] -> "expr".
/// 3. If one string in [expressions] is an interpolation and the next begins
/// with an alphanumeric character, then the former interpolation should be
/// wrapped in braces e.g. ["'$expr1'", "'another'"] -> "'${expr1}another'".
String generateReturnExpr(List<String> expressions, { bool isSingleStringVar = false }) {
if (expressions.isEmpty) {
return "''";
} else if (isSingleStringVar) {
// If our expression is "$varName" where varName is a String, this is equivalent to just varName.
return expressions[0].substring(1);
} else {
final String string = expressions.reversed.fold<String>('', (String string, String expression) {
if (expression[0] != r'$') {
return expression + string;
}
final RegExp alphanumeric = RegExp(r'^([0-9a-zA-Z]|_)+$');
if (alphanumeric.hasMatch(expression.substring(1)) && !(string.isNotEmpty && alphanumeric.hasMatch(string[0]))) {
return '$expression$string';
} else {
return '\${${expression.substring(1)}}$string';
}
});
return "'$string'";
}
}
/// Typed configuration from the localizations config file.
class LocalizationOptions {
LocalizationOptions({
required this.arbDir,
this.outputDir,
String? templateArbFile,
String? outputLocalizationFile,
this.untranslatedMessagesFile,
String? outputClass,
this.preferredSupportedLocales,
this.header,
this.headerFile,
bool? useDeferredLoading,
this.genInputsAndOutputsList,
bool? syntheticPackage,
this.projectDir,
bool? requiredResourceAttributes,
bool? nullableGetter,
bool? format,
bool? useEscaping,
bool? suppressWarnings,
bool? relaxSyntax,
bool? useNamedParameters,
}) : templateArbFile = templateArbFile ?? 'app_en.arb',
outputLocalizationFile = outputLocalizationFile ?? 'app_localizations.dart',
outputClass = outputClass ?? 'AppLocalizations',
useDeferredLoading = useDeferredLoading ?? false,
syntheticPackage = syntheticPackage ?? true,
requiredResourceAttributes = requiredResourceAttributes ?? false,
nullableGetter = nullableGetter ?? true,
format = format ?? false,
useEscaping = useEscaping ?? false,
suppressWarnings = suppressWarnings ?? false,
relaxSyntax = relaxSyntax ?? false,
useNamedParameters = useNamedParameters ?? false;
/// The `--arb-dir` argument.
///
/// The directory where all input localization files should reside.
final String arbDir;
/// The `--output-dir` argument.
///
/// The directory where all output localization files should be generated.
final String? outputDir;
/// The `--template-arb-file` argument.
///
/// This path is relative to [arbDirectory].
final String templateArbFile;
/// The `--output-localization-file` argument.
///
/// This path is relative to [arbDir].
final String outputLocalizationFile;
/// The `--untranslated-messages-file` argument.
///
/// This path is relative to [arbDir].
final String? untranslatedMessagesFile;
/// The `--output-class` argument.
final String outputClass;
/// The `--preferred-supported-locales` argument.
final List<String>? preferredSupportedLocales;
/// The `--header` argument.
///
/// The header to prepend to the generated Dart localizations.
final String? header;
/// The `--header-file` argument.
///
/// A file containing the header to prepend to the generated
/// Dart localizations.
final String? headerFile;
/// The `--use-deferred-loading` argument.
///
/// Whether to generate the Dart localization file with locales imported
/// as deferred.
final bool useDeferredLoading;
/// The `--gen-inputs-and-outputs-list` argument.
///
/// This path is relative to [arbDir].
final String? genInputsAndOutputsList;
/// The `--synthetic-package` argument.
///
/// Whether to generate the Dart localization files in a synthetic package
/// or in a custom directory.
final bool syntheticPackage;
/// The `--project-dir` argument.
///
/// This path is relative to [arbDir].
final String? projectDir;
/// The `required-resource-attributes` argument.
///
/// Whether to require all resource ids to contain a corresponding
/// resource attribute.
final bool requiredResourceAttributes;
/// The `nullable-getter` argument.
///
/// Whether or not the localizations class getter is nullable.
final bool nullableGetter;
/// The `format` argument.
///
/// Whether or not to format the generated files.
final bool format;
/// The `use-escaping` argument.
///
/// Whether or not the ICU escaping syntax is used.
final bool useEscaping;
/// The `suppress-warnings` argument.
///
/// Whether or not to suppress warnings.
final bool suppressWarnings;
/// The `relax-syntax` argument.
///
/// Whether or not to relax the syntax. When specified, the syntax will be
/// relaxed so that the special character "{" is treated as a string if it is
/// not followed by a valid placeholder and "}" is treated as a string if it
/// does not close any previous "{" that is treated as a special character.
/// This was added in for backward compatibility and is not recommended
/// as it may mask errors.
final bool relaxSyntax;
/// The `use-named-parameters` argument.
///
/// Whether or not to use named parameters for the generated localization
/// methods.
///
/// Defaults to `false`.
final bool useNamedParameters;
}
/// Parse the localizations configuration options from [file].
///
/// Throws [Exception] if any of the contents are invalid. Returns a
/// [LocalizationOptions] with all fields as `null` if the config file exists
/// but is empty.
LocalizationOptions parseLocalizationsOptionsFromYAML({
required File file,
required Logger logger,
required String defaultArbDir,
}) {
final String contents = file.readAsStringSync();
if (contents.trim().isEmpty) {
return LocalizationOptions(arbDir: defaultArbDir);
}
final YamlNode yamlNode;
try {
yamlNode = loadYamlNode(file.readAsStringSync());
} on YamlException catch (err) {
throwToolExit(err.message);
}
if (yamlNode is! YamlMap) {
logger.printError('Expected ${file.path} to contain a map, instead was $yamlNode');
throw Exception();
}
return LocalizationOptions(
arbDir: _tryReadUri(yamlNode, 'arb-dir', logger)?.path ?? defaultArbDir,
outputDir: _tryReadUri(yamlNode, 'output-dir', logger)?.path,
templateArbFile: _tryReadUri(yamlNode, 'template-arb-file', logger)?.path,
outputLocalizationFile: _tryReadUri(yamlNode, 'output-localization-file', logger)?.path,
untranslatedMessagesFile: _tryReadUri(yamlNode, 'untranslated-messages-file', logger)?.path,
outputClass: _tryReadString(yamlNode, 'output-class', logger),
header: _tryReadString(yamlNode, 'header', logger),
headerFile: _tryReadUri(yamlNode, 'header-file', logger)?.path,
useDeferredLoading: _tryReadBool(yamlNode, 'use-deferred-loading', logger),
preferredSupportedLocales: _tryReadStringList(yamlNode, 'preferred-supported-locales', logger),
syntheticPackage: _tryReadBool(yamlNode, 'synthetic-package', logger),
requiredResourceAttributes: _tryReadBool(yamlNode, 'required-resource-attributes', logger),
nullableGetter: _tryReadBool(yamlNode, 'nullable-getter', logger),
format: _tryReadBool(yamlNode, 'format', logger),
useEscaping: _tryReadBool(yamlNode, 'use-escaping', logger),
suppressWarnings: _tryReadBool(yamlNode, 'suppress-warnings', logger),
relaxSyntax: _tryReadBool(yamlNode, 'relax-syntax', logger),
useNamedParameters: _tryReadBool(yamlNode, 'use-named-parameters', logger),
);
}
/// Parse the localizations configuration from [FlutterCommand].
LocalizationOptions parseLocalizationsOptionsFromCommand({
required FlutterCommand command,
required String defaultArbDir,
}) {
return LocalizationOptions(
arbDir: command.stringArg('arb-dir') ?? defaultArbDir,
outputDir: command.stringArg('output-dir'),
outputLocalizationFile: command.stringArg('output-localization-file'),
templateArbFile: command.stringArg('template-arb-file'),
untranslatedMessagesFile: command.stringArg('untranslated-messages-file'),
outputClass: command.stringArg('output-class'),
header: command.stringArg('header'),
headerFile: command.stringArg('header-file'),
useDeferredLoading: command.boolArg('use-deferred-loading'),
genInputsAndOutputsList: command.stringArg('gen-inputs-and-outputs-list'),
syntheticPackage: command.boolArg('synthetic-package'),
projectDir: command.stringArg('project-dir'),
requiredResourceAttributes: command.boolArg('required-resource-attributes'),
nullableGetter: command.boolArg('nullable-getter'),
format: command.boolArg('format'),
useEscaping: command.boolArg('use-escaping'),
suppressWarnings: command.boolArg('suppress-warnings'),
useNamedParameters: command.boolArg('use-named-parameters'),
);
}
// Try to read a `bool` value or null from `yamlMap`, otherwise throw.
bool? _tryReadBool(YamlMap yamlMap, String key, Logger logger) {
final Object? value = yamlMap[key];
if (value == null) {
return null;
}
if (value is! bool) {
logger.printError('Expected "$key" to have a bool value, instead was "$value"');
throw Exception();
}
return value;
}
// Try to read a `String` value or null from `yamlMap`, otherwise throw.
String? _tryReadString(YamlMap yamlMap, String key, Logger logger) {
final Object? value = yamlMap[key];
if (value == null) {
return null;
}
if (value is! String) {
logger.printError('Expected "$key" to have a String value, instead was "$value"');
throw Exception();
}
return value;
}
List<String>? _tryReadStringList(YamlMap yamlMap, String key, Logger logger) {
final Object? value = yamlMap[key];
if (value == null) {
return null;
}
if (value is String) {
return <String>[value];
}
if (value is Iterable) {
return value.map((dynamic e) => e.toString()).toList();
}
logger.printError('"$value" must be String or List.');
throw Exception();
}
// Try to read a valid `Uri` or null from `yamlMap`, otherwise throw.
Uri? _tryReadUri(YamlMap yamlMap, String key, Logger logger) {
final String? value = _tryReadString(yamlMap, key, logger);
if (value == null) {
return null;
}
final Uri? uri = Uri.tryParse(value);
if (uri == null) {
logger.printError('"$value" must be a relative file URI');
}
return uri;
}
| flutter/packages/flutter_tools/lib/src/localizations/localizations_utils.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/localizations/localizations_utils.dart",
"repo_id": "flutter",
"token_count": 7226
} | 744 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:multicast_dns/multicast_dns.dart';
import 'package:unified_analytics/unified_analytics.dart';
import 'base/common.dart';
import 'base/context.dart';
import 'base/io.dart';
import 'base/logger.dart';
import 'build_info.dart';
import 'convert.dart';
import 'device.dart';
import 'reporting/reporting.dart';
/// A wrapper around [MDnsClient] to find a Dart VM Service instance.
class MDnsVmServiceDiscovery {
/// Creates a new [MDnsVmServiceDiscovery] object.
///
/// The [_client] parameter will be defaulted to a new [MDnsClient] if null.
MDnsVmServiceDiscovery({
MDnsClient? mdnsClient,
MDnsClient? preliminaryMDnsClient,
required Logger logger,
required Usage flutterUsage,
required Analytics analytics,
}) : _client = mdnsClient ?? MDnsClient(),
_preliminaryClient = preliminaryMDnsClient,
_logger = logger,
_flutterUsage = flutterUsage,
_analytics = analytics;
final MDnsClient _client;
// Used when discovering VM services with `queryForAttach` to do a preliminary
// check for already running services so that results are not cached in _client.
final MDnsClient? _preliminaryClient;
final Logger _logger;
final Usage _flutterUsage;
final Analytics _analytics;
@visibleForTesting
static const String dartVmServiceName = '_dartVmService._tcp.local';
static MDnsVmServiceDiscovery? get instance => context.get<MDnsVmServiceDiscovery>();
/// Executes an mDNS query for Dart VM Services.
/// Checks for services that have already been launched.
/// If none are found, it will listen for new services to become active
/// and return the first it finds that match the parameters.
///
/// The [applicationId] parameter may be used to specify which application
/// to find. For Android, it refers to the package name; on iOS, it refers to
/// the bundle ID.
///
/// The [deviceVmservicePort] parameter may be used to specify which port
/// to find.
///
/// The [useDeviceIPAsHost] parameter flags whether to get the device IP
/// and the [ipv6] parameter flags whether to get an iPv6 address
/// (otherwise it will get iPv4).
///
/// The [timeout] parameter determines how long to continue to wait for
/// services to become active.
///
/// If [applicationId] is not null, this method will find the port and authentication code
/// of the Dart VM Service for that application. If it cannot find a service matching
/// that application identifier after the [timeout], it will call [throwToolExit].
///
/// If [applicationId] is null and there are multiple Dart VM Services available,
/// the user will be prompted with a list of available services with the respective
/// app-id and device-vmservice-port to use and asked to select one.
///
/// If it is null and there is only one available or it's the first found instance
/// of Dart VM Service, it will return that instance's information regardless of
/// what application the service instance is for.
@visibleForTesting
Future<MDnsVmServiceDiscoveryResult?> queryForAttach({
String? applicationId,
int? deviceVmservicePort,
bool ipv6 = false,
bool useDeviceIPAsHost = false,
Duration timeout = const Duration(minutes: 10),
}) async {
// Poll for 5 seconds to see if there are already services running.
// Use a new instance of MDnsClient so results don't get cached in _client.
// If no results are found, poll for a longer duration to wait for connections.
// If more than 1 result is found, throw an error since it can't be determined which to pick.
// If only one is found, return it.
final List<MDnsVmServiceDiscoveryResult> results = await _pollingVmService(
_preliminaryClient ?? MDnsClient(),
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: ipv6,
useDeviceIPAsHost: useDeviceIPAsHost,
timeout: const Duration(seconds: 5),
);
if (results.isEmpty) {
return firstMatchingVmService(
_client,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: ipv6,
useDeviceIPAsHost: useDeviceIPAsHost,
timeout: timeout,
);
} else if (results.length > 1) {
final StringBuffer buffer = StringBuffer();
buffer.writeln('There are multiple Dart VM Services available.');
buffer.writeln('Rerun this command with one of the following passed in as the app-id and device-vmservice-port:');
buffer.writeln();
for (final MDnsVmServiceDiscoveryResult result in results) {
buffer.writeln(
' flutter attach --app-id "${result.domainName.replaceAll('.$dartVmServiceName', '')}" --device-vmservice-port ${result.port}');
}
throwToolExit(buffer.toString());
}
return results.first;
}
/// Executes an mDNS query for Dart VM Services.
/// Listens for new services to become active and returns the first it finds that
/// match the parameters.
///
/// The [applicationId] parameter must be set to specify which application
/// to find. For Android, it refers to the package name; on iOS, it refers to
/// the bundle ID.
///
/// The [deviceVmservicePort] parameter must be set to specify which port
/// to find.
///
/// [applicationId] and either [deviceVmservicePort] or [deviceName] are
/// required for launch so that if multiple flutter apps are running on
/// different devices, it will only match with the device running the desired app.
///
/// The [useDeviceIPAsHost] parameter flags whether to get the device IP
/// and the [ipv6] parameter flags whether to get an iPv6 address
/// (otherwise it will get iPv4).
///
/// The [timeout] parameter determines how long to continue to wait for
/// services to become active.
///
/// If a Dart VM Service matching the [applicationId] and
/// [deviceVmservicePort]/[deviceName] cannot be found before the [timeout]
/// is reached, it will call [throwToolExit].
@visibleForTesting
Future<MDnsVmServiceDiscoveryResult?> queryForLaunch({
required String applicationId,
int? deviceVmservicePort,
String? deviceName,
bool ipv6 = false,
bool useDeviceIPAsHost = false,
Duration timeout = const Duration(minutes: 10),
}) async {
// Either the device port or the device name must be provided.
assert(deviceVmservicePort != null || deviceName != null);
// Query for a specific application matching on either device port or device name.
return firstMatchingVmService(
_client,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
deviceName: deviceName,
ipv6: ipv6,
useDeviceIPAsHost: useDeviceIPAsHost,
timeout: timeout,
);
}
/// Polls for Dart VM Services and returns the first it finds that match
/// the [applicationId]/[deviceVmservicePort] (if applicable).
/// Returns null if no results are found.
@visibleForTesting
Future<MDnsVmServiceDiscoveryResult?> firstMatchingVmService(
MDnsClient client, {
String? applicationId,
int? deviceVmservicePort,
String? deviceName,
bool ipv6 = false,
bool useDeviceIPAsHost = false,
Duration timeout = const Duration(minutes: 10),
}) async {
final List<MDnsVmServiceDiscoveryResult> results = await _pollingVmService(
client,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
deviceName: deviceName,
ipv6: ipv6,
useDeviceIPAsHost: useDeviceIPAsHost,
timeout: timeout,
quitOnFind: true,
);
if (results.isEmpty) {
return null;
}
return results.first;
}
Future<List<MDnsVmServiceDiscoveryResult>> _pollingVmService(
MDnsClient client, {
String? applicationId,
int? deviceVmservicePort,
String? deviceName,
bool ipv6 = false,
bool useDeviceIPAsHost = false,
required Duration timeout,
bool quitOnFind = false,
}) async {
_logger.printTrace('Checking for advertised Dart VM Services...');
try {
await client.start();
final List<MDnsVmServiceDiscoveryResult> results =
<MDnsVmServiceDiscoveryResult>[];
// uniqueDomainNames is used to track all domain names of Dart VM services
// It is later used in this function to determine whether or not to throw an error.
// We do not want to throw the error if it was unable to find any domain
// names because that indicates it may be a problem with mDNS, which has
// a separate error message in _checkForIPv4LinkLocal.
final Set<String> uniqueDomainNames = <String>{};
// uniqueDomainNamesInResults is used to filter out duplicates with exactly
// the same domain name from the results.
final Set<String> uniqueDomainNamesInResults = <String>{};
// Listen for mDNS connections until timeout.
final Stream<PtrResourceRecord> ptrResourceStream = client.lookup<PtrResourceRecord>(
ResourceRecordQuery.serverPointer(dartVmServiceName),
timeout: timeout
);
await for (final PtrResourceRecord ptr in ptrResourceStream) {
uniqueDomainNames.add(ptr.domainName);
String? domainName;
if (applicationId != null) {
// If applicationId is set, only use records that match it
if (ptr.domainName.toLowerCase().startsWith(applicationId.toLowerCase())) {
domainName = ptr.domainName;
} else {
continue;
}
} else {
domainName = ptr.domainName;
}
// Result with same domain name was already found, skip it.
if (uniqueDomainNamesInResults.contains(domainName)) {
continue;
}
_logger.printTrace('Checking for available port on $domainName');
final List<SrvResourceRecord> srvRecords = await client
.lookup<SrvResourceRecord>(
ResourceRecordQuery.service(domainName),
)
.toList();
if (srvRecords.isEmpty) {
continue;
}
// If more than one SrvResourceRecord found, it should just be a duplicate.
final SrvResourceRecord srvRecord = srvRecords.first;
if (srvRecords.length > 1) {
_logger.printWarning(
'Unexpectedly found more than one Dart VM Service report for $domainName '
'- using first one (${srvRecord.port}).');
}
// If deviceVmservicePort is set, only use records that match it
if (deviceVmservicePort != null && srvRecord.port != deviceVmservicePort) {
continue;
}
// If deviceName is set, only use records that match it
if (deviceName != null && !deviceNameMatchesTargetName(deviceName, srvRecord.target)) {
continue;
}
// Get the IP address of the device if using the IP as the host.
InternetAddress? ipAddress;
if (useDeviceIPAsHost) {
List<IPAddressResourceRecord> ipAddresses = await client
.lookup<IPAddressResourceRecord>(
ipv6
? ResourceRecordQuery.addressIPv6(srvRecord.target)
: ResourceRecordQuery.addressIPv4(srvRecord.target),
)
.toList();
if (ipAddresses.isEmpty) {
throwToolExit('Did not find IP for service ${srvRecord.target}.');
}
// Filter out link-local addresses.
if (ipAddresses.length > 1) {
ipAddresses = ipAddresses.where((IPAddressResourceRecord element) => !element.address.isLinkLocal).toList();
}
ipAddress = ipAddresses.first.address;
if (ipAddresses.length > 1) {
_logger.printWarning(
'Unexpectedly found more than one IP for Dart VM Service ${srvRecord.target} '
'- using first one ($ipAddress).');
}
}
_logger.printTrace('Checking for authentication code for $domainName');
final List<TxtResourceRecord> txt = await client
.lookup<TxtResourceRecord>(
ResourceRecordQuery.text(domainName),
)
.toList();
String authCode = '';
if (txt.isNotEmpty) {
authCode = _getAuthCode(txt.first.text);
}
results.add(MDnsVmServiceDiscoveryResult(
domainName,
srvRecord.port,
authCode,
ipAddress: ipAddress
));
uniqueDomainNamesInResults.add(domainName);
if (quitOnFind) {
return results;
}
}
// If applicationId is set and quitOnFind is true and no results matching
// the applicationId were found but other results were found, throw an error.
if (applicationId != null &&
quitOnFind &&
results.isEmpty &&
uniqueDomainNames.isNotEmpty) {
String message = 'Did not find a Dart VM Service advertised for $applicationId';
if (deviceVmservicePort != null) {
message += ' on port $deviceVmservicePort';
}
throwToolExit('$message.');
}
return results;
} finally {
client.stop();
}
}
@visibleForTesting
bool deviceNameMatchesTargetName(String deviceName, String targetName) {
// Remove `.local` from the name along with any non-word, non-digit characters.
final RegExp cleanedNameRegex = RegExp(r'\.local|\W');
final String cleanedDeviceName = deviceName.trim().toLowerCase().replaceAll(cleanedNameRegex, '');
final String cleanedTargetName = targetName.toLowerCase().replaceAll(cleanedNameRegex, '');
return cleanedDeviceName == cleanedTargetName;
}
String _getAuthCode(String txtRecord) {
const String authCodePrefix = 'authCode=';
final Iterable<String> matchingRecords =
LineSplitter.split(txtRecord).where((String record) => record.startsWith(authCodePrefix));
if (matchingRecords.isEmpty) {
return '';
}
String authCode = matchingRecords.first.substring(authCodePrefix.length);
// The Dart VM Service currently expects a trailing '/' as part of the
// URI, otherwise an invalid authentication code response is given.
if (!authCode.endsWith('/')) {
authCode += '/';
}
return authCode;
}
/// Gets Dart VM Service Uri for `flutter attach`.
/// Executes an mDNS query and waits until a Dart VM Service is found.
///
/// When [useDeviceIPAsHost] is true, it will use the device's IP as the
/// host and will not forward the port.
///
/// Differs from [getVMServiceUriForLaunch] because it can search for any available Dart VM Service.
/// Since [applicationId] and [deviceVmservicePort] are optional, it can either look for any service
/// or a specific service matching [applicationId]/[deviceVmservicePort].
/// It may find more than one service, which will throw an error listing the found services.
Future<Uri?> getVMServiceUriForAttach(
String? applicationId,
Device device, {
bool usesIpv6 = false,
int? hostVmservicePort,
int? deviceVmservicePort,
bool useDeviceIPAsHost = false,
Duration timeout = const Duration(minutes: 10),
}) async {
final MDnsVmServiceDiscoveryResult? result = await queryForAttach(
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: usesIpv6,
useDeviceIPAsHost: useDeviceIPAsHost,
timeout: timeout,
);
return _handleResult(
result,
device,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
hostVmservicePort: hostVmservicePort,
usesIpv6: usesIpv6,
useDeviceIPAsHost: useDeviceIPAsHost
);
}
/// Gets Dart VM Service Uri for `flutter run`.
/// Executes an mDNS query and waits until the Dart VM Service service is found.
///
/// When [useDeviceIPAsHost] is true, it will use the device's IP as the
/// host and will not forward the port.
///
/// Differs from [getVMServiceUriForAttach] because it only searches for a specific service.
/// This is enforced by [applicationId] being required and using either the
/// [deviceVmservicePort] or the [device]'s name to query.
Future<Uri?> getVMServiceUriForLaunch(
String applicationId,
Device device, {
bool usesIpv6 = false,
int? hostVmservicePort,
int? deviceVmservicePort,
bool useDeviceIPAsHost = false,
Duration timeout = const Duration(minutes: 10),
}) async {
final MDnsVmServiceDiscoveryResult? result = await queryForLaunch(
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
deviceName: deviceVmservicePort == null ? device.name : null,
ipv6: usesIpv6,
useDeviceIPAsHost: useDeviceIPAsHost,
timeout: timeout,
);
return _handleResult(
result,
device,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
hostVmservicePort: hostVmservicePort,
usesIpv6: usesIpv6,
useDeviceIPAsHost: useDeviceIPAsHost
);
}
Future<Uri?> _handleResult(
MDnsVmServiceDiscoveryResult? result,
Device device, {
String? applicationId,
int? deviceVmservicePort,
int? hostVmservicePort,
bool usesIpv6 = false,
bool useDeviceIPAsHost = false,
}) async {
if (result == null) {
await _checkForIPv4LinkLocal(device);
return null;
}
final String host;
final InternetAddress? ipAddress = result.ipAddress;
if (useDeviceIPAsHost && ipAddress != null) {
host = ipAddress.address;
} else {
host = usesIpv6
? InternetAddress.loopbackIPv6.address
: InternetAddress.loopbackIPv4.address;
}
return buildVMServiceUri(
device,
host,
result.port,
hostVmservicePort,
result.authCode,
useDeviceIPAsHost,
);
}
// If there's not an ipv4 link local address in `NetworkInterfaces.list`,
// then request user interventions with a `printError()` if possible.
Future<void> _checkForIPv4LinkLocal(Device device) async {
_logger.printTrace(
'mDNS query failed. Checking for an interface with a ipv4 link local address.'
);
final List<NetworkInterface> interfaces = await listNetworkInterfaces(
includeLinkLocal: true,
type: InternetAddressType.IPv4,
);
if (_logger.isVerbose) {
_logInterfaces(interfaces);
}
final bool hasIPv4LinkLocal = interfaces.any(
(NetworkInterface interface) => interface.addresses.any(
(InternetAddress address) => address.isLinkLocal,
),
);
if (hasIPv4LinkLocal) {
_logger.printTrace('An interface with an ipv4 link local address was found.');
return;
}
final TargetPlatform targetPlatform = await device.targetPlatform;
switch (targetPlatform) {
case TargetPlatform.ios:
UsageEvent('ios-mdns', 'no-ipv4-link-local', flutterUsage: _flutterUsage).send();
_analytics.send(Event.appleUsageEvent(workflow: 'ios-mdns', parameter: 'no-ipv4-link-local'));
_logger.printError(
'The mDNS query for an attached iOS device failed. It may '
'be necessary to disable the "Personal Hotspot" on the device, and '
'to ensure that the "Disable unless needed" setting is unchecked '
'under System Preferences > Network > iPhone USB. '
'See https://github.com/flutter/flutter/issues/46698 for details.'
);
case TargetPlatform.android:
case TargetPlatform.android_arm:
case TargetPlatform.android_arm64:
case TargetPlatform.android_x64:
case TargetPlatform.android_x86:
case TargetPlatform.darwin:
case TargetPlatform.fuchsia_arm64:
case TargetPlatform.fuchsia_x64:
case TargetPlatform.linux_arm64:
case TargetPlatform.linux_x64:
case TargetPlatform.tester:
case TargetPlatform.web_javascript:
case TargetPlatform.windows_x64:
case TargetPlatform.windows_arm64:
_logger.printTrace('No interface with an ipv4 link local address was found.');
}
}
void _logInterfaces(List<NetworkInterface> interfaces) {
for (final NetworkInterface interface in interfaces) {
if (_logger.isVerbose) {
_logger.printTrace('Found interface "${interface.name}":');
for (final InternetAddress address in interface.addresses) {
final String linkLocal = address.isLinkLocal ? 'link local' : '';
_logger.printTrace('\tBound address: "${address.address}" $linkLocal');
}
}
}
}
}
class MDnsVmServiceDiscoveryResult {
MDnsVmServiceDiscoveryResult(
this.domainName,
this.port,
this.authCode, {
this.ipAddress
});
final String domainName;
final int port;
final String authCode;
final InternetAddress? ipAddress;
}
Future<Uri> buildVMServiceUri(
Device device,
String host,
int devicePort, [
int? hostVmservicePort,
String? authCode,
bool useDeviceIPAsHost = false,
]) async {
String path = '/';
if (authCode != null) {
path = authCode;
}
// Not having a trailing slash can cause problems in some situations.
// Ensure that there's one present.
if (!path.endsWith('/')) {
path += '/';
}
hostVmservicePort ??= 0;
final int? actualHostPort;
if (useDeviceIPAsHost) {
// When using the device's IP as the host, port forwarding is not required
// so just use the device's port.
actualHostPort = devicePort;
} else {
actualHostPort = hostVmservicePort == 0 ?
await device.portForwarder?.forward(devicePort) :
hostVmservicePort;
}
return Uri(scheme: 'http', host: host, port: actualHostPort, path: path);
}
| flutter/packages/flutter_tools/lib/src/mdns_discovery.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/mdns_discovery.dart",
"repo_id": "flutter",
"token_count": 7913
} | 745 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
enum StatusProjectValidator {
error,
warning,
success,
crash,
info,
}
class ProjectValidatorResult {
const ProjectValidatorResult({
required this.name,
required this.value,
required this.status,
this.warning,
});
final String name;
final String value;
final String? warning;
final StatusProjectValidator status;
@override
String toString() {
if (warning != null) {
return '$name: $value (warning: $warning)';
}
return '$name: $value';
}
static ProjectValidatorResult crash(Object exception, StackTrace trace) {
return ProjectValidatorResult(
name: exception.toString(),
value: trace.toString(),
status: StatusProjectValidator.crash
);
}
}
| flutter/packages/flutter_tools/lib/src/project_validator_result.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/project_validator_result.dart",
"repo_id": "flutter",
"token_count": 301
} | 746 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:browser_launcher/browser_launcher.dart';
import 'package:meta/meta.dart';
import 'base/logger.dart';
import 'build_info.dart';
import 'resident_runner.dart';
import 'vmservice.dart';
typedef ResidentDevtoolsHandlerFactory = ResidentDevtoolsHandler Function(DevtoolsLauncher?, ResidentRunner, Logger);
ResidentDevtoolsHandler createDefaultHandler(DevtoolsLauncher? launcher, ResidentRunner runner, Logger logger) {
return FlutterResidentDevtoolsHandler(launcher, runner, logger);
}
/// Helper class to manage the life-cycle of devtools and its interaction with
/// the resident runner.
abstract class ResidentDevtoolsHandler {
/// The current devtools server, or null if one is not running.
DevToolsServerAddress? get activeDevToolsServer;
/// Whether it's ok to announce the [activeDevToolsServer].
///
/// This should only return true once all the devices have been notified
/// of the DevTools.
bool get readyToAnnounce;
Future<void> hotRestart(List<FlutterDevice?> flutterDevices);
Future<void> serveAndAnnounceDevTools({
Uri? devToolsServerAddress,
required List<FlutterDevice?> flutterDevices,
bool isStartPaused = false,
});
bool launchDevToolsInBrowser({required List<FlutterDevice?> flutterDevices});
Future<void> shutdown();
}
class FlutterResidentDevtoolsHandler implements ResidentDevtoolsHandler {
FlutterResidentDevtoolsHandler(this._devToolsLauncher, this._residentRunner, this._logger);
static const Duration launchInBrowserTimeout = Duration(seconds: 15);
final DevtoolsLauncher? _devToolsLauncher;
final ResidentRunner _residentRunner;
final Logger _logger;
bool _shutdown = false;
bool _served = false;
@visibleForTesting
bool launchedInBrowser = false;
@override
DevToolsServerAddress? get activeDevToolsServer {
assert(!_readyToAnnounce || _devToolsLauncher?.activeDevToolsServer != null);
return _devToolsLauncher?.activeDevToolsServer;
}
@override
bool get readyToAnnounce => _readyToAnnounce;
bool _readyToAnnounce = false;
// This must be guaranteed not to return a Future that fails.
@override
Future<void> serveAndAnnounceDevTools({
Uri? devToolsServerAddress,
required List<FlutterDevice?> flutterDevices,
bool isStartPaused = false,
}) async {
assert(!_readyToAnnounce);
if (!_residentRunner.supportsServiceProtocol || _devToolsLauncher == null) {
return;
}
if (devToolsServerAddress != null) {
_devToolsLauncher.devToolsUrl = devToolsServerAddress;
} else {
await _devToolsLauncher.serve();
_served = true;
}
await _devToolsLauncher.ready;
// Do not attempt to print debugger list if the connection has failed or if we're shutting down.
if (_devToolsLauncher.activeDevToolsServer == null || _shutdown) {
assert(!_readyToAnnounce);
return;
}
final Uri? devToolsUrl = _devToolsLauncher.devToolsUrl;
if (devToolsUrl != null) {
for (final FlutterDevice? device in flutterDevices) {
if (device == null) {
continue;
}
// Notify the DDS instances that there's a DevTools instance available so they can correctly
// redirect DevTools related requests.
device.device?.dds.setExternalDevToolsUri(devToolsUrl);
}
}
Future<void> callServiceExtensions() async {
final List<FlutterDevice?> devicesWithExtension = await _devicesWithExtensions(flutterDevices);
await Future.wait(
<Future<void>>[
_maybeCallDevToolsUriServiceExtension(devicesWithExtension),
_callConnectedVmServiceUriExtension(devicesWithExtension)
]
);
}
// If the application is starting paused, we can't invoke service extensions
// as they're handled on the target app's paused isolate. Since invoking
// service extensions will block in this situation, we should wait to invoke
// them until after we've output the DevTools connection details.
if (!isStartPaused) {
await callServiceExtensions();
}
// This check needs to happen after the possible asynchronous call above,
// otherwise a shutdown event might be missed and the DevTools launcher may
// no longer be initialized.
if (_shutdown) {
// If we're shutting down, no point reporting the debugger list.
return;
}
_readyToAnnounce = true;
assert(_devToolsLauncher.activeDevToolsServer != null);
if (_residentRunner.reportedDebuggers) {
// Since the DevTools only just became available, we haven't had a chance to
// report their URLs yet. Do so now.
_residentRunner.printDebuggerList(includeVmService: false);
}
if (isStartPaused) {
await callServiceExtensions();
}
}
// This must be guaranteed not to return a Future that fails.
@override
bool launchDevToolsInBrowser({required List<FlutterDevice?> flutterDevices}) {
if (!_residentRunner.supportsServiceProtocol || _devToolsLauncher == null) {
return false;
}
if (_devToolsLauncher.devToolsUrl == null) {
_logger.startProgress('Waiting for Flutter DevTools to be served...');
unawaited(_devToolsLauncher.ready.then((_) {
_launchDevToolsForDevices(flutterDevices);
}));
} else {
_launchDevToolsForDevices(flutterDevices);
}
return true;
}
void _launchDevToolsForDevices(List<FlutterDevice?> flutterDevices) {
assert(activeDevToolsServer != null);
for (final FlutterDevice? device in flutterDevices) {
final String devToolsUrl = activeDevToolsServer!.uri!.replace(
queryParameters: <String, dynamic>{'uri': '${device!.vmService!.httpAddress}'},
).toString();
_logger.printStatus('Launching Flutter DevTools for ${device.device!.name} at $devToolsUrl');
unawaited(Chrome.start(<String>[devToolsUrl]));
}
launchedInBrowser = true;
}
Future<void> _maybeCallDevToolsUriServiceExtension(
List<FlutterDevice?> flutterDevices,
) async {
if (_devToolsLauncher?.activeDevToolsServer == null) {
return;
}
await Future.wait(<Future<void>>[
for (final FlutterDevice? device in flutterDevices)
if (device?.vmService != null) _callDevToolsUriExtension(device!),
]);
}
Future<void> _callDevToolsUriExtension(
FlutterDevice device,
) async {
try {
await _invokeRpcOnFirstView(
'ext.flutter.activeDevToolsServerAddress',
device: device,
params: <String, dynamic>{
'value': _devToolsLauncher!.activeDevToolsServer!.uri.toString(),
},
);
} on Exception catch (e) {
_logger.printError(
'Failed to set DevTools server address: $e. Deep links to'
' DevTools will not show in Flutter errors.',
);
}
}
Future<List<FlutterDevice?>> _devicesWithExtensions(List<FlutterDevice?> flutterDevices) async {
return Future.wait(<Future<FlutterDevice?>>[
for (final FlutterDevice? device in flutterDevices) _waitForExtensionsForDevice(device!),
]);
}
/// Returns null if the service extension cannot be found on the device.
Future<FlutterDevice?> _waitForExtensionsForDevice(FlutterDevice flutterDevice) async {
const String extension = 'ext.flutter.connectedVmServiceUri';
try {
await flutterDevice.vmService?.findExtensionIsolate(
extension,
);
return flutterDevice;
} on VmServiceDisappearedException {
_logger.printTrace(
'The VM Service for ${flutterDevice.device} disappeared while trying to'
' find the $extension service extension. Skipping subsequent DevTools '
'setup for this device.',
);
return null;
}
}
Future<void> _callConnectedVmServiceUriExtension(List<FlutterDevice?> flutterDevices) async {
await Future.wait(<Future<void>>[
for (final FlutterDevice? device in flutterDevices)
if (device?.vmService != null) _callConnectedVmServiceExtension(device!),
]);
}
Future<void> _callConnectedVmServiceExtension(FlutterDevice device) async {
final Uri? uri = device.vmService!.httpAddress ?? device.vmService!.wsAddress;
if (uri == null) {
return;
}
try {
await _invokeRpcOnFirstView(
'ext.flutter.connectedVmServiceUri',
device: device,
params: <String, dynamic>{
'value': uri.toString(),
},
);
} on Exception catch (e) {
_logger.printError(e.toString());
_logger.printError(
'Failed to set vm service URI: $e. Deep links to DevTools'
' will not show in Flutter errors.',
);
}
}
Future<void> _invokeRpcOnFirstView(
String method, {
required FlutterDevice device,
required Map<String, dynamic> params,
}) async {
if (device.targetPlatform == TargetPlatform.web_javascript) {
await device.vmService!.callMethodWrapper(
method,
args: params,
);
return;
}
final List<FlutterView> views = await device.vmService!.getFlutterViews();
if (views.isEmpty) {
return;
}
await device.vmService!.invokeFlutterExtensionRpcRaw(
method,
args: params,
isolateId: views.first.uiIsolate!.id!,
);
}
@override
Future<void> hotRestart(List<FlutterDevice?> flutterDevices) async {
final List<FlutterDevice?> devicesWithExtension = await _devicesWithExtensions(flutterDevices);
await Future.wait(<Future<void>>[
_maybeCallDevToolsUriServiceExtension(devicesWithExtension),
_callConnectedVmServiceUriExtension(devicesWithExtension),
]);
}
@override
Future<void> shutdown() async {
if (_devToolsLauncher == null || _shutdown || !_served) {
return;
}
_shutdown = true;
_readyToAnnounce = false;
await _devToolsLauncher.close();
}
}
@visibleForTesting
NoOpDevtoolsHandler createNoOpHandler(DevtoolsLauncher? launcher, ResidentRunner runner, Logger logger) {
return NoOpDevtoolsHandler();
}
@visibleForTesting
class NoOpDevtoolsHandler implements ResidentDevtoolsHandler {
bool wasShutdown = false;
@override
DevToolsServerAddress? get activeDevToolsServer => null;
@override
bool get readyToAnnounce => false;
@override
Future<void> hotRestart(List<FlutterDevice?> flutterDevices) async {
return;
}
@override
Future<void> serveAndAnnounceDevTools({
Uri? devToolsServerAddress,
List<FlutterDevice?>? flutterDevices,
bool isStartPaused = false,
}) async {
return;
}
@override
bool launchDevToolsInBrowser({List<FlutterDevice?>? flutterDevices}) {
return false;
}
@override
Future<void> shutdown() async {
wasShutdown = true;
return;
}
}
/// Convert a [URI] with query parameters into a display format instead
/// of the default URI encoding.
String urlToDisplayString(Uri uri) {
final StringBuffer base = StringBuffer(uri.replace(
queryParameters: <String, String>{},
).toString());
base.write(uri.queryParameters.keys.map((String key) => '$key=${uri.queryParameters[key]}').join('&'));
return base.toString();
}
| flutter/packages/flutter_tools/lib/src/resident_devtools_handler.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/resident_devtools_handler.dart",
"repo_id": "flutter",
"token_count": 3938
} | 747 |
// 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 '../base/file_system.dart';
import '../globals.dart' as globals;
/// Manages a Font configuration that can be shared across multiple tests.
class FontConfigManager {
Directory? _fontsDirectory;
/// Returns a Font configuration that limits font fallback to the artifact
/// cache directory.
late final File fontConfigFile = (){
final StringBuffer sb = StringBuffer();
sb.writeln('<fontconfig>');
sb.writeln(' <dir>${globals.cache.getCacheArtifacts().path}</dir>');
sb.writeln(' <cachedir>/var/cache/fontconfig</cachedir>');
sb.writeln('</fontconfig>');
if (_fontsDirectory == null) {
_fontsDirectory = globals.fs.systemTempDirectory.createTempSync('flutter_test_fonts.');
globals.printTrace('Using this directory for fonts configuration: ${_fontsDirectory!.path}');
}
final File cachedFontConfig = globals.fs.file('${_fontsDirectory!.path}/fonts.conf');
cachedFontConfig.createSync();
cachedFontConfig.writeAsStringSync(sb.toString());
return cachedFontConfig;
}();
Future<void> dispose() async {
if (_fontsDirectory != null) {
globals.printTrace('Deleting ${_fontsDirectory!.path}...');
try {
await _fontsDirectory!.delete(recursive: true);
} on FileSystemException {
// Silently exit
}
_fontsDirectory = null;
}
}
}
| flutter/packages/flutter_tools/lib/src/test/font_config_manager.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/test/font_config_manager.dart",
"repo_id": "flutter",
"token_count": 532
} | 748 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:process/process.dart';
import '../base/file_system.dart';
import '../base/platform.dart';
import '../doctor_validator.dart';
import 'vscode.dart';
class VsCodeValidator extends DoctorValidator {
VsCodeValidator(this._vsCode) : super(_vsCode.productName);
final VsCode _vsCode;
static Iterable<DoctorValidator> installedValidators(FileSystem fileSystem, Platform platform, ProcessManager processManager) {
return VsCode
.allInstalled(fileSystem, platform, processManager)
.map<DoctorValidator>((VsCode vsCode) => VsCodeValidator(vsCode));
}
@override
Future<ValidationResult> validate() async {
final List<ValidationMessage> validationMessages =
List<ValidationMessage>.from(_vsCode.validationMessages);
final String vsCodeVersionText = _vsCode.version == null
? 'version unknown'
: 'version ${_vsCode.version}';
if (_vsCode.version == null) {
validationMessages.add(const ValidationMessage.error('Unable to determine VS Code version.'));
}
return ValidationResult(
ValidationType.success,
validationMessages,
statusInfo: vsCodeVersionText,
);
}
}
| flutter/packages/flutter_tools/lib/src/vscode/vscode_validator.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/vscode/vscode_validator.dart",
"repo_id": "flutter",
"token_count": 438
} | 749 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:archive/archive.dart';
import '../application_package.dart';
import '../base/file_system.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../cmake.dart';
import '../cmake_project.dart';
import '../globals.dart' as globals;
abstract class WindowsApp extends ApplicationPackage {
WindowsApp({required String projectBundleId}) : super(id: projectBundleId);
/// Creates a new [WindowsApp] from a windows sub project.
factory WindowsApp.fromWindowsProject(WindowsProject project) {
return BuildableWindowsApp(
project: project,
);
}
/// Creates a new [WindowsApp] from an existing executable or a zip archive.
///
/// `applicationBinary` is the path to the executable or the zipped archive.
static WindowsApp? fromPrebuiltApp(FileSystemEntity applicationBinary) {
if (!applicationBinary.existsSync()) {
globals.printError('File "${applicationBinary.path}" does not exist.');
return null;
}
if (applicationBinary.path.endsWith('.exe')) {
return PrebuiltWindowsApp(
executable: applicationBinary.path,
applicationPackage: applicationBinary,
);
}
if (!applicationBinary.path.endsWith('.zip')) {
// Unknown file type
globals.printError('Unknown windows application type.');
return null;
}
// Try to unpack as a zip.
final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_app.');
try {
globals.os.unzip(globals.fs.file(applicationBinary), tempDir);
} on ArchiveException {
globals.printError('Invalid prebuilt Windows app. Unable to extract from archive.');
return null;
}
final List<FileSystemEntity> exeFilesFound = <FileSystemEntity>[];
for (final FileSystemEntity file in tempDir.listSync()) {
if (file.basename.endsWith('.exe')) {
exeFilesFound.add(file);
}
}
if (exeFilesFound.isEmpty) {
globals.printError('Cannot find .exe files in the zip archive.');
return null;
}
if (exeFilesFound.length > 1) {
globals.printError('Archive "${applicationBinary.path}" contains more than one .exe files.');
return null;
}
return PrebuiltWindowsApp(
executable: exeFilesFound.single.path,
applicationPackage: applicationBinary,
);
}
@override
String get displayName => id;
String executable(BuildMode buildMode, TargetPlatform targetPlatform);
}
class PrebuiltWindowsApp extends WindowsApp implements PrebuiltApplicationPackage {
PrebuiltWindowsApp({
required String executable,
required this.applicationPackage,
}) : _executable = executable,
super(projectBundleId: executable);
final String _executable;
@override
String executable(BuildMode buildMode, TargetPlatform targetPlatform) => _executable;
@override
String get name => _executable;
@override
final FileSystemEntity applicationPackage;
}
class BuildableWindowsApp extends WindowsApp {
BuildableWindowsApp({
required this.project,
}) : super(projectBundleId: project.parent.manifest.appName);
final WindowsProject project;
@override
String executable(BuildMode buildMode, TargetPlatform targetPlatform) {
final String? binaryName = getCmakeExecutableName(project);
return globals.fs.path.join(
getWindowsBuildDirectory(targetPlatform),
'runner',
sentenceCase(buildMode.cliName),
'$binaryName.exe',
);
}
@override
String get name => project.parent.manifest.appName;
}
| flutter/packages/flutter_tools/lib/src/windows/application_package.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/windows/application_package.dart",
"repo_id": "flutter",
"token_count": 1221
} | 750 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.